http://stackoverflow.com/comment/91286348
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52167081
has text: my code is supposed to _replace_ your loop, not to be in your loop
score: 0

http://stackoverflow.com/comment/91265732
has text: Added to the original post. @Keith
score: 0
comment on: http://stackoverflow.com/q/52157671
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52260093
has comment: http://stackoverflow.com/comment/91507299
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91469877
has comment: http://stackoverflow.com/comment/91495933
answer count: 0
has body: I have some code that runs simulations and saves the results into text files. To ensure reproducibility, I was also saving the git hash of the last commit , so that if I look a simulation several months later I can know exactly which commit was used to produce the result. Now we are looking into making our code conda-installable. I know I can access the git hast in the conda recipe by using the {{ GIT_FULL_HASH }} env variable; and save it in the about section of my meta.yaml: about: summary: data['description'] description: data['long_description'] githash: {{ GIT_FULL_HASH }} is there a way I can access its value programmatically after the package has been built and installed, so that I can include it on the saved sim data?
has title: Accessing githash of a conda-installed package
type: Question
has comment: http://stackoverflow.com/comment/91476191
has comment: http://stackoverflow.com/comment/91470761
tagged with: conda
tagged with: git-hash
score: 0

http://stackoverflow.com/a/52257411
upvote count: 1
has comment: http://stackoverflow.com/comment/91468103
accepted answer of: http://stackoverflow.com/q/52254747
answers question: http://stackoverflow.com/q/52254747
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91466354
has body: Consider using QuerySet.get_or_create, which shall eliminate the problem above. MyClass.objects.get_or_create(name=some_item) Also, please note, that if you access class inside the @staticmethod it makes sense to update it to be @classmethod. Also, in the question you are having: from django.db import Models instead of from django.db import models
has comment: http://stackoverflow.com/comment/91464658
type: Answer
score: 1

http://stackoverflow.com/q/52144642
tagged with: reinforcement-learning
downvote count: 1
favorite count: 0
upvote count: 5
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/52595841
has answer: http://stackoverflow.com/a/52145089
tagged with: tensorflow
type: Question
has title: Online Learning with Tensorflow
score: 4
has body: My problem is related to building a recommender system. I am using tensorflow to train the model with user_features, item_features and interactions. How can i handle new data? For example, whenever a use clicks on an item, i wanna record that interaction immediately and learn from that interaction (training the model for just that interaction). How can i do this? Current implementation Right now, i am following the traditional method of training the model first and then making predictions from that. In order to handle new interactions, i have to re-initialize the graph and retrain with all the data to make it work. I hope there is some solution for this. Thanks
answer count: 2

http://stackoverflow.com/comment/91386540
type: QuestionComment
has text: Providing a complete code-example for replication would be helpful.
comment on: http://stackoverflow.com/q/52176249
score: 0
type: Comment

http://stackoverflow.com/a/52250015
answers question: http://stackoverflow.com/q/52249884
upvote count: 1
has comment: http://stackoverflow.com/comment/91449868
downvote count: 1
has comment: http://stackoverflow.com/comment/91451627
has comment: http://stackoverflow.com/comment/91451804
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91448300
has comment: http://stackoverflow.com/comment/91451730
has body: Python passes the value of a reference to an object when making a call instead of actually passing the object reference itself. In this case, self is just a local variable with a copy of a reference to the Node object that the get method is bound to, so if you assign to self with something else (self.next in your case), all that happens is for the local variable self to hold a reference to a different object, but the object that self originally referred to, as well as the reference to the object from the caller, remains untouched.
type: Answer
accepted answer of: http://stackoverflow.com/q/52249884

http://stackoverflow.com/q/52137420
has comment: http://stackoverflow.com/comment/91224491
score: 0
tagged with: function
answer count: 1
has comment: http://stackoverflow.com/comment/91224479
tagged with: python-3.x
has body: I got really strange output from following python function: s = "-8.8373347749999997e-08" def roundNumb(numb, pos): print("roundNumb()", numb , pos) ret = "" if int(numb[pos]) &lt; 5: ret = numb[:pos] print("if int(numb[pos]) &lt; 5: ", int(numb[pos]), " ", ret) else: if int(numb[pos]) == 9: ret = roundNumb(numb , pos - 1) print("int(numb[pos]) == 9 ", int(numb[pos]), " ",ret) else: ret = numb[:(pos-1)] + str(int(numb[(pos-1)]) + 1) print("else:", ret) return ret &gt;&gt;&gt; roundNumb(s, 12) roundNumb() -8.8373347749999997e-08 12 roundNumb() -8.8373347749999997e-08 11 if int(numb[pos]) &lt; 5: 4 -8.83733477 int(numb[pos]) == 9 9 -8.83733477 '-8.83733477' as you can see roundNumb function was called twice, but I don't really understand why. It should be ended on first if statement: if int(numb[pos]) &lt; 5:
has comment: http://stackoverflow.com/comment/91224571
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91224562
tagged with: python
has comment: http://stackoverflow.com/comment/91224507
has comment: http://stackoverflow.com/comment/91224483
has title: Strange statement in if function
type: Question
has answer: http://stackoverflow.com/a/52137559
has comment: http://stackoverflow.com/comment/91224644

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

http://stackoverflow.com/q/52196080
answer count: 1
has body: My dataframe named df looks like Dig CUI importance 2240 a123 0.28912 2240 b123 0.39021 2230 x133 0.12923 3330 cak2 0.12903 3330 xa45 0.21093 3330 2429 0.21893 To the above dataframe I am running it through the following code, df = (df.groupby('dig').apply(lambda x: dict(zip(x['cui'],x['importance']))).to_dict()) I am getting an output as {2240:{a123:0.28912, b123:0.39021},2230:{x133:0.12923},3330:{cak2: 0.12903, xa45:0.21093, 2429:0.21893}} But I need columns in my output dictionary.I need suggestions the output should be like {2240:[{cui:a123, importance:0.28912},{cui:b123, importance:0.39021}],2230:[{cui:x133, importance:0.12923},3330:[{cui:cak2, importance:0.12903},{cui:xa45, importance:0.21093},{cui:2429, importance:0.21893}]]} Suggest me ways to do it.
type: UnansweredQuestion
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91341588
tagged with: pandas
has comment: http://stackoverflow.com/comment/91341613
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/52196194
has title: Pandas DataFrame groupby columns to dict
has comment: http://stackoverflow.com/comment/91341568
score: 0

http://stackoverflow.com/a/52202642
has body: If you want to ensure that each object has unique numbers across all instances then you'll need to have each instance check the generated values against a class level set to ensure uniqueness. import random as random class MyClass: class_random_set = set() def __init__(self, lengthOfList): self.my_random_set = set() for _ in range(0, lengthOfList): while True: num = random.uniform(-1.0, 1.0) if num not in self.class_random_set: self.class_random_set.add(num) self.my_random_set.add(num) break a = MyClass(2) #make a set with 2 random numbers b = MyClass(1) #make a set with 1 random number print(a.my_random_set) print(b.my_random_set)
answers question: http://stackoverflow.com/q/52202240
score: 0
type: Answer

http://stackoverflow.com/q/52156674
score: 1
accepted answer: http://stackoverflow.com/a/52156879
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52156890
type: Question
answer count: 2
tagged with: python
has title: Memory Address - what is the use of it for programmer?
upvote count: 1
has answer: http://stackoverflow.com/a/52156879
has comment: http://stackoverflow.com/comment/91263661
downvote count: 0
has body: Evening community, I'm learning Python and more then often I can see addresses of objects in the memory like: ... at 0x019F60F0 That python is sharing with me when I'm running programs. How useful it will be for me in the future, if anyhow? Or is it just a side-effect of running the program, and human has no use of it?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52156890

http://stackoverflow.com/q/52248614
has comment: http://stackoverflow.com/comment/91445322
type: Question
accepted answer: http://stackoverflow.com/a/52255263
has body: I am trying to complete a multipart upload using my lambda (aws) written in python. Below is the code that I am using. There are around 120 parts and combined size is 30GB. The below operation doesn't seem to complete within 5 minutes , hence the lambda shuts down and the upload doesn't seem to complete. Does S3 offer asynchronous multi part upload functionality? I believe this would ensure that the file gets combined irrespective of lambda shutdown. resp = s3.complete_multipart_upload(Bucket=bucket_name, Key=result_filename, UploadId=upload_id, MultipartUpload={'Parts': parts_mapping})
tagged with: boto3
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/91445611
has comment: http://stackoverflow.com/comment/91445313
has comment: http://stackoverflow.com/comment/91448008
upvote count: 2
has answer: http://stackoverflow.com/a/52255263
answer count: 1
has comment: http://stackoverflow.com/comment/91447324
favorite count: 0
tagged with: aws-lambda
has title: S3 multipart upload - complete multipart upload asyncronously
tagged with: python
has comment: http://stackoverflow.com/comment/91445909
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/91447034
has comment: http://stackoverflow.com/comment/91445509

http://stackoverflow.com/q/52155943
answer count: 2
upvote count: 0
linked to: http://stackoverflow.com/q/180986
accepted answer: http://stackoverflow.com/a/52157881
favorite count: 0
has comment: http://stackoverflow.com/comment/91262179
has comment: http://stackoverflow.com/comment/91262717
tagged with: python
has comment: http://stackoverflow.com/comment/91262180
tagged with: regex
score: -1
type: AnsweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/91262712
type: Question
has comment: http://stackoverflow.com/comment/91262283
has answer: http://stackoverflow.com/a/52157881
has body: I want to create a regular expression to get only the lines that start with a date(ignore the other ones) and the ones that have the word "Prefix" on it. How should the regular expression looks like? I have the following structure in my txt file: Prefix : 0051601 Data Material No. OS Hist. Nr/Controle Quant. Vlr.Unit. Vlr.Total ---------------------------------------------------------------------------------------------------------------------------------------- 13/01/2008 00101050 Lampada farol H5 24V 003 4863 2,000 9,870556 19,7411 ====== Total dia 13/01/2008 ====== Entradas : Saídas : 2,000 19,7411 ------------------------------------------------------------------- And the primary code is: import glob, os import re os.chdir("./txtfiles/") for file in glob.glob("*.txt"): with open(file) as f: content = f.readlines() # not working, just for test purpose result = re.match(r'Prefix', content, re.M|re.I) if result: print(content) else: print "no match found!"
possible better answer: http://stackoverflow.com/a/52156211
has title: What regular expression should I use for this case?
has answer: http://stackoverflow.com/a/52156211
has comment: http://stackoverflow.com/comment/91262686

http://stackoverflow.com/comment/91455667
has text: Share the HTML code or link to website.
score: 0
comment on: http://stackoverflow.com/q/52253858
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52229942
tagged with: slurm
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52237453
score: 1
has body: I have a python script that I am running on a SLURM cluster for multiple input files: #!/bin/bash #SBATCH -p standard #SBATCH -A overall #SBATCH --time=12:00:00 #SBATCH --output=normalize_%A.out #SBATCH --error=normalize_%A.err #SBATCH --nodes=1 #SBATCH --ntasks=1 #SBATCH --cpus-per-task=20 #SBATCH --mem=240000 HDF5_DIR=... OUTPUT_DIR=... NORM_SCRIPT=... norm_func () { local file=$1 echo "$file" python $NORM_SCRIPT -data $file -path $OUTPUT_DIR } # Doing normalization in parallel for file in $HDF5_DIR/*; do norm_func "$file" &amp; done wait The python script is just loading a dataset (scRNAseq), does its normalization and saves as .csv file. Some major lines of code in it are: f = h5py.File(path_to_file, 'r') rawcounts = np.array(rawcounts) unique_code = np.unique(split_code) for code in unique_code: mask = np.equal(split_code, code) curr_counts = rawcounts[:,mask] # Actual TMM normalization mtx_norm = gmn.tmm_normalization(curr_counts) # Writing the results into .csv file csv_path = path_to_save + "/" + file_name + "_" + str(code) + ".csv" with open(csv_path,'w', encoding='utf8') as csvfile: writer = csv.writer(csvfile, delimiter=',') writer.writerow(["", cell_ids]) for idx, row in enumerate(mtx_norm): writer.writerow([gene_symbols[idx], row]) I keep getting step memory exceeded error for datasets that are above 10Gb and I am not sure why. How I can change my .slurm script or python code to reduce its memory usage? How can I actually identify what causes the memory problem, is there a particular way of debugging the memory in this case? Any suggestions would be greatly appreciated.
has title: How to determine at which point in python script step memory exceeded in SLURM
type: Question
has answer: http://stackoverflow.com/a/52237453
tagged with: memory
upvote count: 1
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/q/52120798
favorite count: 0
has body: actions = ActionChains(driver) actions.send_keys(search_query + Keys.ENTER) actions.perform() # code to wait until page loads src = driver.page_source How would I implement this? I'm trying to send keys to the search box, which i have, and then after the .perform I would like it to wait till the search results load, then get the source. Is that possible with selenium? Trying to find a way better than time.sleep(2) Maybe something like driver.wait_until_page_loads()
tagged with: python
has title: python selenium enter search query then wait
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/52121111
tagged with: selenium
tagged with: web-scraping
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/52121111
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/91246859
score: 0
type: Comment
has text: That is very odd because I can run this on python 3, and 3.6 with the desired output.
comment on: http://stackoverflow.com/a/52148468
type: AnswerComment

http://stackoverflow.com/q/52204308
type: AnsweredQuestion
tagged with: list
downvote count: 2
has answer: http://stackoverflow.com/a/52204471
accepted answer: http://stackoverflow.com/a/52204334
type: Question
possible better answer: http://stackoverflow.com/a/52204471
tagged with: list-comprehension
score: 0
has title: Nested list from list using list comprehension?
has body: I have the following list called flat: flat= ['11','13', '17', '19', '13', '17', '19','22','35','14','15'] I splitted it into a list of tuples using zip function as list(zip(flat[0::2], flat[1::2])) with the following output: [('11', '13'), ('17', '19'), ('13', '17'), ('19', '22'), ('35', '14')] Now, how to convert the list flat into the following result using list comprehension? [['11', '13'], ['17', '19'], ['13', '17'], ['19', '22'], ['35', '14']]
favorite count: 0
has answer: http://stackoverflow.com/a/52204334
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52204670
has answer: http://stackoverflow.com/a/52204552
answer count: 4

http://stackoverflow.com/q/52172262
score: 1
accepted answer: http://stackoverflow.com/a/52172295
has answer: http://stackoverflow.com/a/52172299
type: Question
has answer: http://stackoverflow.com/a/52172305
downvote count: 0
answer count: 3
tagged with: types
has body: I am learning how to use regular expressions in python. I am searching for a pattern in a string and returning a value in that string. Here is the code that I have so far. import re string = '20180515_154457_Trace3_110K_2_data.dpt' pattern = r'_Trace3_(\d+)K_\d+_data.dpt' re.search(pattern, string).groups() The above returns ('110', ). Why doesn't it just return ('110')? Why does it give me a tuple with an empty second element?
favorite count: 0
has title: python regexp method returns a list with an empty element
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52172295
tagged with: regex
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52172299

http://stackoverflow.com/q/52181106
has comment: http://stackoverflow.com/comment/91312456
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/91312167
answer count: 2
score: -2
has comment: http://stackoverflow.com/comment/91312493
has comment: http://stackoverflow.com/comment/91312364
has comment: http://stackoverflow.com/comment/91312491
possible better answer: http://stackoverflow.com/a/52181247
has comment: http://stackoverflow.com/comment/91312518
has answer: http://stackoverflow.com/a/52199963
has answer: http://stackoverflow.com/a/52181247
accepted answer: http://stackoverflow.com/a/52199963
has comment: http://stackoverflow.com/comment/91312405
has comment: http://stackoverflow.com/comment/91320902
has comment: http://stackoverflow.com/comment/91312328
has title: Is there a way to str1 -= str2?
has comment: http://stackoverflow.com/comment/91312769
has comment: http://stackoverflow.com/comment/91344847
has comment: http://stackoverflow.com/comment/91312303
favorite count: 0
has comment: http://stackoverflow.com/comment/91312674
tagged with: python-3.x
linked to: http://stackoverflow.com/q/9189172
has comment: http://stackoverflow.com/comment/91312330
has comment: http://stackoverflow.com/comment/91348512
tagged with: python
has comment: http://stackoverflow.com/comment/91312490
downvote count: 4
has comment: http://stackoverflow.com/comment/91339344
type: AnsweredQuestion
has body: First of all, I know -= operation doesn't work in str. But is there a function that works the same? The reason why I need this is because def function(self, str_source): str_source = str_source[:-1] # removing last character of the string str_source += self.other_function() # adding other characters return True In this sort of function, when I do s = s[:-1], the original string does not change. I know why it does not change, and I know I can just return another modified string, but I am currently working on someone else's code that I can't complete rip up the Project. So is it possible to remove the substring of a string in a function?
has comment: http://stackoverflow.com/comment/91312398
has comment: http://stackoverflow.com/comment/91347516

http://stackoverflow.com/comment/91249798
type: Comment
type: QuestionComment
score: 0
has text: @GeorgeDaramouskas Added image:)
comment on: http://stackoverflow.com/q/52149081

http://stackoverflow.com/comment/126571206
type: Comment
has text: Well what was the solution?
comment on: http://stackoverflow.com/q/52242506
score: 0
type: QuestionComment

http://stackoverflow.com/q/52235103
has answer: http://stackoverflow.com/a/52235126
linked to: http://stackoverflow.com/q/132988
answer count: 2
duplicate of: http://stackoverflow.com/q/132988
favorite count: 0
has body: &gt;&gt; a=1 &gt;&gt; id(a);id(1) 1844525312 1844525312 &gt;&gt; id(a)==id(1) True &gt;&gt; id(a) is id(1) False what is the difference between the == and is?
accepted answer: http://stackoverflow.com/a/52235164
tagged with: python
has title: id() python difference between the == and 'is'
score: 2
upvote count: 3
linked to: http://stackoverflow.com/q/306313
downvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52235164
possible better answer: http://stackoverflow.com/a/52235126
duplicate of: http://stackoverflow.com/q/306313

http://stackoverflow.com/a/52144401
downvote count: 0
upvote count: 2
type: AcceptedAnswer
has body: From the JSON spec: Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. So no, NaN is not a valid JSON value for a number.
accepted answer of: http://stackoverflow.com/q/52142990
type: Answer
answers question: http://stackoverflow.com/q/52142990
score: 2

http://stackoverflow.com/q/52187001
tagged with: list
has answer: http://stackoverflow.com/a/52188361
has comment: http://stackoverflow.com/comment/91323978
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52188022
has comment: http://stackoverflow.com/comment/91323996
type: Question
has comment: http://stackoverflow.com/comment/91325122
score: -2
has answer: http://stackoverflow.com/a/52187441
has title: Matching each element in a list to each element in a list of a list, using Python
upvote count: 1
has comment: http://stackoverflow.com/comment/91324868
favorite count: 0
has comment: http://stackoverflow.com/comment/91325233
has answer: http://stackoverflow.com/a/52187764
has comment: http://stackoverflow.com/comment/91326491
tagged with: data-analysis
downvote count: 3
has body: I am trying to find the most efficient way of matching each element in a List to each element in a List of Lists using Python. For e.g input: &gt;&gt;&gt;myList = [['hi', 'no', 'bye', 'Global', 24],['morning', 'X', 'place'],['so', 'large', 'mall','test'], ['hi', 'X', 'place', 'bye']] &gt;&gt;&gt;check_against_myLIst = ['bye','place','hi','australia'] Now I am not sure if the best way would be to use a map function, for loops or any other python data analysis methodology. The output needs to be converted into a dataframe, such that Output is. Index Value Result 0 ['hi', 'no', 'bye', 'Global', 24] True 1 ['morning', 'X', 'place'] True 2 ['so', 'large', 'mall','test'] False 3 ['hi', 'X', 'place', 'bye'] True Thanks !
tagged with: python
answer count: 4

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

http://stackoverflow.com/q/52133742
answer count: 1
tagged with: scripting
type: UnansweredQuestion
tagged with: python
has title: How to running JSP on remote computer
tagged with: python-requests
has body: Assume there is a tomcat apache server on http://192.168.1.10:8443/sample.jsp which is print a result on the page. How can we get that result in a script from command line or command line browsers like elinks from another computer? No matter is this a bash script, php script or a python one. I used python script with requests and re modules for fetching the page source, but there's no success!
type: Question
has answer: http://stackoverflow.com/a/52135195
tagged with: jsp
tagged with: tomcat
score: 0

http://stackoverflow.com/q/52128462
has title: __class__ equality check from two different imports
score: 0
has comment: http://stackoverflow.com/comment/91207426
tagged with: python-importlib
has comment: http://stackoverflow.com/comment/91207561
has comment: http://stackoverflow.com/comment/91207482
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91207492
has body: I have a rather complicated import setup in my python software project where I don't get around importing some modules dynamically with importlib. Therefore I run into situations where I have two objects of the same class, but since they have been loaded independently the equality check between them gives me False. Their string representations of each object's obj.__class__ look the same: &lt;class 'drivers.MongoDriver'&gt; vs &lt;class 'drivers.MongoDriver'&gt;. Equality checks with __eq__ on both classes, issubclass, __eq__ on type() and isinstance fail, though. I could think of a hacky way to still do a equality check by comparing repr(obj.__class__), but that doesn't really seem so nice. Another solution would be to "hide" an attribute specifying some unique class id. Is there another (better) way how to do equality checks between two classes that are essentially the same but have been loaded by importlib independently? Edit: Important: I'm not looking for a way to avoid importing the class twice. Some modules of my project are reimported on purpose dynamically to account for code changes in those modules during runtime. Those modules then again import other modules, such as the driver I want to make an equality check with. And even though it would be nice to not have to reimport those non-changing modules that are used by the changing modules, I am aware that whenever I dynamically import one module that all dependencies are then reimported as well. (If you have a solution on how to reimport a module A which itself has a (static) import B, but not have to reimport B together with A, I would be happy. But this is not directly what I'm asking/looking for.)
type: Question
has comment: http://stackoverflow.com/comment/91207469

http://stackoverflow.com/q/52113939
has answer: http://stackoverflow.com/a/61366441
tagged with: python
tagged with: nlp
score: 25
type: AnsweredQuestion
upvote count: 25
tagged with: spacy
has body: I have downloaded en_core_web_lg model and trying to find similarity between two sentences: nlp = spacy.load('en_core_web_lg') search_doc = nlp("This was very strange argument between american and british person") main_doc = nlp("He was from Japan, but a true English gentleman in my eyes, and another one of the reasons as to why I liked going to school.") print(main_doc.similarity(search_doc)) Which returns very strange value: 0.9066019751888448 These two sentences should not be 90% similar they have very different meanings. Why this is happening? Do I need to add some kind of additional vocabulary in order to make similarity result more reasonable?
has answer: http://stackoverflow.com/a/74593161
has answer: http://stackoverflow.com/a/52143696
possible better answer: http://stackoverflow.com/a/54065910
type: Question
has answer: http://stackoverflow.com/a/54065910
accepted answer: http://stackoverflow.com/a/52143696
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/57932912
has title: Spacy, Strange similarity between two sentences
answer count: 5

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/52233899
tags question: http://stackoverflow.com/q/52144843
tags question: http://stackoverflow.com/q/52136318
tags question: http://stackoverflow.com/q/52115749
tags question: http://stackoverflow.com/q/52153928
tags question: http://stackoverflow.com/q/52227531
tags question: http://stackoverflow.com/q/52169137
tags question: http://stackoverflow.com/q/52178475
tags question: http://stackoverflow.com/q/52117935
tags question: http://stackoverflow.com/q/52268509
tags question: http://stackoverflow.com/q/52127072
tags question: http://stackoverflow.com/q/52176999
tags question: http://stackoverflow.com/q/52162646
tags question: http://stackoverflow.com/q/52139956
tags question: http://stackoverflow.com/q/52155758
tags question: http://stackoverflow.com/q/52153989
tags question: http://stackoverflow.com/q/52262943
tags question: http://stackoverflow.com/q/52112496
tags question: http://stackoverflow.com/q/52218791
tags question: http://stackoverflow.com/q/52232474
type: Tag
tags question: http://stackoverflow.com/q/52122242
tags question: http://stackoverflow.com/q/52126753
tags question: http://stackoverflow.com/q/52187046
tags question: http://stackoverflow.com/q/52152374
tags question: http://stackoverflow.com/q/52268930
tags question: http://stackoverflow.com/q/52172459
tags question: http://stackoverflow.com/q/52121149
tags question: http://stackoverflow.com/q/52253052
tags question: http://stackoverflow.com/q/52157206
tags question: http://stackoverflow.com/q/52147751
tags question: http://stackoverflow.com/q/52234834
tags question: http://stackoverflow.com/q/52263884
tags question: http://stackoverflow.com/q/52119678
tags question: http://stackoverflow.com/q/52124988
tags question: http://stackoverflow.com/q/52113890
tags question: http://stackoverflow.com/q/52112869
tags question: http://stackoverflow.com/q/52145385
tags question: http://stackoverflow.com/q/52258913
tags question: http://stackoverflow.com/q/52236112

http://stackoverflow.com/q/52227213
has title: Pandas: all possible combinations of rows
favorite count: 0
tagged with: python
upvote count: 4
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/52227498
has comment: http://stackoverflow.com/comment/91403954
type: Question
tagged with: combinations
score: 4
has answer: http://stackoverflow.com/a/52227498
tagged with: concatenation
tagged with: pandas
has body: I have a DataFrame looking like.. ID c1 c2 cX r1 2 3 .. r2 8 9 .. rY .. I want to generate a new DataFrame with all possible (two-part) combinations of rows whilst concatenating the columns of the two combined rows (so that the new DF would have twice as much columns). The result should look like: ID c1_r1 c1_r2 c2_r1 c2_r2 cX_rA r1_r2 2 8 3 9 .. r1_r3 .. .. .. .. rA_rB .. The ID name isn't important (it could even be a MultiIndex) nor is the order of the columns of importance. How to approach this?
answer count: 1

http://stackoverflow.com/a/52239901
has comment: http://stackoverflow.com/comment/131174155
upvote count: 2
answers question: http://stackoverflow.com/q/52239783
has body: Rather than read the whole list into memory, loop over the input file, and write all lines except the line you need to delete to the a new file. Use enumerate() to keep a counter if you need to delete by index: row_to_delete = 101068 filename = "EKBE_0_20180907_065907 - Copy.csv" with open(filename, 'r', encoding='utf8', errors='ignore') as inputfile,\ open(filename + '.fixed', 'wb', encoding="utf8") as outputfile: for index, line in enumerate(inputfile): if index == row_to_delete: continue # don't write the line that matches outputfile.writeline(line) Rather than use an index, you could even detect a bad line directly in code this way. Note that this writes to a new file, with the same name but with .fixed added. You can move that file back to replace the old file if you want to, with os.rename(), once you are done copying all but the bad line: os.rename(filename + '.fixed', filename)
accepted answer of: http://stackoverflow.com/q/52239783
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/131636503
score: 2

http://stackoverflow.com/comment/91443565
has text: and bro rate my answers @DanielSaggo
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52247064

http://stackoverflow.com/a/52249233
answers question: http://stackoverflow.com/q/52249158
has comment: http://stackoverflow.com/comment/91446676
upvote count: 5
has comment: http://stackoverflow.com/comment/91446763
has comment: http://stackoverflow.com/comment/91446715
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/91447410
has body: I assume you were referring to the below documentation: sklearn.model_selection.cross_val_score The purpose of cross validation is ensuring that your model hasn't had particularly high variance leading to a good-fit in one instance, but a poor fit in another instance. This is used generally in model validation. With this in mind, you should be passing the training set (X_train, y_train) and seeing how your model performs. Your question was focused on: "Can I pass in the whole data-set into cross validation?" The answer is, yes. This is conditional and based off whether or not you are satisfied with your ML output. Say for example, I have the following below: I have used a Random forest model and am happy with my overall model fit and score. In this case, I have a hold-out set. Once I remove this hold-out set and give my model the whole data-set, we would get a plot with an even higher score as I am giving my model more information (and as such, your CV scores will also reflectively be higher). An example of calling the method might be as such: probablistic_scores = cross_val_score(model, X_train, y_train, cv=5) Generally a 5 Fold Cross validation is preferred. If you wish to go higher than 5 fold - please note that as your 'n' folds increase, the number of computational resources required will also increase and will take longer to process.
type: Answer

http://stackoverflow.com/comment/91456459
type: Comment
comment on: http://stackoverflow.com/a/52254405
has text: @Matphy see edit.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91329849
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/52175978
type: Comment
has text: @MikhailT.: https://stackoverflow.com/questions/2374334/static-variables-in-python-c-api, but it's the wrong thing to do for `__module__`.

http://stackoverflow.com/comment/91227237
comment on: http://stackoverflow.com/a/52138696
type: Comment
score: 0
has text: @Violatic - You can use `dfs['columns_name']` for DataFrame
type: AnswerComment

http://stackoverflow.com/comment/91381980
score: 8
comment on: http://stackoverflow.com/q/52216652
has text: `butikk[ny_vare] = ny_vare_pris` should work.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91220091
type: Comment
comment on: http://stackoverflow.com/a/52135006
has text: and how do I group it based on direct sentence?
score: 0
type: AnswerComment

http://stackoverflow.com/a/52252635
type: Answer
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52235135
answers question: http://stackoverflow.com/q/52235135
has body: The simplest way is to use np.eye() and numpy slicing: def one_hot_encode(y): """Do one-hot encoding of y Parameters ---------- y : numpy array of arbitrary shape Returns one-hot-encoded y of the same shape plus one-hot-encoded vector as a last axis """ # map `y' to an index value (from 0 to number of classes minus one) y_vals = sorted(np.unique(y)) K = len(y_vals) to_index = np.vectorize(lambda x: y_vals.index(x)) y = to_index(y) # remove the last dimension since we want to substitute it with a one-hot-vector if y.shape[-1] == 1 and len(y.shape&gt;1): y = y.reshape(y.shape[:-1]) # do one hot encoding: y = np.eye(K)[y].astype( np.uint8 if K&lt;255 else np.uint16 ) return y

pyqt
type: Tag
tags question: http://stackoverflow.com/q/52205323
tags question: http://stackoverflow.com/q/52166539
tags question: http://stackoverflow.com/q/52202612
tags question: http://stackoverflow.com/q/52171529
tags question: http://stackoverflow.com/q/52230953
tags question: http://stackoverflow.com/q/52199282
tags question: http://stackoverflow.com/q/52253381
tags question: http://stackoverflow.com/q/52215329
tags question: http://stackoverflow.com/q/52240205
tags question: http://stackoverflow.com/q/52178004
tags question: http://stackoverflow.com/q/52162125
tags question: http://stackoverflow.com/q/52270916
tags question: http://stackoverflow.com/q/52213321
tags question: http://stackoverflow.com/q/52270391
tags question: http://stackoverflow.com/q/52114484
tags question: http://stackoverflow.com/q/52185656
tags question: http://stackoverflow.com/q/52262326
tags question: http://stackoverflow.com/q/52260388
tags question: http://stackoverflow.com/q/52142950
tags question: http://stackoverflow.com/q/52266968
tags question: http://stackoverflow.com/q/52248819
tags question: http://stackoverflow.com/q/52153985
tags question: http://stackoverflow.com/q/52269653
tags question: http://stackoverflow.com/q/52166429
tags question: http://stackoverflow.com/q/52240857
tags question: http://stackoverflow.com/q/52173912
tags question: http://stackoverflow.com/q/52268778
tags question: http://stackoverflow.com/q/52223784
tag name: pyqt
tags question: http://stackoverflow.com/q/52269950
tags question: http://stackoverflow.com/q/52238212

http://stackoverflow.com/a/52186875
answers question: http://stackoverflow.com/q/52186737
has body: A list usually contains a number of elements accessed by only one index. As an example, the list list = [1,2,3,4] has 4 elements that you can access with list[0] which yields 0 or list[2] which yields 3 or list[-1] which yields 4. Note that you can use a negative index. Now if you need more then one dimension you want to built a matrix. A matrix is basically a list of list. There are several ways to built a matrix. My preferred way is matrix1 = [[0.0 for x in range(0, lenght)] for y in range(0, lenght)] but also matrix2 = [[1,2,3],[3,4,5]] can work. If you want to access a matrix you can do this by matrix2[0][1] which would yield 2. Note that the first index access the first list, the second index a list within the first list. Now what you apparently want to do is to use a list to store tuples. In that case you have tuples tuple = (value1, value2) stored in a list. For example list = [(1,2),(3,4),(5,6)] contains three tuples. You can access a tuple like a list, so you can access the value 2 with list[0][1]. To recap, list and tuples are accessed with the brackets []. Negative values are acceptable. You can store tuples in lists or lists in lists. If you do so you have to use several brackets [].
type: Answer
score: 0

http://stackoverflow.com/comment/91793510
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52330046
has text: @LiuSha Dataframe and Series have index. as `np.random.randn` is a list of list its un-indexed.
type: AnswerComment

http://stackoverflow.com/comment/91351585
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52201197
has text: You **do not have a value with double backslashes**. The `repr()` output gives you valid Python syntax to recreate the value. There is no problem here, you have the value you need, just pass it on.
type: Comment

http://stackoverflow.com/comment/91188074
comment on: http://stackoverflow.com/q/52118574
has text: Iterating through the dictionary keys defeats the point of dictionaries. You need only check whether the value is `input_user.lower() in data` or use `data.get(input_user.lower())`
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/q/52118695
has comment: http://stackoverflow.com/comment/91201322
has body: I've been trying to find a way to make a TextInput in Kivy with something like class CustomTextInput(TextInputBehavior, Image): pass Only that TextInputBehavior doesn't exist. I wonder if there's a similiar way. I've searched everywhere, the internet and the docs, just can't seem to find the right solution. By 'custom button` I mean something like this:
type: Question
has comment: http://stackoverflow.com/comment/91200071
score: 0
has comment: http://stackoverflow.com/comment/91191313
has title: Is there a way to make a custom TextInput in Kivy?
tagged with: python
tagged with: kivy
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91191641

http://stackoverflow.com/comment/91553561
comment on: http://stackoverflow.com/a/52131155
score: 0
type: Comment
has text: i am looking for colored emojis like in whatsapp
type: AnswerComment

http://stackoverflow.com/comment/91210737
has text: If you don't initialize `addition` before the loop you will get an error when you try to add `x` to it. The function will not remember the previous values of it's local variables next time it's called.
type: Comment
comment on: http://stackoverflow.com/a/52129670
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91298029
type: QuestionComment
has text: ok my bad, I figured it out. I needed to select the frame by its index (1) meaning that it was the second frame in the code
score: 0
comment on: http://stackoverflow.com/q/52172202
type: Comment

regex
tags question: http://stackoverflow.com/q/52148437
tags question: http://stackoverflow.com/q/52173729
tags question: http://stackoverflow.com/q/52220716
tags question: http://stackoverflow.com/q/52157718
tags question: http://stackoverflow.com/q/52224264
tags question: http://stackoverflow.com/q/52259686
tags question: http://stackoverflow.com/q/52228631
tags question: http://stackoverflow.com/q/52197413
tags question: http://stackoverflow.com/q/52193943
tags question: http://stackoverflow.com/q/52214768
tags question: http://stackoverflow.com/q/52134495
tags question: http://stackoverflow.com/q/52204830
tag name: regex
tags question: http://stackoverflow.com/q/52131706
tags question: http://stackoverflow.com/q/52254186
tags question: http://stackoverflow.com/q/52264372
tags question: http://stackoverflow.com/q/52251480
tags question: http://stackoverflow.com/q/52144179
tags question: http://stackoverflow.com/q/52139859
tags question: http://stackoverflow.com/q/52229998
tags question: http://stackoverflow.com/q/52118574
tags question: http://stackoverflow.com/q/52160119
tags question: http://stackoverflow.com/q/52235073
tags question: http://stackoverflow.com/q/52134169
tags question: http://stackoverflow.com/q/52233549
tags question: http://stackoverflow.com/q/52162611
tags question: http://stackoverflow.com/q/52168533
tags question: http://stackoverflow.com/q/52144537
tags question: http://stackoverflow.com/q/52180653
tags question: http://stackoverflow.com/q/52121630
tags question: http://stackoverflow.com/q/52231496
tags question: http://stackoverflow.com/q/52178302
tags question: http://stackoverflow.com/q/52134236
tags question: http://stackoverflow.com/q/52263594
tags question: http://stackoverflow.com/q/52123501
tags question: http://stackoverflow.com/q/52134533
tags question: http://stackoverflow.com/q/52241008
tags question: http://stackoverflow.com/q/52145792
tags question: http://stackoverflow.com/q/52243385
tags question: http://stackoverflow.com/q/52234474
tags question: http://stackoverflow.com/q/52149058
tags question: http://stackoverflow.com/q/52194605
tags question: http://stackoverflow.com/q/52235537
tags question: http://stackoverflow.com/q/52148942
tags question: http://stackoverflow.com/q/52185183
tags question: http://stackoverflow.com/q/52190644
tags question: http://stackoverflow.com/q/52196667
tags question: http://stackoverflow.com/q/52155943
tags question: http://stackoverflow.com/q/52270628
tags question: http://stackoverflow.com/q/52268914
tags question: http://stackoverflow.com/q/52213070
tags question: http://stackoverflow.com/q/52172262
tags question: http://stackoverflow.com/q/52155370
tags question: http://stackoverflow.com/q/52163981
tags question: http://stackoverflow.com/q/52174512
tags question: http://stackoverflow.com/q/52182470
tags question: http://stackoverflow.com/q/52230792
tags question: http://stackoverflow.com/q/52243731
tags question: http://stackoverflow.com/q/52160983
tags question: http://stackoverflow.com/q/52118537
tags question: http://stackoverflow.com/q/52225735
tags question: http://stackoverflow.com/q/52160568
tags question: http://stackoverflow.com/q/52119826
tags question: http://stackoverflow.com/q/52204336
tags question: http://stackoverflow.com/q/52149525
tags question: http://stackoverflow.com/q/52152707
tags question: http://stackoverflow.com/q/52254944
tags question: http://stackoverflow.com/q/52164834
tags question: http://stackoverflow.com/q/52160772
tags question: http://stackoverflow.com/q/52263928
tags question: http://stackoverflow.com/q/52245731
tags question: http://stackoverflow.com/q/52210973
tags question: http://stackoverflow.com/q/52178332
tags question: http://stackoverflow.com/q/52183366
tags question: http://stackoverflow.com/q/52137212
tags question: http://stackoverflow.com/q/52138306
tags question: http://stackoverflow.com/q/52229785
tags question: http://stackoverflow.com/q/52245767
tags question: http://stackoverflow.com/q/52136299
tags question: http://stackoverflow.com/q/52250198

http://stackoverflow.com/comment/91442912
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52247376
has text: @Wen please check edited question.Hope you get it now :)

http://stackoverflow.com/comment/91231030
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52140621
has text: Why do you consider a file with one column to be a csv file (since it will have only have one value on each line/row and therefore not have any need for delimiters)?
score: 0

http://stackoverflow.com/q/52140184
answer count: 1
type: UnansweredQuestion
has title: Error trying to run mod_wsgi on a apache server
has body: I have a Flask Project structure directory inside /var/www: item-catalog-fullstacknd\ itemCatalogApp.wsgi itemCatalogApp\ __init__.py This is th WSGI file above: import sys import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0,"/var/www/item-catalog-fullstacknd/") from itemCatalogApp import app as application application.secret_key = 'Add your secret key' This is the /etc/apache2/sites-enabled/000-default.conf WSGIPythonPath /var/www/item-catalog-fullstacknd/itemCatalogApp/ &lt;VirtualHost *:80&gt; WSGIScriptAlias / /var/www/item-catalog-fullstacknd/itemCatalogApp.wsgi &lt;Directory /var/www/item-catalog-fullstacknd/itemCatalogApp&gt; Order allow,deny Allow from all &lt;/Directory&gt; Alias /static /var/www/item-catalog-fullstacknd/itemCatalogApp/static &lt;Directory /var/www/item-catalog-fullstacknd/itemCatalogApp/static/&gt; Order allow,deny Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; And I am getting the following error: mod_wsgi (pid=17586): Exception occurred processing WSGI script '/var/www/item-catalog-fullstacknd/itemCatalogApp.wsgi'. Traceback (most recent call last): File "/var/www/item-catalog-fullstacknd/itemCatalogApp.wsgi", line 6, in &lt;module&gt; from itemCatalogApp import app as application File "/var/www/item-catalog-fullstacknd/itemCatalogApp/__init__.py", line 3, in &lt;module&gt; from flask import Flask, jsonify, render_template, request ImportError: No module named flask I already pip install all the modules contained in the requirements.txt file. I have no idea what to do anymore.
tagged with: python
tagged with: mod-wsgi
type: Question
has answer: http://stackoverflow.com/a/52145619
tagged with: flask
tagged with: apache2
score: 0

http://stackoverflow.com/a/52208862
has comment: http://stackoverflow.com/comment/91368441
has body: Use a set of names, then you can check presence with the in operator: processes = {'pro1.exe', 'pro2.exe', 'pro3.exe'} for proc in psutil.process_iter(): if proc.name() in processes: proc.kill() And if you wanted to define a set of the first n 'pro[n].exe' strings, then you could use a generator expression with the set() constructor: processes = set(f'pro{i}.exe' for i in range(1,n)) which, with e.g. n = 10, gives: {'pro6.exe', 'pro8.exe', 'pro9.exe', 'pro2.exe', 'pro4.exe', 'pro3.exe', 'pro1.exe', 'pro7.exe', 'pro5.exe'} notice that a set does not have order, since it has no concept of indexes.
answers question: http://stackoverflow.com/q/52208822
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91367359
accepted answer of: http://stackoverflow.com/q/52208822
score: 0
type: Answer

http://stackoverflow.com/comment/91313421
comment on: http://stackoverflow.com/q/52181539
score: 1
has text: Can you post the error with the full stack trace?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52158893
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/52160333
tagged with: web-scraping
has body: I want to scrape data from a website, but first I want to get the page with pagination. Here I'm using python as a program language, and I already got this code. But when I run it, it doesn't work properly. the result must be stopped when response.url didn't match with expected_url. Is there someone know how to solve it? Please help, thank you. Here is the code : from bs4 import BeautifulSoup import urllib.request count = 0 url = "http://www.belanjamimo.net/foundation-bb-cream/?o=a&amp;s=%d" def get_url(url): req = urllib.request.Request(url) return urllib.request.urlopen(req) expected_url = url % count response = get_url(expected_url) while (response.url == expected_url): print("GET {0}".format(expected_url)) count += 9 expected_url = url % count response = get_url(expected_url)
type: Question
has comment: http://stackoverflow.com/comment/91567953
tagged with: pagination
accepted answer: http://stackoverflow.com/a/52160333
has comment: http://stackoverflow.com/comment/91268495
answer count: 1
has title: pagination : why it's still run while the page is not match?
tagged with: python
has comment: http://stackoverflow.com/comment/91268194

http://stackoverflow.com/comment/91182034
has text: Try installing gcc-c++ or g++
comment on: http://stackoverflow.com/q/52115655
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52229674
type: AnsweredQuestion
score: 0
tagged with: mapreduce
type: Question
tagged with: hadoop
answer count: 1
has answer: http://stackoverflow.com/a/52297044
has body: I installed Pydoop and am trying to run MapReduce jobs. Just to do a dry run, I tried executing the word count examples wordcount_minimal.py and wordcount_full.py. Both of them hang at the map phase. In the end of the stderr, I find this message as per the script I run: module 'wordcount_minimal' has no attribute 'main' or module 'wordcount_full' has no attribute 'main' I executed the job using the command: pydoop submit --upload-file-to-cache wordcount_full.py wordcount_full hdfs_input_dir hdfs_output_dir Unable to find the reason behind this. Any idea what could be the reason? I was able to execute the example from the pydoop script using the map and reduce functions and it completed successfully. But with the pydoop submit option, I have this issue. Not sure if I am missing something. PS: I have a cluster with 2 nodes running Hortonworks HDP 2.6.5. Pydoop is installed on both of them.
accepted answer: http://stackoverflow.com/a/52297044
tagged with: python
tagged with: hortonworks-data-platform
has title: Pydoop mapreduce "AttributeError: module 'wordcount_minimal' has no attribute '__main__'"

http://stackoverflow.com/comment/91264395
comment on: http://stackoverflow.com/q/52156423
has text: @jpp, I have now included the desired output for my question. Thanks!
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52192868
answer count: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/91335615
has title: Putting boundaries and transforming variables (boolean python)
has answer: http://stackoverflow.com/a/52192978
tagged with: python
has comment: http://stackoverflow.com/comment/91335724
has body: I am at my beginning journey of learning python and I am struggling to get my head around transforming entries in a code. I have a for loop going and for every loop I create 4 variables. So below is the result of four loops. A B C D 0 0 18 19 0 0 52 52 0 0 18 19 -1 -1 19 52 ** in this loop A have to be 0 , B have to be 0 and D have to be 50 -1 -1 19 20 ** in this case A and B must become 0 Expected result: A B C D 0 0 18 19 0 0 50 50 (## just a mark no need to be here just to point) , C and D became 50 0 0 18 19 0 0 19 52 0 0 19 20 ** A and B got transformed to 0 So I thought this would work, what I need is that none of this variables to be greater than 50 or below 0. If they are below zero they must become 0 and if they are above 50 then 50, else just the variable itself: if A &lt; 0: A = 0 elif A&gt;50: A = 50 elif 0&lt;A&lt;50: A=A elif A &lt; 0: A = 0 elif B&gt;50: B = 50 elif 0&lt;B&lt;50: B=B ...... I also thought about defining a function and passing the 4 variables each time to the function.. Ok i edit the if , sorry typo. Let be a bit more clear on every run A,B,C and D must be transformed if they are above 50 or below zero, so just use a 0
type: AnsweredQuestion
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/91335694
tagged with: loops
has comment: http://stackoverflow.com/comment/91335535
type: Question
has answer: http://stackoverflow.com/a/52193300
possible better answer: http://stackoverflow.com/a/52192978
accepted answer: http://stackoverflow.com/a/52193300
tagged with: if-statement
score: -2

http://stackoverflow.com/q/52117056
tagged with: testing
answer count: 2
accepted answer: http://stackoverflow.com/a/52117356
score: 0
has comment: http://stackoverflow.com/comment/91184982
possible better answer: http://stackoverflow.com/a/52119689
has answer: http://stackoverflow.com/a/52119689
has title: How do I run daily automated tests for a web scraper?
has comment: http://stackoverflow.com/comment/91185527
has answer: http://stackoverflow.com/a/52117356
tagged with: django
tagged with: python
has body: I maintain a REST API built with Django REST that, internally, scrapes several webpages to retrieve a bunch of information. I have tests for every endpoint that check whether the scrapers are still working. They actually connect with the pages and check that the sources remain unchanged and that everything is still fine basically. I would like to run these tests several times per day, and be notified when any of these scrapers fail. I'm not sure how should I approach this. I'm looking for a method that allows me to: Run tests automatically every X hours Notify me of the results I've been looking at CI, but I'm not sure if that is the preferable approach here.
type: AnsweredQuestion
type: Question

http://stackoverflow.com/q/52198446
has answer: http://stackoverflow.com/a/52200559
has comment: http://stackoverflow.com/comment/91347873
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91349964
tagged with: python
has comment: http://stackoverflow.com/comment/137851318
score: 2
type: Question
tagged with: crash
upvote count: 2
has title: How to resolve ucrtbase.dll APPCRASH with python (ucrtbase.DLL)
answer count: 1
downvote count: 0
favorite count: 0
has body: I made exe file by python. I'm using the following command: pyinstaller --windowed --onfile gui.py but when I excute gui.exe, it crashes: Problem signing: Problem Event Name: APPCRASH Application name: gui.Exe Application version: 0.0.0.0 Application timestamp: 5a2e9fe6 Error Module Name: **ucrtbase.DLL** Error Module Version: 10.0.10586.78 Error Module Timestamp: 5879aa7b Exception Code: 40000015 Exception Offset: 0008469a OS version: 6.1.7601.2.1.0.256.4 Locale ID: 1042 Additional Information 1: f997 Tip 2: f997d3aa488aa2577b4933f22e55cb2d Tip 3: 6403 Tip 4: 640395134c67d4ec87d3c630dcc2b585 Why does this happen? How can I resolve this problem?

http://stackoverflow.com/q/52163733
accepted answer: http://stackoverflow.com/a/52164059
type: AnsweredQuestion
type: Question
tagged with: signals
answer count: 1
has body: class Leave(models.Model): employee_ID = models.CharField(max_length = 20) name = models.CharField(max_length = 50) user = models.ForeignKey(User, on_delete = models.CASCADE, null =True) def create_form(sender, instance, created, **kwargs): print('form sent') post_save.connect(receiver = create_form, sender= Leave) I've written a post_save signal for my model, so that each time the ModelForm is saved it print's form sent, but the same happens if I alter some fields in the /admin and save. How do I stop that and write another signal if admin alters any field. I've tried this for admin but it doesn't work from django.contrib import admin def admin_alter(sender, instance, created, **kwargs): if Leave.status == '1': print('admin altered') post_save.connect(receiver = after_accepting, sender= admin)
score: 0
has answer: http://stackoverflow.com/a/52164059
tagged with: model
has comment: http://stackoverflow.com/comment/91303871
has comment: http://stackoverflow.com/comment/91277331
has title: Django signals is functioning even for django - admin when written for a model
tagged with: django
tagged with: python

http://stackoverflow.com/a/52196736
has comment: http://stackoverflow.com/comment/91343192
score: 1
has comment: http://stackoverflow.com/comment/91342880
accepted answer of: http://stackoverflow.com/q/52196667
answers question: http://stackoverflow.com/q/52196667
has comment: http://stackoverflow.com/comment/91342766
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91343096
has body: Use split to split on newlines with lookahead for \* ReceiverList: re.compile("\r?\n(?=\* ReceiverList)").split(s)
has comment: http://stackoverflow.com/comment/91343333
type: Answer
has comment: http://stackoverflow.com/comment/91343573
has comment: http://stackoverflow.com/comment/91343650
has comment: http://stackoverflow.com/comment/91343127
upvote count: 1
has comment: http://stackoverflow.com/comment/91342823

http://stackoverflow.com/a/52180231
score: 0
has body: I found a way to work around it (in a way), thanks to the comments. Set the text attribute of the childless node to whitespace or newline depending on what you want. &gt;&gt;&gt; childlessNode = ET.SubElement(parent_node, "childless") &gt;&gt;&gt; childlessNode.text = ' ' or if you don't need the reference to it ET.SubElement(parent_node, "childless").text = ' ' Ref (thanks to Caramiriel's comment ): https://github.com/python/cpython/blob/09b52471f39ba280d836b945d47719c697af0b45/Lib/xml/etree/ElementTree.py#L934
answers question: http://stackoverflow.com/q/52168502
type: Answer

http://stackoverflow.com/q/52206248
has body: I am looking at the the regex posted here https://gist.github.com/gruber/8891611 for matching to URLs, which is the following: (?i)\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)/)(?:[^\s()&lt;&gt;{}\[\]]+|\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\))+(?:\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\)|[^\s`!()\[\]{};:'".,&lt;&gt;?«»“”‘’])|(?:(?&lt;!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx…
type: Question
tagged with: matching
has comment: http://stackoverflow.com/comment/91361836
tagged with: newline
has comment: http://stackoverflow.com/comment/91362336
score: 0
has title: Regex to match all urls, even with line break
has comment: http://stackoverflow.com/comment/92194193
tagged with: url
has comment: http://stackoverflow.com/comment/91398587
has comment: http://stackoverflow.com/comment/91406013
has comment: http://stackoverflow.com/comment/91398582
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: regex

http://stackoverflow.com/a/52245124
has body: You can start more threads the same way you started the first one from threading import Thread t1 = Thread(target=alphabetical_links, kwargs={ 'mainurl': link, }) t1.start() t2 = Thread(target=sub_links, kwargs={ 'process_links': link, }) t2.start()
score: 0
answers question: http://stackoverflow.com/q/52245035
type: Answer
has comment: http://stackoverflow.com/comment/91438723

http://stackoverflow.com/a/52240091
answers question: http://stackoverflow.com/q/52240060
type: Answer
has comment: http://stackoverflow.com/comment/91428944
accepted answer of: http://stackoverflow.com/q/52240060
upvote count: 2
score: 2
has body: This might work: with self.assertRaises(ValidationError): try: AvailablePermissions( **permission ).full_clean_save() except NoReverseMatch: raise ValidationError But do you really want to do that? Generally with unit testing the desire is to exercise all of the possible paths. This would just guarantee one of two paths were tested.
has comment: http://stackoverflow.com/comment/91428960
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91429024

http://stackoverflow.com/q/52121886
favorite count: 0
has comment: http://stackoverflow.com/comment/91195334
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91202606
score: 3
tagged with: python
answer count: 0
upvote count: 3
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/91197171
has title: Recommended way to PUT an iterable of byte-likes via python-requests
has comment: http://stackoverflow.com/comment/91197218
downvote count: 0
has body: I am using the requests library to put objects into an object store. The objects are fairly large (many megabytes) and performance is critical, so I'm trying to avoid copies wherever possible. Each object consists of a small header and a large blob of data. Since the default adapter for requests ultimately sits on top of http.client and http.client allows the request body to be specified as an iterable of byte-like objects, it seems very doable. I also need a Content-Length header (the server requires it), so the generator approach listed in the documentation (using chunked encoding) won't cut it. I have actually done it, but I had to reverse engineer it from the code using undocumented features, which always introduces a risk of a future version breaking things. I'd like to know if there is either a better solution, or if not, how fragile this is to future changes in requests. Here's my solution so far: class Multipart: def __init__(self, items=()): self.items = list(items) def __iter__(self): return iter(self.items) @property def len(self): return sum(len(item) for item in self.items) One alternative I've thought of is to get a PreparedRequest and then override its .body (also shown in the documentation) and presumably also Content-Length. However, I'm not sure if that's going to cause other problems e.g. if the original prepared request had some form of transfer encoding pre-applied that I would need to undo in the headers. It's also a bit less convenient since that has to be done in the code that deals with the request itself (and hence knows the session, URL etc), rather than in the code that prepares the data.

http://stackoverflow.com/comment/91262306
has text: Fix your indentation
comment on: http://stackoverflow.com/q/52155783
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52214332
has comment: http://stackoverflow.com/comment/91396539
has comment: http://stackoverflow.com/comment/91395439
downvote count: 2
tagged with: mysql
has comment: http://stackoverflow.com/comment/91396469
type: Question
score: -2
has comment: http://stackoverflow.com/comment/91396171
has answer: http://stackoverflow.com/a/52225080
has title: Operands missing in MySQL statement
has comment: http://stackoverflow.com/comment/91395892
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91397181
has comment: http://stackoverflow.com/comment/91397324
has comment: http://stackoverflow.com/comment/91378017
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91396997
tagged with: python
has body: I'm getting an arguments error from the MySQL module looking for 4 operands. I just don't see which operands it's looking for. It works for some case types and not others. Line numbers of error (trimmed at bottom which refers to MySQL library): Traceback (most recent call last): File "/Users/christoph/PycharmProjects/physicianWorkQueueProject/physicianWorkQueueProject.py", line 158, in &lt;module&gt; parse() File "/Users/christoph/PycharmProjects/physicianWorkQueueProject/physicianWorkQueueProject.py", line 138, in parse c.execute(getPhysiciansql_cmd) ... mysql.connector.errors.DataError: 1241 (21000): Operand should contain 4 column(s) #!/usr/bin/python ################################################## # This is a prototype pathologist work queue management system # The program calls out to a database of pathologists, their specialities, # and an index of case types and their intended specialists # # Usage: Run at your command line. You will then enter case numbers (which aren't validated (currently)) # and case types (which are validated). The program will distribute the entered case as follows: # # If the case is intended for generalists, a system that amounts to names being pulled from a hat # is employed. When a name is selected (at random), the case is entered into that pathologists' work queue. # That pathologists' name is not returned to the pool. # The cycle will then repeat with a random name picked every time, in this same way, for generalist-requiring cases, # until the entirety of names have been pulled. At this point, all names are returned to the pool and the whole cycle # begins again # # For the specialist requiring cases, the name-draw system is bypassed and the case is directly entered # into the pathologists' work queue. # 16 Aug 2018 # My Real Name ################################################## import mysql.connector as mariaDB import time import pandas as pd from random import choice def distributefairly(inputCaseNumber, inputcasetype): # …
has comment: http://stackoverflow.com/comment/91378980

http://stackoverflow.com/a/65208534
type: Answer
answers question: http://stackoverflow.com/q/52247428
score: 0
has body: MS Excel, Libre Office and Google Spreadsheets import numeric-only cells as the number, so if it is a long string of a number (e.g. tweetid) then they convert it to scientific notation. A workaround solution is to append a non-numeric text ( underscore character _ for example) to the number when you output your csv file from Python. Another solution that works only with Libre Office Calc, when you open a csv file it will pop-up a menu before loading it. So if select the column you want to be treated as text, and then from the menu just above change the "Column type" to "Text", and hit OK, then it will load the column without converting it to scientific notation. See the image below for visual illustration.

http://stackoverflow.com/comment/91509995
has text: @NadunPerera See my edit, I was able to get this working with a minimal `main.py` file, perhaps start there and add back the rest of your original file to see where it stops working.
type: Comment
comment on: http://stackoverflow.com/a/52261528
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91286122
type: Comment
has text: The problem is that I can't pass symbol '+' to query params
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52163092

http://stackoverflow.com/q/52212879
tagged with: lexer
tagged with: coroutine
type: Question
downvote count: 0
has title: Coroutines vs generators for parsing
linked to: http://stackoverflow.com/q/715758
favorite count: 0
duplicate of: http://stackoverflow.com/q/715758
tagged with: parsing
answer count: 0
upvote count: 2
type: UnansweredQuestion
has body: My understanding is coroutines vs generators is push vs pull model. Both, I think, can work for parsing, to implement hand-coded recursive descent parser. Just trying to choose, what are pros and cons. Also would be grateful for code examples. Edit: the question was marked as a possible duplicate. It is different, I believe. This question is mostly about applicability of coroutines vs generators to the problem of parsing. Not about their differences in general.
tagged with: python
score: 2

http://stackoverflow.com/q/52212539
score: 1
type: Question
has answer: http://stackoverflow.com/a/52212608
tagged with: led
tagged with: raspberry-pi
downvote count: 0
has title: Change led blinking interval with button input in python
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: gpio
upvote count: 1
tagged with: python
has body: I want to change the blinking time of LED with every button press. The code i written in python do not respond to button input clicks. what chages does it need?looks like callback isnt working import RPi.GPIO as GPIO from time import sleep inbutton = 13 outpin = 7 z = 1 def init(): GPIO.setmode(GPIO.BOARD) GPIO.setup(outpin, GPIO.OUT) GPIO.setup(inbutton, GPIO.IN, pull_up_down=GPIO.PUD_UP) global z z = 1 def zest(): global z if z == 1: z = 2 while z == 2: GPIO.output(outpin, 1) print("led on") sleep(1) GPIO.output(outpin, 0) print("led off") sleep(1) elif z == 2: z = 1 while z == 1: GPIO.output(outpin, 1) print("led on") sleep(2) GPIO.output(outpin, 0) print("led off") sleep(2) def loop(): GPIO.add_event_detect(inbutton, GPIO.FALLING, callback=zest(), bouncetime=1000) if __name__ == '__main__': init() try: while True: loop() except KeyboardInterrupt: GPIO.output(outpin, 0) GPIO.cleanup() On running LED blinks with 1second interval. but dont respond to button click.experts out there please have a look.

http://stackoverflow.com/comment/91382849
type: Comment
comment on: http://stackoverflow.com/a/52216552
score: 1
type: AnswerComment
has text: Thank you very much, plus the sentence you provided "wsgi-file = EWP_OMS/wsgi.py", and I succeeded after changing the sentence" pythonpath =/var/ EWP_OMS_ENV "to" virtualenv=/var/ EWP_OMS_ENV"

http://stackoverflow.com/a/52217328
score: 0
has comment: http://stackoverflow.com/comment/91385536
type: Answer
has comment: http://stackoverflow.com/comment/91385088
answers question: http://stackoverflow.com/q/52217180
has comment: http://stackoverflow.com/comment/91383969
has body: Instead of generic sum, you have to apply a custom function. This one, for example works on your example: import numpy as np f = lambda x: x[x.notnull()][0] if any(x.notnull()) else np.nan df['w'] = df[list('xyz')].apply(f, axis=1)

http://stackoverflow.com/a/52214013
answers question: http://stackoverflow.com/q/52206407
score: 2
upvote count: 2
has body: Try this: cnts = cv2.findContours(gray,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2] xcnts = np.vstack((x.reshape(-1,2) for x in cnts)) print(xcnts.shape) It return (698, 2) for this image (from opencv - plot contours in an image):
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52206407
type: Answer

http://stackoverflow.com/comment/91226563
has text: As I showed in the screenshot it gives me `01` for day and month both. Not really sure why you don't get it.
type: Comment
comment on: http://stackoverflow.com/a/52137676
score: 0
type: AnswerComment

http://stackoverflow.com/a/52168993
has body: You can split your logic into 2 steps. First sum by cast and year using GroupBy + sum. Then find the maximum revenue by year using GroupBy + idxmax: # sum by cast and year df_summed = df.groupby(['cast', 'year'])['revenue'].sum().reset_index() # maximums by year res = df_summed.loc[df_summed.groupby('year')['revenue'].idxmax()] print(res) cast year revenue 3 NickRobinson 2012 3.401340e+09 0 BryceDallasHoward 2015 1.568978e+09 For the above output, I've used more interesting data: id cast year revenue title 135397 ChrisPratt 2015 1.392446e+09 JurassicWorld 135397 BryceDallasHoward 2015 1.568978e+09 SomeMovie 135397 IrrfanKhan 2012 1.392446e+09 JurassicWorld 135397 NickRobinson 2012 1.046987e+09 JurassicWorld 135398 NickRobinson 2012 2.354353e+09 SomeOtherMovie
accepted answer of: http://stackoverflow.com/q/52168725
type: Answer
answers question: http://stackoverflow.com/q/52168725
upvote count: 1
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/comment/91341654
comment on: http://stackoverflow.com/a/52195764
type: Comment
has text: Btw, I made the changes as mentioned and it gave me the following error while terminating, `Exception RuntimeError: 'main thread is not in main loop' in <bound method DoubleVar.__del__ of <Tkinter.DoubleVar instance at 0x7f86a746d7e8>> ignored Tcl_AsyncDelete: async handler deleted by the wrong thread Aborted (core dumped)`
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91447332
has text: I'm sure there were more comments on this question before...they have disappeared. Anyway it would be good to know why solutions liek distanceTransform "don't give me the path I want" -- what is the problem with the found path?
comment on: http://stackoverflow.com/q/52196231
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/52260698
has comment: http://stackoverflow.com/comment/91469000
tagged with: pandas
has comment: http://stackoverflow.com/comment/91468998
has comment: http://stackoverflow.com/comment/91469144
accepted answer: http://stackoverflow.com/a/52260856
has title: How to create a pandas dataframe with a column as array
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52260856
has body: I want to create a dataframe with one of the column as a list or array But an attempt to do so gives an error 'Must have equal len keys and value when setting with an iterable' Please support eg data.loc[0,'emails']={'a@a.com','b@b.com'} =&gt;error data.loc[0,'emails']='a@a.com' =&gt;No error Data=> &gt; Name | emails ___________________________ &gt; Judas |['j@a.com','x@y.com'] &gt; Priest|['x@a.com','x@y.com','j@k.com'] This scenario could be one like trying to get only list of emails as a column from one of the columns which contains very long texts.
possible better answer: http://stackoverflow.com/a/52260873
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/52260873
upvote count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/91469265
favorite count: 0

http://stackoverflow.com/a/52226234
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91402532
has comment: http://stackoverflow.com/comment/91403351
upvote count: 1
has comment: http://stackoverflow.com/comment/91403284
has body: You could use the minor and major ticklabels to alternate between showing the label above and below the axis. import matplotlib.pyplot as plt fig, ax = plt.subplots() D = {'label1': 7.33, 'label2': 7.12, 'label3': 4.26, 'label4': 6.98} labs, vals = zip(*sorted([(k,v) for k,v in D.items()], key=lambda t: t[1] )) ticks = ["{}\n{}".format(k,v) for k,v in zip(labs,vals)] ax.set_xticks(vals[::2]) ax.set_xticklabels(ticks[::2]) ax.set_xticks(vals[1::2], minor=True) ax.set_xticklabels(ticks[1::2], minor=True, va="bottom") ax.tick_params(which="minor", direction="in", pad=-10 ) plt.plot(vals, list(range(len(vals)))) plt.show()
has comment: http://stackoverflow.com/comment/91405524
type: Answer
has comment: http://stackoverflow.com/comment/91402623
answers question: http://stackoverflow.com/q/52225713

http://stackoverflow.com/q/52171916
tagged with: rotation
has comment: http://stackoverflow.com/comment/91314535
has comment: http://stackoverflow.com/comment/91321528
score: 0
has comment: http://stackoverflow.com/comment/91328524
tagged with: 3d
has body: I want to make something like a simple 3D viewer (maybe editor). So one of my goals is to learn how to rotate 3D objects for example using mouse. I took "3D Rotating Monkey Head" example and changed some code in the main.py file. I used functions of converting the Euler angles into quaternions and back - so I achieved the closest result. So the app works almost as it should (demo gif on imgur) But there is one annoying problem - an unwanted rotation along the z axis (tilt?). You can see this here (demo gif on imgur) it is obvious that this should not be so. Is there a way to get rid of this tilt? gl and quaternions are new topics for me. Maybe I did something wrong. My code is here (only main.py) from kivy.app import App from kivy.clock import Clock from kivy.core.window import Window from kivy.uix.widget import Widget from kivy.resources import resource_find from kivy.graphics.transformation import Matrix from kivy.graphics.opengl import * from kivy.graphics import * from objloader import ObjFile #============== quat ========================================================================= import numpy as np from math import atan2, asin, pi, cos, sin, radians, degrees def q2e(qua): L = (qua[0]**2 + qua[1]**2 + qua[2]**2 + qua[3]**2)**0.5 w = qua[0] / L x = qua[1] / L y = qua[2] / L z = qua[3] / L Roll = atan2(2 * (w * x + y * z), 1 - 2 * (x**2 + y**2)) if Roll &lt; 0: Roll += 2 * pi temp = w * y - z * x if temp &gt;= 0.5: temp = 0.5 elif temp &lt;= -0.5: temp = -0.5 Pitch = asin(2 * temp) Yaw = atan2(2 * (w * z + x * y), 1 - 2 * (y**2 + z**2)) if Yaw &lt; 0: Yaw += 2 * pi return [Yaw,Pitch,Roll] def e2q(ypr): y,p,r = ypr roll = r / 2 pitch = p / 2 yaw = y / 2 w = cos(roll) * cos(pitch) * cos(yaw) + \ sin(roll) * sin(pitch) * sin(yaw) x = sin(roll) * cos(pitch) * cos(yaw) - \ cos(roll) * sin(pitch) * sin(yaw) y = cos(roll) * sin(pitch) * cos(yaw) + \ sin(roll) * cos(pitch) * sin(yaw) z = cos(roll) * cos(pitch) * sin(yaw) + \ sin(roll) * sin(pitch) * cos(yaw) qua = […
accepted answer: http://stackoverflow.com/a/52193929
answer count: 1
has comment: http://stackoverflow.com/comment/91328896
has title: Python: rotating 3D objects in kivy (unwanted tilt)
has comment: http://stackoverflow.com/comment/91328992
has comment: http://stackoverflow.com/comment/91321867
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/91328708
type: AnsweredQuestion
tagged with: euler-angles
has answer: http://stackoverflow.com/a/52193929
type: Question

http://stackoverflow.com/q/52160584
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91271305
accepted answer: http://stackoverflow.com/a/52161467
type: Question
has comment: http://stackoverflow.com/comment/91270828
has answer: http://stackoverflow.com/a/52161467
has body: Will like to ask u all how do I go about calculating returns or spread difference between each ID. Will like to use a function such as a define function etc. Example: The difference between each high for id 1 and 2, The difference between each close for id 1 and 2. Many thanks.
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
upvote count: 1
has title: Calculating many rows using a function
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91271155
favorite count: 0
has comment: http://stackoverflow.com/comment/91271576

http://stackoverflow.com/a/52146029
downvote count: 0
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91242451
answers question: http://stackoverflow.com/q/52145792
has body: You may achieve what you need with a solution like this: import re s="""Claim Status\r\n[Primary Status: Paidup to Rebilled]\r\nGeneral Info.\r\n[PA Number: #######]\r\nClaim Insurance: Modified\r\n[Ins. Mode: Primary], [Corrected Claim Checked], [ICN: #######], [Id: ########]""" res = [] for m in re.finditer(r'^(.+)(?:\r?\n\s*\[(.+)])?\r?$', s, re.M): t = [] t.append(m.group(1).strip()) if m.group(2): t.extend([x.strip() for x in m.group(2).strip().split('], [') if ':' in x]) res.append(tuple(t)) print(res) See the Python online demo. Output: [('Claim Status', 'Primary Status: Paidup to Rebilled'), ('General Info.', 'PA Number: #######'), ('Claim Insurance: Modified', 'Ins. Mode: Primary', 'ICN: #######', 'Id: ########')] With the ^(.+)(?:\r?\n\s*\[(.+)])?\r?$ regex, you match two consecutive lines with the second being optional (due to the (?:...)? optional non-capturing group), the first is captured into Group 1 and the subsequent one (that starts with [ and ends with ]) is captured into Group 2. (Note that \r?$ is necessary since in the multiline mode $ only matches before a newline and not a carriage return.) Group 1 value is added to a temporary list, then the contents of the second group is split with ], [ (if you are not sure about the amount of whitespace, you may use re.split(r']\s*,\s*\[', m.group(2))) and then only add those items that contain a : in them to the temporary list.
accepted answer of: http://stackoverflow.com/q/52145792
type: AcceptedAnswer

http://stackoverflow.com/a/52195081
has comment: http://stackoverflow.com/comment/91340681
answers question: http://stackoverflow.com/q/52194859
type: Answer
has comment: http://stackoverflow.com/comment/91340240
has comment: http://stackoverflow.com/comment/91340249
has comment: http://stackoverflow.com/comment/91340102
score: 0
has comment: http://stackoverflow.com/comment/91339954
has body: If you want to fix this from the numpy side… Well, you probably don't want to modify numpy to understand non-standard descr strings, and I suspect that even if you treat that descr string as what it seems to be claiming you'd get garbage anyway. But you can do a hacky workaround. If you open the binary file, it should start with something like this: \x93NUMPY\x01\x00v\x00{'descr': '&lt;?24', 'fortran_order': False, 'shape': (30, 20), } … followed by some whitespace ending in a newline before the raw bytes. You can edit this carefully in a hex editor or text editor, or with Python code that opens the file in binary mode, reads it, does some normal string operations on the bytes, and writes it back out. In particular, the bit that looks like a Python dict repr really is exactly that, and the values mean exactly what you think they mean. Loading the file ends up trying to create an np.dtype('&lt;?24'), and that's where the error comes from. If you just edit the descr and shape values, and make sure to keep the dict repr the same length (by padding with whitespace), that will give you something you can load. So, what does &lt;?24 mean? Well, it's not a valid format as specified by PEP 3118 and struct, but it does fit the pattern of numpy's extensions to that format. For example, in numpy, you can specify f8, meaning "same as f but 8 bytes". So, presumably, this means a 24-byte little-endian version of ?, which means _Bool if compiled with C99, char if not, and is meant to be interpreted as bool in Python. So, if numpy allowed this descr to specify a dtype, what it would mean is that every cell is 24 bytes, interpreted as a little-endian integer interpreted as a bool. Of course numpy doesn't know how to handle integers of any length but 1, 2, 4, or 8 bytes, and it expects bools to be 1 byte, so it isn't allowed. But you could read the same thing as 24 separate bools. How do you do that? Just change the descr string to '?', and the shape to (30, 20, 24), and now you've go…
has comment: http://stackoverflow.com/comment/91341403

http://stackoverflow.com/a/64289084
answers question: http://stackoverflow.com/q/52129909
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: This "should" be a general solution using tf.gather_nd (I've only tested for rank 2 and 3 tensors along the last axis): def torch_gather(x, indices, gather_axis): # if pytorch gather indices are # [[[0, 10, 20], [0, 10, 20], [0, 10, 20]], # [[0, 10, 20], [0, 10, 20], [0, 10, 20]]] # tf nd_gather needs to be # [[0,0,0], [0,0,10], [0,0,20], [0,1,0], [0,1,10], [0,1,20], [0,2,0], [0,2,10], [0,2,20], # [1,0,0], [1,0,10], [1,0,20], [1,1,0], [1,1,10], [1,1,20], [1,2,0], [1,2,10], [1,2,20]] # create a tensor containing indices of each element all_indices = tf.where(tf.fill(indices.shape, True)) gather_locations = tf.reshape(indices, [indices.shape.num_elements()]) # splice in our pytorch style index at the correct axis gather_indices = [] for axis in range(len(indices.shape)): if axis == gather_axis: gather_indices.append(gather_locations) else: gather_indices.append(all_indices[:, axis]) gather_indices = tf.stack(gather_indices, axis=-1) gathered = tf.gather_nd(x, gather_indices) reshaped = tf.reshape(gathered, indices.shape) return reshaped

webdriver
tags question: http://stackoverflow.com/q/52253150
tags question: http://stackoverflow.com/q/52177780
tags question: http://stackoverflow.com/q/52245411
tags question: http://stackoverflow.com/q/52240403
tags question: http://stackoverflow.com/q/52166692
tags question: http://stackoverflow.com/q/52126812
tags question: http://stackoverflow.com/q/52216976
type: Tag
tags question: http://stackoverflow.com/q/52115190
tags question: http://stackoverflow.com/q/52187248
tags question: http://stackoverflow.com/q/52262584
tags question: http://stackoverflow.com/q/52155252
tags question: http://stackoverflow.com/q/52209043
tags question: http://stackoverflow.com/q/52128266
tag name: webdriver
tags question: http://stackoverflow.com/q/52233552
tags question: http://stackoverflow.com/q/52172202
tags question: http://stackoverflow.com/q/52177460

http://stackoverflow.com/comment/91364370
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52185891
type: Comment
has text: amazing explanations and ideas. Simple and elegant! In the generator version, I think you meant `files.apply(tf.contrib.data.parallel_interleave(wrap_generator, cycle_length=N))` after fetching the files. Chose the generator approach so that the model need not wait until entire file is read - i.e. data prep and training can go in parallel. In order to test this hypothesis and finding the right settings for these APIs (like cycle_length etc), is there a way to visualize - % time spent in CPU and % time spent in IO for a run, something like this https://youtu.be/SxOsJPaxHME?t=977?

http://stackoverflow.com/a/52128477
has comment: http://stackoverflow.com/comment/91327327
accepted answer of: http://stackoverflow.com/q/52128407
has comment: http://stackoverflow.com/comment/91207559
answers question: http://stackoverflow.com/q/52128407
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91207659
has body: As per your latest comment you want to print last name which are in second column(index 1) If fieldnames are not present then you should not use DictReader as it will take whatever in first row as key import csv with open('cs.csv', newline='') as csvfile: reader = csv.reader(csvfile) for row in reader: print(row[1]) #-------------------------------------------------- # fieldnames are present import csv with open('cs.csv', newline='') as csvfile: reader = csv.DictReader(csvfile) #print(reader.fieldnames) look_for = reader.fieldnames[1] #since L_name is at index 1 for row in reader: print(row[look_for]) ''' csv file contents F_Name,L_Name Sherlock,Holmes Bruce,Wayne OrderedDict([('F_Name', 'Sherlock'), ('L_Name', 'Holmes')]) Holmes OrderedDict([('F_Name', 'Bruce'), ('L_Name', 'Wayne')]) Wayne ['F_Name', 'L_Name'] Holmes Wayne '''
has comment: http://stackoverflow.com/comment/91207919
type: Answer
has comment: http://stackoverflow.com/comment/91317565
has comment: http://stackoverflow.com/comment/91207673
has comment: http://stackoverflow.com/comment/91207455
downvote count: 0
score: 1

http://stackoverflow.com/comment/91437364
type: Comment
type: AnswerComment
has text: And please choose the most helpful answer by clicking on the tick under its score at its top left side.
comment on: http://stackoverflow.com/a/52243880
score: 0

http://stackoverflow.com/comment/91212280
comment on: http://stackoverflow.com/q/52130902
score: 0
has text: @MitchelPaulin indeed, here is the link https://www.hackerrank.com/challenges/the-minion-game/problem
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52151354
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91253215
type: Answer
accepted answer of: http://stackoverflow.com/q/52151121
has body: You can store them in a list. As an example: n=input() testResults = [] for i in range (0,int(n)): inp = input() output = runCase(inp) testResults.append(str(output)) for result in testResults: print(results) Str converts output to string and append adds it to the end of the list.
answers question: http://stackoverflow.com/q/52151121

http://stackoverflow.com/a/52181587
score: 0
type: AcceptedAnswer
has body: First point: the tags you're looking for is not "row" but "col". Second point: those tags are not direct children of the root node, they are nested in entity −> spreadsheetContainer -> row, so you need to use an XPath expression (or to manually traverse the dom, but xpath does it for you...) Third point: your XML is namespaced (cf the xmlns="http://www.example.com attrib in the root tag) so you need to namespace the xpath expression (or any tag lookup actually). So the code you want is actually: from lxml.etree import ElementTree as ET namespace = "{http://www.example.com}" path = "{0}entity/{0}spreadsheetContainer/{0}row/{0}col".format(namespace) root = ET.parse("example.xml") values = [col.text for col in root.findall(path)]
type: Answer
answers question: http://stackoverflow.com/q/52180919
accepted answer of: http://stackoverflow.com/q/52180919

http://stackoverflow.com/a/52213467
has body: Maintain a dictionary to keep track of frequencies of each character of the string (comments inline) def is_it_correct(inp): if(len(inp) != 5): return False # store characters in a dictionary; key=ASCII of a character, value=it's frequency in the input string ind = 0 dictionary = dict() while(ind &lt; len(inp)): cur_char = inp[ind] cur_int = ord(cur_char) if(dictionary.get(cur_int) == None): dictionary[cur_int] = 1 else: dictionary[cur_int] = dictionary[cur_int]+1 ind = ind+1 # Make sure there's only one digit (0-9) i.e ASCII b/w 48 &amp; 57 # Also, make sure that there are exactly 4 lower case alphabets (a-z) i.e ASCII b/w 97 &amp; 122 digits = 0 alphabets = 0 for key, val in dictionary.items(): if(key &gt;= 48 and key &lt;= 57): digits = digits+val if(key &gt;= 97 and key &lt;= 122): alphabets = alphabets+val if(digits != 1 or alphabets != 4): return False # you should have 4 distinct ASCII values as your dictionary keys (only one ASCII is repeating in 5-length string) if(len(dictionary) != 4): return False return True ret = is_it_correct("b3ksl") print(ret)
upvote count: 1
answers question: http://stackoverflow.com/q/52213070
score: 1
accepted answer of: http://stackoverflow.com/q/52213070
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/52138950
downvote count: 0
has comment: http://stackoverflow.com/comment/91227624
answers question: http://stackoverflow.com/q/52138936
has body: You can use os.get_terminal_size().columns to get the number of columns in the terminal and then print the necessary spaces to centralise your text: import os def print_centre(s): print(' ' * ((os.get_terminal_size().columns - len(s))//2) + s) Some improvements (as pointed out by abarnert): shutil.get_terminal_size is more reliable than os.get_terminal_size. You can use s.center(...) for more readability. Which gives a neater solution: import shutil def print_centre(s): print(s.center(shutil.get_terminal_size().columns))
has comment: http://stackoverflow.com/comment/91227630
upvote count: 3
type: Answer
score: 3

http://stackoverflow.com/comment/91337118
type: Comment
type: QuestionComment
score: 1
has text: Where is that input coming from to begin with?
comment on: http://stackoverflow.com/q/52193580

http://stackoverflow.com/comment/91280232
type: Comment
comment on: http://stackoverflow.com/a/52164125
type: AnswerComment
has text: So here you got 2 versions of pyasn1 one is 0.1.9 and other 0.2.2. I suggest you to uninstall pyasn1 completely "pip uninstall pyasn1-modules==0.1.9" and "pip uninstall pyasn1-modules==0.2.2"....and use pip install -U pyasn1 pyasn1-modules.
score: 0

http://stackoverflow.com/comment/91403847
score: 0
comment on: http://stackoverflow.com/q/52227120
type: Comment
type: QuestionComment
has text: I'm a little confused: what exactly are you comparing about/between the files? Are you just looking for matching lines?

http://stackoverflow.com/comment/91224918
type: AnswerComment
has text: Anyway I have solved it by going from the other end - extending ProfileSerializer which has user field
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52130100

http://stackoverflow.com/a/75902600
answers question: http://stackoverflow.com/q/52169051
downvote count: 0
score: 1
upvote count: 1
has body: The canonical method is to reduce all boolean conditions into a single boolean condition and filter the frame by it. So for the task at hand, to filter a dataframe by a condition on its index and its columns, write two boolean conditions and reduce into one using &amp; (as suggested by @sacuL). Some alternative methods: eval() may be used for a readable condition df.loc[df.eval('index &lt; 6 and A == 0'), 'C'] = 99 A function may be passed to loc: df.loc[lambda x: (x.index &lt; 6) &amp; (x['A']==0), 'C'] = 99
type: Answer

pandas
tags question: http://stackoverflow.com/q/52124240
tags question: http://stackoverflow.com/q/52213804
tags question: http://stackoverflow.com/q/52237685
tags question: http://stackoverflow.com/q/52127529
tags question: http://stackoverflow.com/q/52254994
tags question: http://stackoverflow.com/q/52250345
tags question: http://stackoverflow.com/q/52123199
tags question: http://stackoverflow.com/q/52181024
tags question: http://stackoverflow.com/q/52269720
tags question: http://stackoverflow.com/q/52255502
tags question: http://stackoverflow.com/q/52149058
tags question: http://stackoverflow.com/q/52169544
tags question: http://stackoverflow.com/q/52207741
tags question: http://stackoverflow.com/q/52260698
tags question: http://stackoverflow.com/q/52200710
tags question: http://stackoverflow.com/q/52170069
tags question: http://stackoverflow.com/q/52118445
tags question: http://stackoverflow.com/q/52222676
tags question: http://stackoverflow.com/q/52183652
tags question: http://stackoverflow.com/q/52113568
tags question: http://stackoverflow.com/q/52264065
tags question: http://stackoverflow.com/q/52215414
tags question: http://stackoverflow.com/q/52270185
tags question: http://stackoverflow.com/q/52196937
tags question: http://stackoverflow.com/q/52125667
tags question: http://stackoverflow.com/q/52125211
tags question: http://stackoverflow.com/q/52264354
tags question: http://stackoverflow.com/q/52180942
tags question: http://stackoverflow.com/q/52200044
tags question: http://stackoverflow.com/q/52201870
tags question: http://stackoverflow.com/q/52141759
tags question: http://stackoverflow.com/q/52165617
tags question: http://stackoverflow.com/q/52202301
tags question: http://stackoverflow.com/q/52195449
tags question: http://stackoverflow.com/q/52217601
tags question: http://stackoverflow.com/q/52160567
tags question: http://stackoverflow.com/q/52176573
tags question: http://stackoverflow.com/q/52144841
tags question: http://stackoverflow.com/q/52254186
tags question: http://stackoverflow.com/q/52120651
tags question: http://stackoverflow.com/q/52235280
tags question: http://stackoverflow.com/q/52224644
tags question: http://stackoverflow.com/q/52221286
tags question: http://stackoverflow.com/q/52152922
tags question: http://stackoverflow.com/q/52177109
tags question: http://stackoverflow.com/q/52265151
tags question: http://stackoverflow.com/q/52206338
tags question: http://stackoverflow.com/q/52244867
tags question: http://stackoverflow.com/q/52257025
tags question: http://stackoverflow.com/q/52234407
tags question: http://stackoverflow.com/q/52159281
tags question: http://stackoverflow.com/q/52166840
tags question: http://stackoverflow.com/q/52146452
tags question: http://stackoverflow.com/q/52200369
tags question: http://stackoverflow.com/q/52253543
tags question: http://stackoverflow.com/q/52241935
tags question: http://stackoverflow.com/q/52135616
tags question: http://stackoverflow.com/q/52115873
tags question: http://stackoverflow.com/q/52190238
tags question: http://stackoverflow.com/q/52235063
tags question: http://stackoverflow.com/q/52118037
tags question: http://stackoverflow.com/q/52174031
tags question: http://stackoverflow.com/q/52149692
tags question: http://stackoverflow.com/q/52175020
tags question: http://stackoverflow.com/q/52225770
tags question: http://stackoverflow.com/q/52239093
tags question: http://stackoverflow.com/q/52162909
tags question: http://stackoverflow.com/q/52236643
tags question: http://stackoverflow.com/q/52243573
tags question: http://stackoverflow.com/q/52225216
tags question: http://stackoverflow.com/q/52142290
tags question: http://stackoverflow.com/q/52164441
tags question: http://stackoverflow.com/q/52186560
tags question: http://stackoverflow.com/q/52250160
tags question: http://stackoverflow.com/q/52151831
tags question: http://stackoverflow.com/q/52195739
tags question: http://stackoverflow.com/q/52213991
tags question: http://stackoverflow.com/q/52257356
tags question: http://stackoverflow.com/q/52209230
tags question: http://stackoverflow.com/q/52187366

http://stackoverflow.com/a/52261274
answers question: http://stackoverflow.com/q/52238803
upvote count: 43
has comment: http://stackoverflow.com/comment/110739434
downvote count: 0
score: 43
has comment: http://stackoverflow.com/comment/91470139
has body: In the past, you were able to simply pass a dictionary to spark.createDataFrame(), but this is now deprecated: mylist = [ {"type_activity_id":1,"type_activity_name":"xxx"}, {"type_activity_id":2,"type_activity_name":"yyy"}, {"type_activity_id":3,"type_activity_name":"zzz"} ] df = spark.createDataFrame(mylist) #UserWarning: inferring schema from dict is deprecated,please use pyspark.sql.Row instead # warnings.warn("inferring schema from dict is deprecated," As this warning message says, you should use pyspark.sql.Row instead. from pyspark.sql import Row spark.createDataFrame(Row(**x) for x in mylist).show(truncate=False) #+----------------+------------------+ #|type_activity_id|type_activity_name| #+----------------+------------------+ #|1 |xxx | #|2 |yyy | #|3 |zzz | #+----------------+------------------+ Here I used ** (keyword argument unpacking) to pass the dictionaries to the Row constructor.
type: Answer
has comment: http://stackoverflow.com/comment/91470274
has comment: http://stackoverflow.com/comment/112308184
has comment: http://stackoverflow.com/comment/115340538

http://stackoverflow.com/a/52262618
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52249488
score: 3
answers question: http://stackoverflow.com/q/52249488
type: AcceptedAnswer
downvote count: 0
has body: You can search the repository on github using the search bar. You'll find it in keras/activations.py, which invokes the same function from the keras backend. All the backends are at keras/backend, and the tensorflow backend specifically is at keras/backend/tensorflow_backend.py. In tensorflow, you can find the corresponding kernel definition at tensorflow/core/kernels/softmax_op.
type: Answer

http://stackoverflow.com/q/52236869
upvote count: 0
answer count: 1
has body: I am trying to get volume-weighted average prices for stocks from the moneycontrol.com website. The parse function is running without any issues but the parse_links function is not getting called. Am i missing something here? # -*- coding: utf-8 -*- import scrapy class MoneycontrolSpider(scrapy.Spider): name = "moneycontrol" allowed_domains = ["https://www.moneycontrol.com"] start_urls = ["https://www.moneycontrol.com/india/stockpricequote"] def parse(self,response): for link in response.css('td.last &gt; a::attr(href)').extract(): if(link): yield scrapy.Request(link, callback=self.parse_links,method='GET') def parse_links(self, response): VWAP= response.xpath('//*[@id="n_vwap_val"]/text()').extract_first() print(VWAP) with open('quotes.txt','a+') as f: f.write('VWAP: {}'.format(VWAP) + '\n')
tagged with: python
accepted answer: http://stackoverflow.com/a/52237929
has title: Issue with scrapy spider
favorite count: 0
score: -1
tagged with: scrapy
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91422964
type: Question
has answer: http://stackoverflow.com/a/52237929

http://stackoverflow.com/comment/91453117
type: Comment
has text: This won't work, as if you given `*args`,`**kwargs` must follow, explicit arguments must come before, `(name, age=12, *args, **kwargs)` this is the correct syntax
comment on: http://stackoverflow.com/a/52252845
type: AnswerComment
score: 0

thumbor
type: Tag
tag name: thumbor
tags question: http://stackoverflow.com/q/52252694

hdp
tag name: hdp
type: Tag
tags question: http://stackoverflow.com/q/52268153

http://stackoverflow.com/comment/91234182
has text: try `list("66")` - what do you get?
score: 1
comment on: http://stackoverflow.com/q/52142154
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91490383
type: AnswerComment
type: Comment
has text: @AntonioAndrés - It depends what need - if want select by label or select by positions, check [this](https://stackoverflow.com/q/31593201) for difference.
comment on: http://stackoverflow.com/a/52270389
score: 0

http://stackoverflow.com/comment/91438233
has text: @AnkurJyotiPhukan: that's.. rather overkill when the logging library has so many hooks to add info to log records.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52161735
type: QuestionComment

function
tags question: http://stackoverflow.com/q/52128868
tag name: function
tags question: http://stackoverflow.com/q/52189421
tags question: http://stackoverflow.com/q/52208401
tags question: http://stackoverflow.com/q/52136632
tags question: http://stackoverflow.com/q/52142333
tags question: http://stackoverflow.com/q/52157840
tags question: http://stackoverflow.com/q/52194511
tags question: http://stackoverflow.com/q/52131147
tags question: http://stackoverflow.com/q/52222112
tags question: http://stackoverflow.com/q/52213184
tags question: http://stackoverflow.com/q/52169506
tags question: http://stackoverflow.com/q/52254935
tags question: http://stackoverflow.com/q/52133976
tags question: http://stackoverflow.com/q/52184372
tags question: http://stackoverflow.com/q/52149415
tags question: http://stackoverflow.com/q/52175598
tags question: http://stackoverflow.com/q/52225266
tags question: http://stackoverflow.com/q/52174366
tags question: http://stackoverflow.com/q/52154434
type: Tag
tags question: http://stackoverflow.com/q/52124536
tags question: http://stackoverflow.com/q/52239990
tags question: http://stackoverflow.com/q/52209673
tags question: http://stackoverflow.com/q/52189954
tags question: http://stackoverflow.com/q/52130222
tags question: http://stackoverflow.com/q/52261821
tags question: http://stackoverflow.com/q/52156341
tags question: http://stackoverflow.com/q/52236214
tags question: http://stackoverflow.com/q/52252354
tags question: http://stackoverflow.com/q/52127689
tags question: http://stackoverflow.com/q/52254721
tags question: http://stackoverflow.com/q/52122645
tags question: http://stackoverflow.com/q/52184796
tags question: http://stackoverflow.com/q/52137420
tags question: http://stackoverflow.com/q/52142539
tags question: http://stackoverflow.com/q/52143042
tags question: http://stackoverflow.com/q/52266566
tags question: http://stackoverflow.com/q/52169281
tags question: http://stackoverflow.com/q/52250125
tags question: http://stackoverflow.com/q/52138391
tags question: http://stackoverflow.com/q/52211636
tags question: http://stackoverflow.com/q/52167816
tags question: http://stackoverflow.com/q/52194648

http://stackoverflow.com/comment/91297465
comment on: http://stackoverflow.com/q/52173227
type: Comment
type: QuestionComment
has text: @KhalilAlHooti I have posted the csv file into my question. It's not a huge file, or rather they are both not huge files..
score: 0

http://stackoverflow.com/comment/91379644
has text: If you were to provide a minimal example to play with and show the different things you actually tried (the key is to make it minimal), this would be a good question.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52215329
score: 0

http://stackoverflow.com/comment/91346264
has text: So you want to get Molecular Formula which is H2O that is it?? just tell us what all you need to extract from the web page you've mentioned. it doesn't matter change in lenght of webpage. as long as you get all your data out of it.
score: 0
comment on: http://stackoverflow.com/q/52198273
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91268951
comment on: http://stackoverflow.com/q/52159382
score: 1
has text: also what do you mean by pass the authorization process?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52192934
answer count: 2
has comment: http://stackoverflow.com/comment/91335672
has comment: http://stackoverflow.com/comment/91336653
has answer: http://stackoverflow.com/a/52193312
favorite count: 0
has comment: http://stackoverflow.com/comment/91336089
has comment: http://stackoverflow.com/comment/91335631
has body: I was watching a presentation and it introduced me to this way of finding the maximum value in a dictionary: c = {"One":1, "Two":2, "Uns":1} max(c,key=c.get) 'Two' I don't understand quite how it works. The 'get' method returns the value for a key, if the key exists in the dictionary. So does the 'max' iterate through each key, find the associated value and then return the key associated with the maximum value? How does it work when the dictionary has multiple maximum values? c = {"One":1, "Two":2, "Uns":1, "Dos": 2} max(c,key=c.get) 'Dos' To experiment further, I tried this: c = {"One":1, "Two":2, "Uns":1} max(c.values(),key=c.get) 1 Why did it return '1' instead of '2'?
tagged with: python
has title: Using max together with the 'get' method for a dictionary
type: AnsweredQuestion
upvote count: 2
score: 1
possible better answer: http://stackoverflow.com/a/52193312
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52193139
accepted answer: http://stackoverflow.com/a/52193139
has comment: http://stackoverflow.com/comment/91335765
has comment: http://stackoverflow.com/comment/91335861

http://stackoverflow.com/comment/136262720
comment on: http://stackoverflow.com/a/77278003
score: 0
type: Comment
has text: As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
type: AnswerComment

http://stackoverflow.com/comment/91432898
comment on: http://stackoverflow.com/q/52240263
type: Comment
type: QuestionComment
has text: Have you considered [`np.average()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.average.html)'s weights attribute?
score: 1

http://stackoverflow.com/a/52192301
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/91334899
has comment: http://stackoverflow.com/comment/91334803
score: 4
answers question: http://stackoverflow.com/q/52191968
has comment: http://stackoverflow.com/comment/91334358
has body: Olivier's answer took the thoughts right out of my head. However, as inspect.stack() is a particularly expensive call, I would consider opting to use something along the lines of: frame = inspect.getframeinfo(inspect.currentframe().f_back, context=1) if frame.code_context[0][0].startswith('@'): print('Used as @decorate: True') else: print("Used as @decorate: False")
has comment: http://stackoverflow.com/comment/91334437

http://stackoverflow.com/comment/91492280
type: AnswerComment
comment on: http://stackoverflow.com/a/52270446
score: 0
type: Comment
has text: Okay @brunodesthuilliers

http://stackoverflow.com/comment/91440889
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52227264
has text: If you want to make post request without changing server side code, then just replace `@Field` with `@Query`. Leave `@FormUrlEncoded @POST("add_user")` . I think this works with retrofit.
type: Comment

http://stackoverflow.com/a/52299204
answers question: http://stackoverflow.com/q/52236276
upvote count: 1
score: 1
downvote count: 0
type: Answer
has body: Try this tuotrial to locate the text: https://www.pyimagesearch.com/2018/08/20/opencv-text-detection-east-text-detector/ Then once you locate you can isolate and use tesseract to recognize it.

http://stackoverflow.com/comment/91466487
comment on: http://stackoverflow.com/q/52259298
has text: Please show what the end result should be for your input file.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91672220
type: AnswerComment
comment on: http://stackoverflow.com/a/52332376
type: Comment
has text: If you want to reproduce the problem you can do the following: select 3 items, let's call it A, B and C and in the first test you have checked in A, in a second test select the same items in the same order and now you have checked in B, and for the third case the same procedure but now you have checked in C.
score: 0

pycrypto
tags question: http://stackoverflow.com/q/52181366
type: Tag
tag name: pycrypto

python
tags question: http://stackoverflow.com/q/52167618
tags question: http://stackoverflow.com/q/52247576
tags question: http://stackoverflow.com/q/52196306
tags question: http://stackoverflow.com/q/52155827
tags question: http://stackoverflow.com/q/52258529
tags question: http://stackoverflow.com/q/52162901
tags question: http://stackoverflow.com/q/52192877
tags question: http://stackoverflow.com/q/52158448
tags question: http://stackoverflow.com/q/52153495
tags question: http://stackoverflow.com/q/52214912
tags question: http://stackoverflow.com/q/52266572
tags question: http://stackoverflow.com/q/52190302
tags question: http://stackoverflow.com/q/52211219
tags question: http://stackoverflow.com/q/52267788
tags question: http://stackoverflow.com/q/52166475
tags question: http://stackoverflow.com/q/52114443
tags question: http://stackoverflow.com/q/52203828
tags question: http://stackoverflow.com/q/52155265
tags question: http://stackoverflow.com/q/52216654
tags question: http://stackoverflow.com/q/52229711
tags question: http://stackoverflow.com/q/52167343
tags question: http://stackoverflow.com/q/52266255
tags question: http://stackoverflow.com/q/52171013
tags question: http://stackoverflow.com/q/52140502
tags question: http://stackoverflow.com/q/52146463
tags question: http://stackoverflow.com/q/52216373
tags question: http://stackoverflow.com/q/52132933
tags question: http://stackoverflow.com/q/52145755
tags question: http://stackoverflow.com/q/52156160
tags question: http://stackoverflow.com/q/52264722
tags question: http://stackoverflow.com/q/52114719
tags question: http://stackoverflow.com/q/52147529
tags question: http://stackoverflow.com/q/52149331
tags question: http://stackoverflow.com/q/52168852
tags question: http://stackoverflow.com/q/52128289
tags question: http://stackoverflow.com/q/52234656
tags question: http://stackoverflow.com/q/52144469
tags question: http://stackoverflow.com/q/52257509
tags question: http://stackoverflow.com/q/52198132
tags question: http://stackoverflow.com/q/52236996
tags question: http://stackoverflow.com/q/52247143
tags question: http://stackoverflow.com/q/52259995
tags question: http://stackoverflow.com/q/52131289
tags question: http://stackoverflow.com/q/52139213
tags question: http://stackoverflow.com/q/52262706
tags question: http://stackoverflow.com/q/52255960
tags question: http://stackoverflow.com/q/52257830
tags question: http://stackoverflow.com/q/52186420
tags question: http://stackoverflow.com/q/52167672
tags question: http://stackoverflow.com/q/52237276
tags question: http://stackoverflow.com/q/52246983
tags question: http://stackoverflow.com/q/52118889
tags question: http://stackoverflow.com/q/52154682
tags question: http://stackoverflow.com/q/52247904
tags question: http://stackoverflow.com/q/52247971
tags question: http://stackoverflow.com/q/52118454
tags question: http://stackoverflow.com/q/52125795
tags question: http://stackoverflow.com/q/52153991
tags question: http://stackoverflow.com/q/52194605
tags question: http://stackoverflow.com/q/52250392
tags question: http://stackoverflow.com/q/52219499
tags question: http://stackoverflow.com/q/52222767
tags question: http://stackoverflow.com/q/52235537
tags question: http://stackoverflow.com/q/52190862
tags question: http://stackoverflow.com/q/52125459
tags question: http://stackoverflow.com/q/52190649
tags question: http://stackoverflow.com/q/52148942
tags question: http://stackoverflow.com/q/52228241
tags question: http://stackoverflow.com/q/52222515
tags question: http://stackoverflow.com/q/52172970
tags question: http://stackoverflow.com/q/52150412
tags question: http://stackoverflow.com/q/52210916
tags question: http://stackoverflow.com/q/52175543
tags question: http://stackoverflow.com/q/52256121
tags question: http://stackoverflow.com/q/52195339
tags question: http://stackoverflow.com/q/52179239
tags question: http://stackoverflow.com/q/52235577
tags question: http://stackoverflow.com/q/52195716
tags question: http://stackoverflow.com/q/52172442
tags question: http://stackoverflow.com/q/52221393

http://stackoverflow.com/q/52167807
has title: Get top K values in pandas series include recurring values
score: 0
has comment: http://stackoverflow.com/comment/91285778
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/91286765
has body: I have a code snippet in python. It gets top K=5 values but don't increment the value of K if the value has already occurred. For example upon giving [1, 3, 3, 5, 5, 6, 1, 4, 8, 9, 34, 66, 124] and K = 5, it should return [1, 3, 3, 5, 5, 6, 1, 4] Here if a value is repeating then it should not increment the value of K. Here is the Python code. But how can I do it in pandas Series?. def get_top_K_uniques(K, nums): ret = [] presense = defaultdict(bool) counter = 0 for each in nums: if not presense[each]: presense[each] = True counter+=1 ret.append(each) if counter == K: return ret Thanks in advance.
has comment: http://stackoverflow.com/comment/91285631
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91285904
has answer: http://stackoverflow.com/a/52168095
has comment: http://stackoverflow.com/comment/91285857
type: Question
has answer: http://stackoverflow.com/a/52169311
has comment: http://stackoverflow.com/comment/91285700

http://stackoverflow.com/a/52241156
has comment: http://stackoverflow.com/comment/91431033
downvote count: 1
answers question: http://stackoverflow.com/q/52241126
has body: input evaluates the specified string given as input. So the specified string has to be a valid python expression. To get a list, you can specify the input as a list explictly &gt;&gt;&gt; lst = input("Enter list values : ") Enter list values : list([1,2,3,4,5,6]) &gt;&gt;&gt; lst [1, 2, 3, 4, 5, 6] Alternatively, you can use raw_input to get a string, split the string and map each element to an int &gt;&gt;&gt; lst = map(int, raw_input("Enter list values : ").split()) Enter list values : 1 2 3 4 5 6 &gt;&gt;&gt; lst [1, 2, 3, 4, 5, 6]
has comment: http://stackoverflow.com/comment/91430955
type: Answer
has comment: http://stackoverflow.com/comment/91430912
upvote count: 2
score: 1

http://stackoverflow.com/q/52131251
possible better answer: http://stackoverflow.com/a/52131309
has answer: http://stackoverflow.com/a/52131309
has body: I have an OrderedDict that each key has more than one value. &lt;key, value1, value2, value3&gt; &lt; 1, 50 , 1000, 20 &gt; &lt; 3, 40 , 2000, 2 &gt; &lt; 5, 30 , 10000, 70 &gt; .. How can I get the key of the item that has the minimum value3? for this example, the minimum value3 would be 2. So, I want to have: &lt; 3, 40 , 2000, 2 &gt; or the key which is 3
answer count: 2
has comment: http://stackoverflow.com/comment/91213038
tagged with: ordereddict
favorite count: 0
accepted answer: http://stackoverflow.com/a/52131285
tagged with: python
has title: minimum value of an multi value OrderedDict
type: AnsweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/91213039
type: Question
has comment: http://stackoverflow.com/comment/91212995
has answer: http://stackoverflow.com/a/52131285
score: -2
downvote count: 3

http://stackoverflow.com/a/52177553
accepted answer of: http://stackoverflow.com/q/52177500
answers question: http://stackoverflow.com/q/52177500
has body: It is from the package https://github.com/koenvanderveen/privateml/blob/master/image_analysis/pond/tensor.py one level up from where your file is.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/52185354
score: 1
has comment: http://stackoverflow.com/comment/91324738
has comment: http://stackoverflow.com/comment/91325402
has comment: http://stackoverflow.com/comment/91324802
has comment: http://stackoverflow.com/comment/91325746
answers question: http://stackoverflow.com/q/52185289
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91325471
downvote count: 0
has body: You can use last_valid_index. Just note that since your series originally contained NaN values and these are considered float, even after filtering your series will be float. You may wish to convert to int as a separate step. # first convert dataframe to numeric df = df.apply(pd.to_numeric, errors='coerce') # extract column B = df.iloc[:, 1] # filter to the last valid value B_filtered = B[:B.last_valid_index()] print(B_filtered) 0 2.0 1 3.0 2 3.0 3 6.0 Name: B, dtype: float64

http://stackoverflow.com/comment/91320003
comment on: http://stackoverflow.com/q/52184919
has text: @UnholySheep The value for rowNum is a counter from a for loop i have earlier in my program, i just used "input" to show that the value is not always the same.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52194694
upvote count: 1
answers question: http://stackoverflow.com/q/52194550
has comment: http://stackoverflow.com/comment/91339346
has comment: http://stackoverflow.com/comment/91339549
has comment: http://stackoverflow.com/comment/91339299
accepted answer of: http://stackoverflow.com/q/52194550
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91339617
type: Answer
has body: As can be seen from the JSON response, the keys you are looking for are located in a list under the markets and runners keys. You should use something like the following: for data in tennis_events: for market in data['markets']: event_id = market['event-id'] for runner in market['runners']: market_id = runner['market-id'] evparid = runner['event-participant-id']
has comment: http://stackoverflow.com/comment/91339388
has comment: http://stackoverflow.com/comment/91339586
score: 1

http://stackoverflow.com/comment/91249858
has text: The problem may be that no one can reproduce the error. On Linux, the code works fine with or without giving the path to chromedriver explicitly. Maybe we need to see more output to see where it is going wrong. You may be able to generate more output with `webdriver.Chrome(service_args=["--verbose", "--log-path=D:\\myprojects\logfile.log"])`, or, if you want to state the path to the executable explicitly: `webdriver.Chrome(executable_path="D:\\myprojects\chromedriver.exe", service_args=["--verbose", "--log-path=D:\\myprojects\logfile.log"])`
score: 0
comment on: http://stackoverflow.com/q/52121506
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52228482
downvote count: 0
score: 1
has body: Using the progress bar's setValue method sets the absolute value, it doesn't adjust the value from where it is. To move the progress bar's value back by 25 when the checkbox is unchecked try: self.ui.fBar.setValue(self.ui.fBar.value() - 25)
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52218698
type: Answer
accepted answer of: http://stackoverflow.com/q/52218698

http://stackoverflow.com/q/52243955
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/91436838
has title: FFT - Peak to Peak, Peak, RMS
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/91436925
has body: I work with vibration, and I am trying to get the following information from a FFT amplitude: Peak to Peak Peak RMS I am performing an FFT on a simple sine wave function, considering a Hanning windowing. Note that the "full amplitude" from the sine wave function is 5, and running the code below the FFT gives me 2.5 amplitude result. So, in this case, I am getting the peak from FFT. What about peak to peak and RMS? P.-S. - I am not interested in the RMS of a bandwidth frequency (i.e parsevall theorem). I am interested in the RMS from each peak, that is usually seen in vibration software. import numpy as np import matplotlib.pyplot as plt f_s = 100.0 # Hz sampling frequency f = 1.0 # Hz time = np.arange(0.0, 10.0, 1/f_s) x = 5 * np.sin(2*np.pi*f*time) N = len(time) T = 1/f_s # apply hann window and take the FFT win = np.hanning(len(x)) FFT = np.fft.fft(win * x) n = len(FFT) yf = np.linspace(0.0,1.0/(2.0*T),N//2) plt.figure(1) plt.plot(yf,2.0/N * np.abs(FFT[0:N//2])) plt.grid() plt.figure(2) plt.plot(time,x) plt.xlabel('time') plt.ylabel('Amplitude') plt.grid() plt.show()
downvote count: 1
tagged with: signal-processing
has answer: http://stackoverflow.com/a/52246432
type: UnansweredQuestion
tagged with: vibration
has comment: http://stackoverflow.com/comment/120892853
score: 1
favorite count: 0
tagged with: fft

http://stackoverflow.com/a/52267284
has comment: http://stackoverflow.com/comment/91482357
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52267256
score: 3
upvote count: 3
has body: You can do reindex . df.reindex(columns=['col2','newcol1','newcol3'],fill_value=-1) Out[183]: col2 newcol1 newcol3 0 2 -1 -1 1 3 -1 -1 2 4 -1 -1

http://stackoverflow.com/comment/91265209
type: Comment
type: QuestionComment
has text: @zvone I have added the complete error report, hope this helps but rest assured this is the code that runs as I have only 1 test file with 1 test case
comment on: http://stackoverflow.com/q/52157214
score: 0

http://stackoverflow.com/q/52257265
has body: I have two arrays, for every item in list table, I want to write data to corresponding item in list drive, inside a for loop in python drive1 =[] drive2 =[] drive4 =[] tables = ['values_1', 'values_2', 'values_4'] drive = [ drive1, drive2, drive4] for item in tables and drive: tab = db[item]
score: 0
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52257418
has comment: http://stackoverflow.com/comment/91461760
accepted answer: http://stackoverflow.com/a/52257418
has comment: http://stackoverflow.com/comment/91461868
has title: Assign values to particular array for particular condition in for loop python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91461732
type: Question
tagged with: arrays

http://stackoverflow.com/comment/91190244
type: Comment
comment on: http://stackoverflow.com/q/52119405
has text: We don't know -- where is your output, and what is wrong with it? [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here.
score: 0
type: QuestionComment

http://stackoverflow.com/q/52237297
has title: Unable to bind local var to nested global var
type: Question
score: 1
has body: Unable to bind the local x of f() to the global var x of the nested g(). Why? def f(): x=0 def g(): global x x+=1 print(x) g() g() # added to make seemingly more practical - &gt;&gt;&gt; f() ... NameError: global name 'x' is not defined
possible better answer: http://stackoverflow.com/a/52237370
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52237348
favorite count: 0
has comment: http://stackoverflow.com/comment/91423202
accepted answer: http://stackoverflow.com/a/52237348
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/19158339
upvote count: 1
has answer: http://stackoverflow.com/a/52237370

http://stackoverflow.com/q/52155204
tagged with: encoding
has answer: http://stackoverflow.com/a/52155335
tagged with: http://stackoverflow.com/tag/c
accepted answer: http://stackoverflow.com/a/52155335
answer count: 3
has comment: http://stackoverflow.com/comment/91260636
has comment: http://stackoverflow.com/comment/91260722
downvote count: 0
has title: Data Encoding in C and Python
favorite count: 0
has answer: http://stackoverflow.com/a/52155372
has answer: http://stackoverflow.com/a/52155403
tagged with: python
possible better answer: http://stackoverflow.com/a/52155372
type: AnsweredQuestion
score: 1
has body: I'm encountering the following question. I've written some double-type data into binary files using C and now I want to read them using Python. When I used python function with open("test.dat","rb") as dfile: data = dfile.read() It gave me b'\x00\x00\x00\x00\x00\x00\xf8?\x00\x00\x00\x00\x00\x00\x04@\x00\x00\x00\x00\x00\x00\n@\x00\x00\x00\x00\x00\x00\x11@' So I tried to decode using data.decode(), then it gave me decoding error. I suppose it was because I used the wrong encoding type. But I tried ascii and utf-8 and they did not work. Therefore my questions is 2-fold: How can i read an binary file without knowing the encoding type? Since i did not give an encoding type when writing the binary file in c, does c encode the data at all? If yes, what kind of encoding type would that be? FYI, the code i used to write binary file in the first place is #include &lt;stdio.h&gt; int main(){ double buffer[4]= {1.5, 2.5, 3.25, 4.25}; FILE *ptr; ptr = fopen("test.dat", "wb"); fwrite(buffer,sizeof(buffer),1,ptr); printf("%ld\n",sizeof(buffer)); return 0; }
upvote count: 1
has comment: http://stackoverflow.com/comment/91260639
type: Question

http://stackoverflow.com/comment/91323843
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52173099
type: AnswerComment
has text: Thanks Ankit for the solution... this worked for me with numeric value. But when i use the same code were p_x and p_y column has alphanumeric value it gives error related to string.

http://stackoverflow.com/a/52263246
accepted answer of: http://stackoverflow.com/q/52263142
answers question: http://stackoverflow.com/q/52263142
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/91510185
has body: EDIT: Now I see your problem. When you use a from a import * it imports everything from a directly into your namespace. This means that instead of using a.Results you should just use Results. If you want to keep it in the a namespace you can import a instead.
upvote count: 1
has comment: http://stackoverflow.com/comment/91476479

http://stackoverflow.com/q/52229522
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91409591
has comment: http://stackoverflow.com/comment/91409144
has body: I am just starting out to play with Dockers. I have read up on Dockers and have watched a few tutorial videos. I am trying to create a simple form using Python that I will build and use Docker to display on my localhost. I am using flask and wtforms. I have pip installed flask, flask_wtf, and wtforms but when I try to build using sudo docker-compose up, I keep getting the error ModuleNotFoundError: No module named 'wtforms'. I have read through many other similar questions on here, but none of the solutions works for me. I have copied the three files I am using below: -- api.py -- # docker test from flask import Flask, render_template, flash, request from flask_restful import Resource, Api from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField app= Flask(__name__) api= Api(app) app.config.from_object(__name__) app.config['SECRET_KEY'] = '7d441f27d441f27567d441f2b6176a' @app.route("/", methods=['GET', 'POST']) class UserForm(Form): salutation= TextField('Salutation:', validators= [validators.required()]) first_name= TextField('First Name:', validators= [validators.required()]) last_name= TextField('Last Name:', validators= [validators.required()]) def welcome(): form = UserForm(request.form) print(form.errors) if request.method == 'POST': salutation=request.form['salutation'] first_name=request.form['first_name'] last_name=request.form['last_name'] print(salutation) print(first_name) print(last_name) if form.validate(): flash('Welcome' + salutation + last_name) else: flash('Please fill in the required fields.') api.add_resource(UserForm, '/') if __name__ == '__main__': app.run(host= '0.0.0.0', port=80, debug=True) -- requirements.txt -- Flask==0.12 flask-restful==0.3.5 wtforms==2.2 -- docker-compose.yml -- version: '2' services: form-service: build: ./form volumes: - ./form:/usr/src/app ports: - 5001:80 -- Dockerfile -- FROM python:3-onbuild COPY . /usr/src/app CMD ["python", "api.py"]
type: Question
has comment: http://stackoverflow.com/comment/91409424
tagged with: docker
score: 0
has title: ModuleNotFoundError: No module named 'wtforms' when trying to docker-compose
tagged with: python

http://stackoverflow.com/a/52200687
has body: For python newbie, studying the Python anti-patterns is a must. This allow one avoid many mistake and bugs. OP apparently has pass experience from other programming language but doesn't aware of better way of working in python. If you study the anti-pattern, you will learn with open() is the better way to open a file. Immediately, you will spot f as a file handler, which will not store any data unless you pass data from f.read() function to another variable. def openfile(filename): with open(filename) as f: data = f.read() # to print out the contents print(data) Using sys.argv is acceptable, but argparse is highly recommended.
answers question: http://stackoverflow.com/q/52200409
score: 3
downvote count: 0
upvote count: 3
type: Answer

http://stackoverflow.com/comment/91310430
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52179044
has text: Also: are you sure you are using `jinja` as the template engine ? I know jinja owes a lot to Django but you code looks like standard django template language.
score: 0

http://stackoverflow.com/a/52136129
has comment: http://stackoverflow.com/comment/91259033
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52135616
has comment: http://stackoverflow.com/comment/91270477
has comment: http://stackoverflow.com/comment/91259552
answers question: http://stackoverflow.com/q/52135616
has body: One observation that could come in handy is that you do not need to sort all the values at each step. Rather, if you ensure that the window is always sorted, all you need to do is insert the new value at the relevant spot, and remove the old one from where it was, both of which are operations that can be done in O(log_2(window_size)) using bisect. In practice, this would look something like def rolling_mean(data): x = sorted(data[:49]) res = np.repeat(np.nan, len(data)) for i in range(49, len(data)): if i != 49: del x[bisect.bisect_left(x, data[i - 50])] bisect.insort_right(x, data[i]) res[i] = np.mean(x[3:47]) return res Now, the additional benefit in this case turns out to be less than what is gained by the vectorization that scipy.stats.trim_mean relies on, and so in particular, this will still be slower than @ChrisA's solution, but it is a useful starting point for further performance optimization. &gt; data = pd.Series(np.random.randint(0, 1000, 50000)) &gt; %timeit data.rolling(50).apply(lambda w: trim_mean(w, 0.06)) 727 ms ± 34.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) &gt; %timeit rolling_mean(data.values) 812 ms ± 42.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) Notably, Numba's jitter, which is often useful in situations like these, also provides no benefit: &gt; from numba import jit &gt; rolling_mean_jit = jit(rolling_mean) &gt; %timeit rolling_mean_jit(data.values) 1.05 s ± 183 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) The following, seemingly far-from-optimal, approach outperforms both of the other approaches considered above: def rolling_mean_np(data): res = np.repeat(np.nan, len(data)) for i in range(len(data)-49): x = np.sort(data[i:i+50]) res[i+49] = x[3:47].mean() return res Timing: &gt; %timeit rolling_mean_np(data.values) 564 ms ± 4.44 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) What is more, this time around, JIT compilation does help: &gt; rolling_mean_np_jit = jit(rolling_mean_np) &gt; %timeit rol…
has comment: http://stackoverflow.com/comment/91260691
type: Answer
has comment: http://stackoverflow.com/comment/91232075
has comment: http://stackoverflow.com/comment/91238189
upvote count: 12
has comment: http://stackoverflow.com/comment/91260784
downvote count: 0
has comment: http://stackoverflow.com/comment/91297104
has comment: http://stackoverflow.com/comment/91239891
score: 12
has comment: http://stackoverflow.com/comment/91269958
has comment: http://stackoverflow.com/comment/91261286
has comment: http://stackoverflow.com/comment/91231999

http://stackoverflow.com/q/52126516
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91204958
has body: I referred from ikolim's answer here: How to fetch data from database and show in table in kivy+python But what I want is just like this: I tried editing the code from the answer to get it but it does not seem to work. Thanks :)
type: UnansweredQuestion
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/91208827
tagged with: kivy-language
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/91233815
linked to: http://stackoverflow.com/q/47013527
has title: Display data from a database in a table in kivy
score: 0

http://stackoverflow.com/q/52162157
answer count: 0
score: 1
tagged with: selenium
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91274685
downvote count: 0
linked to: http://stackoverflow.com/q/41829000
favorite count: 0
type: UnansweredQuestion
has title: Select element of a graph with selenium Xpath when mouseover
tagged with: python
tagged with: xpath
has body: I am using Selenium Xpath to get data from Semrush. At this time, I want to select a label that is only showed when mouse is over of this bar graph. The point is that the labels of the graph are just up when the mouse is over of each bar. I want each of the values of the bar graph. I used selenium KDE to select the link but it didn't worked: elements = driver.find_elements_by_xpath("//div[@id='highcharts-26']/div/span/a") #grab that stuff you wanted? lista=[] for e in elements: lista.append(e.get_attribute('class').strip()) #print text fields dados[i]=lista str1 = ''.join(lista) websites.loc[websites['URL']==i,'1 a 3']=str1 print('keywords 1 a 3' + str1) Can anyone help me?

http://stackoverflow.com/comment/91303311
type: AnswerComment
score: 0
type: Comment
has text: It is as the question says: i want to show tuples in a table and your answer is exactly what I needed however, when I tried to plug it in the project in github, it does not return the output as you answered
comment on: http://stackoverflow.com/a/52168802

http://stackoverflow.com/q/52134403
has comment: http://stackoverflow.com/comment/91218934
tagged with: python
has answer: http://stackoverflow.com/a/52134463
downvote count: 3
type: Question
upvote count: 0
has body: def fancy_divide(list_of_numbers, index): try: try: raise Exception("0") finally: denom = list_of_numbers[index] for i in range(len(list_of_numbers)): list_of_numbers[i] /= denom except Exception as ex: print(ex) Does this code print 0 when you call fancy_divide([0, 2, 4], 0)?
answer count: 1
favorite count: 0
type: UnansweredQuestion
has title: Exception output in python
score: -3

http://stackoverflow.com/comment/91323235
has text: `l[0][1]`, l is your ouput .
score: 0
comment on: http://stackoverflow.com/q/52186737
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91302251
type: Comment
type: QuestionComment
has text: Hi @Ykh before your replay i remove and everything worked very good , and now i add this ` ` and this worked too , can you please explain what ` ` is for with your solution in answer so i can accept the answer
comment on: http://stackoverflow.com/q/52175622
score: 0

http://stackoverflow.com/q/52113864
has comment: http://stackoverflow.com/comment/93891488
tagged with: python
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: machine-learning
linked to: http://stackoverflow.com/q/28759253
tagged with: tensorflow
score: 3
upvote count: 3
has body: I have set up the Google's DeepLab V3 Demo on my local system and it runs successfully after making some minor changes. It's as: # -*- coding: utf-8 -*- # DeepLab Demo # This demo will demostrate the steps to run deeplab semantic segmentation model on sample input images. import os from io import BytesIO import tarfile import tempfile from six.moves import urllib from matplotlib import gridspec from matplotlib import pyplot as plt import numpy as np from PIL import Image import tensorflow as tf class DeepLabModel(object): """Class to load deeplab model and run inference.""" INPUT_TENSOR_NAME = 'ImageTensor:0' OUTPUT_TENSOR_NAME = 'SemanticPredictions:0' INPUT_SIZE = 513 FROZEN_GRAPH_NAME = 'frozen_inference_graph' def __init__(self, tarball_path): """Creates and loads pretrained deeplab model.""" self.graph = tf.Graph() graph_def = None # Extract frozen graph from tar archive. tar_file = tarfile.open(tarball_path) for tar_info in tar_file.getmembers(): if self.FROZEN_GRAPH_NAME in os.path.basename(tar_info.name): file_handle = tar_file.extractfile(tar_info) graph_def = tf.GraphDef.FromString(file_handle.read()) break tar_file.close() if graph_def is None: raise RuntimeError('Cannot find inference graph in tar archive.') with self.graph.as_default(): tf.import_graph_def(graph_def, name='') self.sess = tf.Session(graph=self.graph) def run(self, image): """Runs inference on a single image. Args: image: A PIL.Image object, raw input image. Returns: resized_image: RGB image resized from original input image. seg_map: Segmentation map of `resized_image`. """ width, height = image.size resize_ratio = 1.0 * self.INPUT_SIZE / max(width, height) target_size = (int(resize_ratio * width), int(resize_ratio * height)) resized_image = image.convert('RGB').resize(target_size, Image.ANTIALIAS) batch_seg_map = self.sess.run( self.OUTPUT_TENSOR_NAME, feed_dict={self.INPUT_TENSOR_NAME: [np.asarray(resized_image)]}) seg_map = batch_seg_map[0] return resized_image, seg_map def create_pas…
type: Question
tagged with: image-segmentation
has answer: http://stackoverflow.com/a/52922609
answer count: 1
downvote count: 0
has title: Extract Image Segmentation Map from Tensorflow DeepLab v3 Demo
has comment: http://stackoverflow.com/comment/120541753

http://stackoverflow.com/a/52269521
has body: The description of the tf.slim package sheds a little more light onto the differences: Specifically, if you look under "Layers", the following can be found: Layers While the set of TensorFlow operations is quite extensive, developers of neural networks typically think of models in terms of higher level concepts like "layers", "losses", "metrics", and "networks". A layer, such as a Convolutional Layer, a Fully Connected Layer or a BatchNorm Layer are more abstract than a single TensorFlow operation and typically involve several operations. Furthermore, a layer usually (but not always) has variables (tunable parameters) associated with it, unlike more primitive operations. For example, a Convolutional Layer in a neural network is composed of several low level operations: Creating the weight and bias variables Convolving the weights with the input from the previous layer Adding the biases to the result of the convolution. Applying an activation function. Using only plain TensorFlow code, this can be rather laborious: input = ... with tf.name_scope('conv1_1') as scope: kernel = tf.Variable(tf.truncated_normal([3, 3, 64, 128], dtype=tf.float32, stddev=1e-1), name='weights') conv = tf.nn.conv2d(input, kernel, [1, 1, 1, 1], padding='SAME') biases = tf.Variable(tf.constant(0.0, shape=[128], dtype=tf.float32), trainable=True, name='biases') bias = tf.nn.bias_add(conv, biases) conv1 = tf.nn.relu(bias, name=scope) To alleviate the need to duplicate this code repeatedly, TF-Slim provides a number of convenient operations defined at the more abstract level of neural network layers. For example, compare the code above to an invocation of the corresponding TF-Slim code: input = ... net = slim.conv2d(input, 128, [3, 3], scope='conv1_1') In short, the slim operators do some neat abstractions for you so that you do not have to worry about all the nitty-gritty details of TensorFlow - a nice addition if you ask me. It seems, though, that this is still under active development, so I wou…
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/52267314
downvote count: 0
type: Answer

http://stackoverflow.com/q/52194375
has body: Here is my code and memory error when call todense(), I am using GBDT model, and wondering if anyone have good ideas how to work around memory error? Thanks. for feature_colunm_name in feature_columns_to_use: X_train[feature_colunm_name] = CountVectorizer().fit_transform(X_train[feature_colunm_name]).todense() X_test[feature_colunm_name] = CountVectorizer().fit_transform(X_test[feature_colunm_name]).todense() y_train = y_train.astype('int') grd = GradientBoostingClassifier(n_estimators=n_estimator, max_depth=10) grd.fit(X_train.values, y_train.values) Detailed error message, in _process_toarray_args return np.zeros(self.shape, dtype=self.dtype, order=order) MemoryError ... regards, Lin
has answer: http://stackoverflow.com/a/52198654
has comment: http://stackoverflow.com/comment/91338491
accepted answer: http://stackoverflow.com/a/52198654
answer count: 1
downvote count: 0
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/91343159
tagged with: xgboost
has comment: http://stackoverflow.com/comment/91338507
favorite count: 0
has title: memory error when todense in python using CountVectorizer
has comment: http://stackoverflow.com/comment/91341356
has comment: http://stackoverflow.com/comment/91339018
has comment: http://stackoverflow.com/comment/91344266
tagged with: machine-learning
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/52176616
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91338721
has comment: http://stackoverflow.com/comment/91338449
has comment: http://stackoverflow.com/comment/91345416
score: 1
has comment: http://stackoverflow.com/comment/91344355
type: Question

http://stackoverflow.com/q/52267076
upvote count: 0
tagged with: nested-lists
has title: Nested List and count() - Follow-up question
tagged with: python
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/52267129
linked to: http://stackoverflow.com/q/5828123
score: -1
has answer: http://stackoverflow.com/a/52267129
answer count: 1
downvote count: 1
favorite count: 0
has body: A link to the original question: Nested List and count() I was testing the accepted answer's code and found it to not work for list that contain strings. The accepted answer's code: def flatten(seq,container=None): if container is None: container = [] for s in seq: if hasattr(s,'__iter__'): flatten(s,container) else: container.append(s) return container c = flatten([(1,2),(3,4),(5,[6,7,['a','b']]),['c','d',('e',['f','g','h'])]]) print c print c.count('g') d = flatten([[[1,(1,),((1,(1,))), [1,[1,[1,[1]]]], 1, [1, [1, (1,)]]]]]) print d print d.count(1) I tested using this input at first: list1 = [[[1,2,3,4,5],[1,2,3,4,5]],[[1,2,3,4,5],[1,2,3,4,5]],[[1,2,3,4,5],[1,2,3,4,5]]] And it worked. But once I use this: list1 = [[[1,'2',3,4,5],[1,2,3,4,5]],[[1,2,3,4,5],[1,2,3,4,5]],[[1,2,3,4,5],[1,2,3,4,5]]] Note: The first 2 is now a string. It produces this error: RecursionError: maximum recursion depth exceeded I understand recursion, but I don't why this error happens. Initially, I thought it has something to do with '__iter__' but I'm pretty sure strings are iterable because I've checked. For reference, I'm using Python 3.6.4. And I'm still new to Python, please be nice to me :)

http://stackoverflow.com/q/52245645
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52245710
has title: Dynamically set instance attribute in Python
has comment: http://stackoverflow.com/comment/91439779
tagged with: python
has body: I have a class with two instance attributes. For example: class Test(): def __init__(self, parameter): self.one = self.somefunction(parameter) self.two = 'somestring' In the same class I define a function somefunction which will, accordingly to the above coding, be called at the time the object is created. While I tried this, I could set self.one when I return some value inside my somefunction(parameter), like: def somefunction(parameter): return ... However, this doesn't feel like best practice.What's the best way to set an initial value of an instance dynamically?
tagged with: attributes
tagged with: instance
has comment: http://stackoverflow.com/comment/91439517
upvote count: 1
accepted answer: http://stackoverflow.com/a/52245710
type: Question
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91439712
downvote count: 0

http://stackoverflow.com/a/52195154
answers question: http://stackoverflow.com/q/52194210
has body: I looked again at the abc.h5 file described in: how to import .mat-v7.3 file using h5py It was created in Octave with: &gt;&gt; A = [1,2,3;4,5,6]; &gt;&gt; B = [1,2,3,4]; &gt;&gt; save -hdf5 abc.h5 A B Using h5py: In [102]: f = h5py.File('abc.h5','r') In [103]: A = f['A']['value'][:] In [104]: A Out[104]: array([[1., 4.], [2., 5.], [3., 6.]]) In [105]: A.shape Out[105]: (3, 2) In [106]: A.flags Out[106]: C_CONTIGUOUS : True F_CONTIGUOUS : False ... In [107]: A.ravel() Out[107]: array([1., 4., 2., 5., 3., 6.]) So it's a transposed C order array. Apparently that's how MATLAB developers have chosen to store their matrices in HDF5. I could tranpose it in numpy: In [108]: At = A.T In [109]: At Out[109]: array([[1., 2., 3.], [4., 5., 6.]]) In [110]: At.flags Out[110]: C_CONTIGUOUS : False F_CONTIGUOUS : True .... As is normal, a C-order array becomes F-order when transposed. The Octave matrices saved with the older .mat format In [115]: data = io.loadmat('../abc.mat') In [116]: data['A'] Out[116]: array([[1., 2., 3.], [4., 5., 6.]]) In [117]: _.flags Out[117]: C_CONTIGUOUS : False F_CONTIGUOUS : True So the h5py array, transposed, matches the convention that io.loadmat has been using for quite some time. I don't have hdf5storage installed on this OS. But by your tests, it is following the io.loadmat convention - correct shape but F order.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52194210
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/a/52126954
accepted answer of: http://stackoverflow.com/q/52126812
answers question: http://stackoverflow.com/q/52126812
has body: Your error means, that the username has the None value. That in turn means, that your command username = driver.find_element_by_id('email').click() returns None. Why? Because the .click() method returns None. So, split that command into these two: username = driver.find_element_by_id('email') username.click()
type: Answer
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91476498
comment on: http://stackoverflow.com/a/52222953
has text: Thank you! Now it is exactly how I wanted it!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52148490
answers question: http://stackoverflow.com/q/52148437
has body: You may move the \s* into an optional non-capturing group: (?:\b(price|rs)\s*)?(\d+[\s\d.]*\s*?(pkg|k|m|(?:la(?:c|kh|k)|crore|cr)s?|l)\b\.?) ^^^^^^^^^^^^^^^^^^^^ See the regex demo The (?:\b(price|rs)\s*)? pattern will match a word boundary, followed with price or rs that are followed with 0+ whitespace chars, and the whole pattern will be tried once, and the pattern is optional due to ? modifier (the whole sequence of patterns can match 1 or 0 times)
score: 2
accepted answer of: http://stackoverflow.com/q/52148437
upvote count: 2
has comment: http://stackoverflow.com/comment/91246678
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/52677447
type: Answer
has body: The error you post just says "I was looking for one specific DLL and did not find it". Rather than installing other packages and extensions that might, or might not, be or somehow contain the right DLL, you now need to determine exactly what it is that isn't to be found. I can suggest three complementary methods, none absolutely certain to pinpoint the exact problem (of course the voodoo method of "install some package at random and see whether it fixes it" might also work, and often does -- but that's magic, not computer science): the quickest: check the pyimod03_importers.py file at line 714, see what it was doing when the exception was thrown. Due to Windows' library loading strategies, you might be handed a red herring, with a file reported not to be there when it actually is, because it relies on a second missing file whose name you won't be told. the easiest: use a tool like SysInternals' DEPENDS.EXE to inspect the OMR.EXE file. This is almost guaranteed not to work in this case, because the needed imports might be specified in Python format, not in any form that DEPENDS.EXE will recognize. the most comprehensive, but least easy: use a tool like SysInternals' PROCMON, set up the filters to exclude the background noise of Windows' idle state - there will be an awful lot of that - and then fake running OMR.EXE; exclude the additional noise generated by that. You'll need about fortyish filters to be set up. Finally run OMR.EXE. Near the end, you will see a series of attempt to load SOMETHING.DLL, all failed; the first is where the DLL is supposed to be (by either Python or OMR), the others are all suitable alternatives. Then: if the DLL is one of yours, find out how to pack them with the EXE bundle. if it is not, you need to reliably assess where it can be found. It might well be that the suggestion you were given - install MSVC redistributable that-version-or-other - was absolutely correct. Libraries with names like MSVCnn... belong to that package. MSO... files…
score: 0
answers question: http://stackoverflow.com/q/52120694

http://stackoverflow.com/comment/91404343
score: 0
has text: I tried changing the working directory: if os.path.isdir(p): os.chdir(p) files = os.listdir(os.curdir) print("Files found in folder:", files) files.sort(key=os.path.getmtime) which gave me this error: FileNotFoundError: [Errno 2] No such file or directory: 'Anteckningar/20180831.pdf'
type: Comment
comment on: http://stackoverflow.com/a/52226925
type: AnswerComment

concatenation
tags question: http://stackoverflow.com/q/52204115
tags question: http://stackoverflow.com/q/52227295
tags question: http://stackoverflow.com/q/52113872
tags question: http://stackoverflow.com/q/52240343
tags question: http://stackoverflow.com/q/52246136
type: Tag
tag name: concatenation
tags question: http://stackoverflow.com/q/52227213
tags question: http://stackoverflow.com/q/52223045
tags question: http://stackoverflow.com/q/52163474
tags question: http://stackoverflow.com/q/52115527
tags question: http://stackoverflow.com/q/52268652
tags question: http://stackoverflow.com/q/52174095

http://stackoverflow.com/comment/91190316
score: 1
type: AnswerComment
has text: Also, `file.write(info)` should be inside the loop
type: Comment
comment on: http://stackoverflow.com/a/52118928

http://stackoverflow.com/q/52130409
tagged with: regex
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91211164
type: Question
has title: pandas str.extractall find unknown number of groups / regex
has body: After some searching I seem to be coming up a bit blank. I'm also a total regex simpleton... I have a csv file with data like this: header1 header2 row1 "asdf (qwer) asdf" row2 "asdf (hghg) asdf (lkjh)" row3 "asdf (poiu) mkij (vbnc) yuwuiw (hjgk)" I've put double quotes around the rows in header2 for clarity that it is one field. I want to extract each occurrence of words between brackets (). There will be a least one occurrence per row, but I don't know ahead of time how many occurrences of bracketed words will appear in each line. Using the wonderful https://www.regextester.com/ i think the regex i need is \(.*?\) But I keep getting: ValueError: pattern contains no capture groups the code i used was: pattern = r'\(.*?\)' extracted = df.loc[:, 'header2'].str.extractall(pattern) Any help appreciated. thanks
accepted answer: http://stackoverflow.com/a/52130446
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52130446
tagged with: pandas
tagged with: python

http://stackoverflow.com/q/52130673
tagged with: anaconda
type: Question
answer count: 2
has body: I'm trying to write a Python-3.6 script that would set apart empty .aif audio records (i.e. containing ambient noise only) from those which contain speech. My aim is not to recognize speech content - firstly, it's not English, and secondly, it's not needed for my purposes. Nonetheless, I failed to invent something better than to use SpeechRecognition with pocketsphinx for resolving this issue. My idea was quite primitive: import speech_recognition as sr r = sr.Recognizer() emptyRecords = [] for fname in os.listdir(TESTDIR): with sr.AudioFile(TESTDIR + fname) as source: recorded = r.record(source) recognized = r.recognize_sphinx(recorded) if len(recognized) &lt;= 10: print("{} seems to be an empty record.".format(fname)) emptyRecords.append(fname) That is, I tried to transform recorded audios into lists of strings and to separate those lists according to an 'intuitive' threshold of 10 words, since sometimes pocketsphinx recognized background noise as a sparse sequence of several interjections. However, this took an extremely long time because of unnecessary speech recognition process - for each record I only needed to check whether it containted more than 10 words and nothing more. As far as I understand from SpeechRecognition's docs, the Recognizer class doesn't contain any attributes or methods that would limit the number of words to be recognized. Could someone suggest a better idea for this issue? Thanks in advance.
tagged with: speech-recognition
accepted answer: http://stackoverflow.com/a/52137079
tagged with: pocketsphinx
tagged with: python
has title: Python: setting apart speech from empty audio records
score: 0
possible better answer: http://stackoverflow.com/a/52151034
has answer: http://stackoverflow.com/a/52151034
has answer: http://stackoverflow.com/a/52137079
type: AnsweredQuestion

http://stackoverflow.com/comment/91430034
type: QuestionComment
has text: The other `except KeyboardInterrupt:` is inside an infinite loop, so if that's where the Ctrl-C gets caught, it goes nowhere. Why are you even catching this exception if you actually want it to end the program?
comment on: http://stackoverflow.com/q/52240620
score: 0
type: Comment

http://stackoverflow.com/q/52235621
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/53061614
tagged with: python
type: UnansweredQuestion
upvote count: 3
score: 3
has title: SALib.analyze.delta: What is the definition of the return parameters delta and delta_conf?
type: Question
has body: I wanted to implement a sensitivity analysis on given input and output data in python. The design of the input parameters is based on Latin hypercubes, so I decided to use the delta module of SALib. I can not find some documentation what exactly is the meaning of the return parameter delta, delta_conf, S1, S1_conf. Does somebody know the definition and thereby how to understand the results? The documentation of the package referres to some papers, but i have no access. .. [1] Borgonovo, E. (2007). "A new uncertainty importance measure." Reliability Engineering &amp; System Safety, 92(6):771-784, doi:10.1016/j.ress.2006.04.015. .. [2] Plischke, E., E. Borgonovo, and C. L. Smith (2013). "Global sensitivity measures from given data." European Journal of Operational Research, 226(3):536-550, doi:10.1016/j.ejor.2012.11.047. Many thanks in advance!

http://stackoverflow.com/comment/91317198
type: Comment
type: QuestionComment
has text: Thanks, this thread was quite useful. I did it in a slightly different way than detailed there and will outline that in an answer, for others to see.
comment on: http://stackoverflow.com/q/52174867
score: 0

http://stackoverflow.com/comment/91281635
type: AnswerComment
has text: Thanks again for enhancing this! I have found a couple of bugs here.. Please have a look in this [pdf](https://drive.google.com/file/d/18HYOoRqBtjI1ytkKVQCcWusuhgaruinP/view?usp=sharing) for the details.
type: Comment
comment on: http://stackoverflow.com/a/52149678
score: 0

http://stackoverflow.com/q/52267898
type: Question
score: -1
upvote count: 0
answer count: 1
has body: I've been scouring forums for tools/scripts to be able to identify which domains are being used and which domains are not being used within an sde database. I came across a py script tool which works great for .gdb but i keep getting an error when trying it on .sde. # Add as 'Script' in toolbox. # Set Parameters input_workspace as string, output_workspace as string # -------------------------------------------------------------------------- # -------------------------------------------------------------------------- # Import required modules # import arcpy import os # -------------------------------------------------------------------------- # -------------------------------------------------------------------------- # Get Paramaters for Script Tool input_workspace = arcpy.GetParameterAsText(0) # The geodatabase with domains you wish to summarize output_workspace = arcpy.GetParameterAsText(1) # A new file geodatabase which will house the domain info # Set overwrite output arcpy.env.overwriteOutput = True # List the domain objects arcpy.AddMessage("Listing domains in the input workspace.") dList = arcpy.da.ListDomains(input_workspace) # Create the output workspace arcpy.AddMessage("Setting up the output workspace.") arcpy.CreateFileGDB_management(("\\").join(output_workspace.split("\\") [:-1]), output_workspace.split("\\")[-1]) # Create the necessary tables in the output workspace arcpy.AddMessage("Creating tables.") arcpy.AddMessage("\tDomain Properties table.") arcpy.CreateTable_management(output_workspace,"domainProperties","#","#") arcpy.AddMessage("\tRange Domain table.") arcpy.CreateTable_management(output_workspace,"rangeDomains","#","#") arcpy.AddMessage("\tApplied domains table.") arcpy.CreateTable_management(output_workspace,"appliedDomains","#","#") for d in dList: if d.domainType == "CodedValue": arcpy.AddMessage("\t" + d.name + " CV info table.") arcpy.CreateTable_management(output_workspace,"cv_" + d.name + "_details","#","#") # Add the necessary fields…
favorite count: 0
has title: identify inactive/unused domains in SDE database Python
type: UnansweredQuestion
tagged with: python
tagged with: arcgis-server
downvote count: 1
has answer: http://stackoverflow.com/a/52285818

http://stackoverflow.com/comment/91379639
comment on: http://stackoverflow.com/q/52212898
type: Comment
has text: Are you using numpy?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91403822
type: Comment
comment on: http://stackoverflow.com/a/52227133
has text: How do those approaches compare to `df.airline.apply(pd.Series)` ?
score: 0
type: AnswerComment

http://stackoverflow.com/q/52196721
has answer: http://stackoverflow.com/a/52201192
accepted answer: http://stackoverflow.com/a/52201192
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91342904
has comment: http://stackoverflow.com/comment/91342955
tagged with: python-2.7
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91343030
has answer: http://stackoverflow.com/a/52196930
has title: Reading tsv column and store in a dictionary resulting in None values
tagged with: http://stackoverflow.com/tag/csv
has body: I have a tsv file with the following format: first 44 90 org second 80 49 sport third 50 52 NIL The file was written by the following code: id = first before = 44 after = 90 taregt = org with open('/path/to/file.tsv', 'w') as f: result = u'\t'.join([ id, Before, After, target]) f.write(result+'\n') And i would like to read the two middle columns into two dictionaries as value and the first column as a key. I have the following sample compilable code however it stores the values as None. start = {} end = {} with open('/path/to/file.tsv', 'rd') as f: for line in f: parts = line.decode('utf-8').split('\t') key = parts[0] print(key) start[key] = parts[1] end[key] = parts[2] print(key , start.get(key), end.get(key)) the printed output is: (u'(first)', None, None) I'm using python 2.7. Thank you in advance.
tagged with: python
tagged with: dictionary
tagged with: text
possible better answer: http://stackoverflow.com/a/52196930

http://stackoverflow.com/q/52184796
upvote count: 1
tagged with: function
answer count: 1
tagged with: variables
has comment: http://stackoverflow.com/comment/91319535
favorite count: 0
has comment: http://stackoverflow.com/comment/91429594
tagged with: python
has answer: http://stackoverflow.com/a/52184964
accepted answer: http://stackoverflow.com/a/52184964
downvote count: 0
has body: I am going to to write a decorator which evaluates the actual names (not their value) of the variables that are passed to the function call. Below, you find a skeleton of the code which makes it a bit clearer what I want to do. import functools def check_func(func): # how to get variable names of function call # s.t. a call like func(arg1, arg2, arg3) # returns a dictionary {'a':'arg1', 'b':'arg2', 'c':'arg3'} ? pass def my_decorator(func): @functools.wraps(func) def call_func(*args, **kwargs): check_func(func) return func(*args, **kwargs) return call_func @my_decorator def my_function(a, b, c): pass arg1='foo' arg2=1 arg3=[1,2,3] my_function(arg1,arg2,arg3)
tagged with: names
type: Question
type: AnsweredQuestion
score: 1
has title: How to get variable names of function call

recursion
type: Tag
tags question: http://stackoverflow.com/q/52248532
tags question: http://stackoverflow.com/q/52172821
tag name: recursion
tags question: http://stackoverflow.com/q/52194723
tags question: http://stackoverflow.com/q/52222756
tags question: http://stackoverflow.com/q/52213762
tags question: http://stackoverflow.com/q/52235443
tags question: http://stackoverflow.com/q/52246079
tags question: http://stackoverflow.com/q/52131390
tags question: http://stackoverflow.com/q/52138518
tags question: http://stackoverflow.com/q/52175803
tags question: http://stackoverflow.com/q/52124536
tags question: http://stackoverflow.com/q/52236214
tags question: http://stackoverflow.com/q/52214698
tags question: http://stackoverflow.com/q/52132876

http://stackoverflow.com/comment/91312785
has text: First you'd need something to tokenize your `text` and the elements of your `list`. Are your using some function/module as tokenizer?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52181407
score: 0

http://stackoverflow.com/comment/91445479
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52247301
score: 0
has text: Nope. That is not the same thing!

http://stackoverflow.com/q/52127269
tagged with: bluetooth
score: 0
tagged with: python
has title: Phone Book Access Profile pabp linux
type: UnansweredQuestion
type: Question
has body: I try to execute the file 'pbapclient.py'. I downloaded the files from https://github.com/bmwcarit/pypbap , but the console prompt show me some errors. I want to print/save all my contact from my android phone(I've got htc one m9).I run antergos. I try for at least 4 month... thanks for the help. This is the prompt [mattia@LinuxMattia pypbap-master]$ python3 pbapclient.py Traceback (most recent call last): File "pbapclient.py", line 22, in &lt;module&gt; from PyOBEX import client File "/usr/lib/python3.7/site- packages/PyOBEX/client.py", line 489, in &lt;module&gt; class SyncClient(Client): File "/usr/lib/python3.7/site- packages/PyOBEX/client.py", line 491, in SyncClient def connect(self, header_list = (headers.Target("IRMC-SYNC"),)): File "/usr/lib/python3.7/site-packages/PyOBEX/headers.py", line 33, in __init__ self.data = self.encode(data) File "/usr/lib/python3.7/site-packages/PyOBEX/headers.py", line 48, in encode return struct.pack("&gt;BH", self.code, len(data) + 3) + data TypeError: can't concat str to bytes Thanks for the help
answer count: 1
has answer: http://stackoverflow.com/a/52127546
tagged with: antergos

http://stackoverflow.com/comment/91315731
comment on: http://stackoverflow.com/q/52182746
score: 0
type: Comment
type: QuestionComment
has text: This line `test = pd.DataFrame(sampledata, index= test.genre)` is incorrect and throwing error

http://stackoverflow.com/comment/91310741
score: 0
comment on: http://stackoverflow.com/a/52180287
type: Comment
type: AnswerComment
has text: I agree with you about the reasons for the problem,but the problem that this approach solves is limited, and I want a general solution.

http://stackoverflow.com/q/52254019
tagged with: firebase-analytics
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/37330412
type: Question
has answer: http://stackoverflow.com/a/52260206
answer count: 2
accepted answer: http://stackoverflow.com/a/52260206
linked to: http://stackoverflow.com/q/37325871
has body: Is there any Python library which can be used to collect and send information (data) to Firebase analytics? I would use this library in an application that I am developing. Edit: Thanks for downvoting without informing me what is the reason for. Edit 2: Of course I have found several APIs. But most of the APIs are for admin purposes. I know that this can be used as well but maybe there is a simplified version used for clients.
upvote count: 6
linked to: http://stackoverflow.com/q/50355752
favorite count: 0
has title: Firebase analytics and Python client API
possible better answer: http://stackoverflow.com/a/52254405
downvote count: 3
has answer: http://stackoverflow.com/a/52254405
tagged with: python
linked to: http://stackoverflow.com/q/50974885
tagged with: firebase

http://stackoverflow.com/comment/91482627
type: QuestionComment
comment on: http://stackoverflow.com/q/52266842
type: Comment
score: 2
has text: Solved it, just made a function that stretches the contour to have a square bounding box, so that coins viewed at an angle appear as they would face-on. This could work for more complicated shapes...

http://stackoverflow.com/comment/91186749
has text: what if one element is 'AAP' the next one is ' - whatever' your code would count wrongly
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52117869
type: Comment

http://stackoverflow.com/comment/91350749
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52200515
has text: can you post the other error as well which you get after `batch_size = 64`
score: 0

http://stackoverflow.com/comment/91193327
comment on: http://stackoverflow.com/q/52119002
has text: I think you should read the error messages and then perform a quick search.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91426746
type: QuestionComment
comment on: http://stackoverflow.com/q/52238963
has text: @DanielRoseman, e.g. contrast to languages featuring pointers.
score: 0
type: Comment

http://stackoverflow.com/q/52217597
possible better answer: http://stackoverflow.com/a/52217676
has answer: http://stackoverflow.com/a/52217676
has answer: http://stackoverflow.com/a/52217663
has answer: http://stackoverflow.com/a/52217661
has comment: http://stackoverflow.com/comment/91383717
downvote count: 4
tagged with: random
accepted answer: http://stackoverflow.com/a/52217661
has answer: http://stackoverflow.com/a/52218911
favorite count: 0
has comment: http://stackoverflow.com/comment/91384544
tagged with: python
answer count: 4
score: -3
has body: I have a string 'ABCDEF', I would like 4 unique characters to be generated randomly every time I run the program. The result should give something like: BDAF EDCB CAFE ... I could use random.sample but it would require a list to be used instead, are there ways of achieving the same result using a string?
upvote count: 1
type: Question
type: AnsweredQuestion
has title: How to generate random values from a string in python?
linked to: http://stackoverflow.com/q/4481724

http://stackoverflow.com/comment/91211505
type: Comment
type: QuestionComment
has text: @StephenRauch I see what you mean. Thanks, you're right.
comment on: http://stackoverflow.com/q/52130403
score: 0

http://stackoverflow.com/comment/91414772
comment on: http://stackoverflow.com/a/52232741
type: Comment
has text: Hmm, how would you do the query though?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91361569
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52187208
type: Comment
has text: I already use `process = subprocess.Popen(bash_command, stdout=subprocess.PIPE, shell=True)` to run the actual script. I took a look at your links but couldn't find anything related to my issue. The `.virtualenvs` folder was created using virtualenv_wrapper.

http://stackoverflow.com/comment/91476992
type: QuestionComment
has text: @MartijnPieters The book is called *Learning Python for Forensics*, so I'm assuming this script is meant to analyze files from dubious sources.
comment on: http://stackoverflow.com/q/52264355
score: 0
type: Comment

http://stackoverflow.com/comment/91323496
comment on: http://stackoverflow.com/a/52183261
type: AnswerComment
score: 0
type: Comment
has text: It doesn't store anything.

http://stackoverflow.com/comment/91489609
comment on: http://stackoverflow.com/a/52270199
has text: Yes I do have xterm installed but looks like something is failing. Please have a look at this screenshot. https://ibb.co/jYvZQU
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91369551
comment on: http://stackoverflow.com/a/52207227
score: 1
has text: I've added the edit. Sounds like a decent workaround, just be careful what you choose as the BUILD_ID. I'd be slightly concerned about choosing an existing BUILD_ID and effecting another build.
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52561153
type: Answer
downvote count: 2
score: -2
has body: I commented "#from .async import process_pool" in firebase.py and started working, it was incompatible with python 3.7
upvote count: 0
has comment: http://stackoverflow.com/comment/108545525
answers question: http://stackoverflow.com/q/52133031
has comment: http://stackoverflow.com/comment/92061124

http://stackoverflow.com/q/52163488
has title: How to set the `app_settings`'s `AuthenticationMethod` to `username_email`?
tagged with: django-allauth
has body: In my project I use the allauth, and in my custom LoginSerializer's validate method: if 'allauth' in settings.INSTALLED_APPS: from allauth.account import app_settings # Authentication through email if app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.EMAIL: user = self._validate_email(email, password) # Authentication through username if app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.USERNAME: user = self._validate_username(username, password) you see there are app_settings.AuthenticationMethod.EMAIL and app_settings.AuthenticationMethod.USERNAME types. I read the source code I found the: There has another type USERNAME_EMAIL : class AppSettings(object): class AuthenticationMethod: USERNAME = 'username' EMAIL = 'email' USERNAME_EMAIL = 'username_email' Where can I set the allauth use the AuthenticationMethod.USERNAME_EMAIL?
type: Question
score: 0
tagged with: django
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/52163918
type: UnansweredQuestion

http://stackoverflow.com/comment/91407165
type: Comment
has text: Done! Now, whenever you get an item page, the script will automatically get the "Add to watch list" button. If you need anything else, you can also send me an email to the address you find in my profile.
comment on: http://stackoverflow.com/a/52228129
type: AnswerComment
score: 0

postgresql
tags question: http://stackoverflow.com/q/52249871
tags question: http://stackoverflow.com/q/52146193
tags question: http://stackoverflow.com/q/52173763
tags question: http://stackoverflow.com/q/52151156
tags question: http://stackoverflow.com/q/52175952
tags question: http://stackoverflow.com/q/52141654
tags question: http://stackoverflow.com/q/52242162
tags question: http://stackoverflow.com/q/52254550
tags question: http://stackoverflow.com/q/52206575
tags question: http://stackoverflow.com/q/52127228
tags question: http://stackoverflow.com/q/52173523
tags question: http://stackoverflow.com/q/52195349
tags question: http://stackoverflow.com/q/52222385
tags question: http://stackoverflow.com/q/52171466
tags question: http://stackoverflow.com/q/52129128
tags question: http://stackoverflow.com/q/52229486
tag name: postgresql
type: Tag
tags question: http://stackoverflow.com/q/52126169
tags question: http://stackoverflow.com/q/52132185
tags question: http://stackoverflow.com/q/52145402
tags question: http://stackoverflow.com/q/52171348
tags question: http://stackoverflow.com/q/52122389
tags question: http://stackoverflow.com/q/52263573
tags question: http://stackoverflow.com/q/52204615
tags question: http://stackoverflow.com/q/52155849
tags question: http://stackoverflow.com/q/52145136
tags question: http://stackoverflow.com/q/52180514
tags question: http://stackoverflow.com/q/52265021
tags question: http://stackoverflow.com/q/52144880

http://stackoverflow.com/q/52163423
has title: How to create a link using BeautifulSoup in Python?
score: 1
possible better answer: http://stackoverflow.com/a/72057616
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/72057616
has comment: http://stackoverflow.com/comment/91278445
has comment: http://stackoverflow.com/comment/91278189
has comment: http://stackoverflow.com/comment/91277778
has answer: http://stackoverflow.com/a/52197996
downvote count: 0
accepted answer: http://stackoverflow.com/a/52197996
favorite count: 0
tagged with: beautifulsoup
has body: I'm trying to build a HTML page that has a table with rows of information (test cases, failed, warning, total # of tests) I want each row in the Test Cases column to be a link to another page. As you see in the image below, my goal is for Test 1 to be a link. Below is the code that I wrote to build what you see in the image. Thanks. import bs4 f = open("practice.html", 'w') html = """ """ soup = bs4.BeautifulSoup(html, "lxml") table = soup.find('table') tr = bs4.Tag(table, name='tr') HTMLColumns = ["Test Cases", "Failed", "Warning", "Total number of tests"] for title in HTMLColumns: # Add titles to each column td = bs4.Tag(tr, name='td') td.insert(0, title) td.attrs['style'] = 'background-color: #D6FCE9; font-weight: bold;' tr.append(td) table.append(tr) results = ["Test 1", str(5), str(3), str(6)] tr = bs4.Tag(table, name='tr') for index, r in enumerate(results): # loop through whole list of issue tuples, and create rows td = bs4.Tag(tr, name='td') td.attrs['style'] = 'background-color: #ffffff; font-weight: bold;' td.string = str(r) tr.append(td) table.append(tr) f.write(soup.prettify()) f.close() Below is code for creating a link that I took from BeautifulSoup documentation: from bs4 import BeautifulSoup soup = BeautifulSoup("", "lxml") original_tag = soup.b new_tag = soup.new_tag("a", href="http://www.example.com") original_tag.append(new_tag) original_tag # new_tag.string = "Link text." original_tag # Link text. f = open("practice.html", 'w') f.write(soup.prettify()) f.close()
has comment: http://stackoverflow.com/comment/91277870
has comment: http://stackoverflow.com/comment/91277605
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91276291
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91277688

http://stackoverflow.com/q/52270145
has answer: http://stackoverflow.com/a/52570022
accepted answer: http://stackoverflow.com/a/52270173
type: AnsweredQuestion
tagged with: format
has body: I have a pd series, s = pd.Series([1, 2, 3, np.nan]) when I do, s.map('this is a string {}'.format) [out] 0 this is a string 1.0 1 this is a string 2.0 2 this is a string 3.0 3 this is a string nan how can I get the same result by using formatted string? s.map(f'this is a string {?}') ?
tagged with: f-string
type: Question
answer count: 2
score: 8
downvote count: 0
favorite count: 0
tagged with: series
upvote count: 8
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/52270173
has title: python f'string not working in pd.Series.map function
possible better answer: http://stackoverflow.com/a/52570022

http://stackoverflow.com/comment/91421499
score: 0
comment on: http://stackoverflow.com/q/52229082
has text: The working directory is set to ".".
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91265124
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52157372
score: 0
has text: Please be **much** more specific about what the problem is and indicate the lines of code involved.

http://stackoverflow.com/q/52158930
has title: Read File and Print It Out in Python
accepted answer: http://stackoverflow.com/a/52159158
type: AnsweredQuestion
type: Question
downvote count: 4
upvote count: 0
has answer: http://stackoverflow.com/a/52159700
has comment: http://stackoverflow.com/comment/91267725
answer count: 4
has answer: http://stackoverflow.com/a/52159306
possible better answer: http://stackoverflow.com/a/52159289
has body: I am new to python. I want to read a file. The contents in the file are: 17 2 3 0 5 16 11 7 9 8 0 6 0 14 17 1 I want to read and print it out like this: aList= [[17,2,3,0], [5,16,11,7], [9,8,0,6], [0,14,17,1]] Here is my code: file = open("file.txt","r") aList=[] for line in file: aList.append(line.strip().split(",")) Now the error is the file not found and cannot print it out.
favorite count: 0
has answer: http://stackoverflow.com/a/52159289
has answer: http://stackoverflow.com/a/52159158
score: -4
tagged with: python

http://stackoverflow.com/q/52163823
answer count: 2
possible better answer: http://stackoverflow.com/a/52164006
score: -1
has answer: http://stackoverflow.com/a/52164006
has answer: http://stackoverflow.com/a/52163928
has comment: http://stackoverflow.com/comment/91277519
tagged with: linux
has title: Find duplicate lines python
favorite count: 0
has comment: http://stackoverflow.com/comment/91277670
has comment: http://stackoverflow.com/comment/91277183
downvote count: 2
accepted answer: http://stackoverflow.com/a/52163928
upvote count: 1
has comment: http://stackoverflow.com/comment/91278892
tagged with: python
has comment: http://stackoverflow.com/comment/91277115
type: AnsweredQuestion
has body: I have a problem to find duplicates and only print those duplicates. I have a text file that I open and trying to find duplicates and print those. What I have as long is: A file which is called data1.txt, the file contains some line: G1/0/1 fc:3f:db:8d:fd:6c G1/0/1 38:63:bb:bb:f8:7d G1/0/2 30:e1:71:7a:27:3b G1/0/3 40:a8:f0:53:6f:31 How could I make a script that only find duplicates on the first world and print the output like this: G1/0/1 fc:3f:db:8d:fd:6c G1/0/1 38:63:bb:bb:f8:7d I don't need to see those other lines which is single.
type: Question
has comment: http://stackoverflow.com/comment/91277237

http://stackoverflow.com/comment/91377867
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52214170
score: 2
has text: Please attempt to do this yourself first and if that fails then ask your question. Otherwise if you are unable to even make a attempt then you are probably better off hiring a developer.

http://stackoverflow.com/comment/91360957
type: AnswerComment
has text: Look at the graph, though, there's a triangle. Area under that curve should be `1/2 * 2 * 4 = 4`, not zero
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52205569

http://stackoverflow.com/q/52179255
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91308788
has comment: http://stackoverflow.com/comment/91308727
has body: Hey guys so i have this text file which i scrape from reddit using reddit praw: Is that intended or a bug? WHAT. Iâ€™m on the way to my pubs. Does first hit desolator remove ti shuffle thread? ðŸ¤”ðŸ¤” My brother works at valve and I confirm this so i was wondering why i got that when i save my string to a txt, the way i save to txt are the following: with open(str(number)+".txt",'w', newline='',encoding="utf-8") as out: out.write(toPrint) out.close() i'm not sure if i'm using wrong unicode, is there anyway so that i can remove these noises ? i'm sure the first one are I'm and the second one are an emoji from reddit, i prefer to just delete the emoji since that way seems to be easier.
has comment: http://stackoverflow.com/comment/91308804
type: Question
tagged with: encoding
tagged with: reddit
has comment: http://stackoverflow.com/comment/91308605
has comment: http://stackoverflow.com/comment/91308755
score: 0
tagged with: python
tagged with: praw
has title: reddit praw scraping removing emoji and whwat encode to use
answer count: 0

http://stackoverflow.com/a/57785739
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52259343
has body: As mentioned in other answers, TensorFlow Lite can help you with network quantization. TensorFlow Lite provides several levels of support for quantization. Tensorflow Lite post-training quantization quantizes weights and activations post training easily. Quantization-aware training allows for training of networks that can be quantized with minimal accuracy drop; this is only available for a subset of convolutional neural network architectures. So first, you need to decide whether you need post-training quantization or quantization-aware training. For example, if you already saved the model as *.h5 files, you would probably want to follow @Mitiku's instruction and do the post-training quantization. If you prefer to achieve higher performance by simulating the effect of quantization in training (using the method you quoted in the question), and your model is in the subset of CNN architecture supported by quantization-aware training, this example may help you in terms of interaction between Keras and TensorFlow. Basically, you only need to add this code between model definition and its fitting: sess = tf.keras.backend.get_session() tf.contrib.quantize.create_training_graph(sess.graph) sess.run(tf.global_variables_initializer())
type: Answer
score: 2
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52259343

python-3.x
tags question: http://stackoverflow.com/q/52128440
tags question: http://stackoverflow.com/q/52199619
tags question: http://stackoverflow.com/q/52140176
tags question: http://stackoverflow.com/q/52175456
tags question: http://stackoverflow.com/q/52238539
tags question: http://stackoverflow.com/q/52146243
tags question: http://stackoverflow.com/q/52133582
tags question: http://stackoverflow.com/q/52262344
tags question: http://stackoverflow.com/q/52247573
tags question: http://stackoverflow.com/q/52215289
tags question: http://stackoverflow.com/q/52128868
tags question: http://stackoverflow.com/q/52158992
tags question: http://stackoverflow.com/q/52128191
tags question: http://stackoverflow.com/q/52125938
tags question: http://stackoverflow.com/q/52210577
tags question: http://stackoverflow.com/q/52261597
tags question: http://stackoverflow.com/q/52260354
tags question: http://stackoverflow.com/q/52165314
tags question: http://stackoverflow.com/q/52190143
tags question: http://stackoverflow.com/q/52133310
tags question: http://stackoverflow.com/q/52174782
tags question: http://stackoverflow.com/q/52243247
tags question: http://stackoverflow.com/q/52261686
tags question: http://stackoverflow.com/q/52260212
tags question: http://stackoverflow.com/q/52122193
tags question: http://stackoverflow.com/q/52164137
tags question: http://stackoverflow.com/q/52188574
tags question: http://stackoverflow.com/q/52247579
tags question: http://stackoverflow.com/q/52145497
tags question: http://stackoverflow.com/q/52178579
tags question: http://stackoverflow.com/q/52248385
tags question: http://stackoverflow.com/q/52200369
tags question: http://stackoverflow.com/q/52144223
tags question: http://stackoverflow.com/q/52173863
tags question: http://stackoverflow.com/q/52194717
tags question: http://stackoverflow.com/q/52156258
tags question: http://stackoverflow.com/q/52114484
tags question: http://stackoverflow.com/q/52190238
tags question: http://stackoverflow.com/q/52216696
tags question: http://stackoverflow.com/q/52235742
tags question: http://stackoverflow.com/q/52193201
tags question: http://stackoverflow.com/q/52225770
tags question: http://stackoverflow.com/q/52127800
tags question: http://stackoverflow.com/q/52201848
tags question: http://stackoverflow.com/q/52249282
tags question: http://stackoverflow.com/q/52186560
tags question: http://stackoverflow.com/q/52219122
tags question: http://stackoverflow.com/q/52118110
tags question: http://stackoverflow.com/q/52144474
tags question: http://stackoverflow.com/q/52158494
tags question: http://stackoverflow.com/q/52187366
tags question: http://stackoverflow.com/q/52149914
tags question: http://stackoverflow.com/q/52117742
tags question: http://stackoverflow.com/q/52181927
tags question: http://stackoverflow.com/q/52201501
tags question: http://stackoverflow.com/q/52160432
tags question: http://stackoverflow.com/q/52257249
tags question: http://stackoverflow.com/q/52242960
tags question: http://stackoverflow.com/q/52176106
tags question: http://stackoverflow.com/q/52141149
tags question: http://stackoverflow.com/q/52268430
tags question: http://stackoverflow.com/q/52246451
tags question: http://stackoverflow.com/q/52176457
tags question: http://stackoverflow.com/q/52156566
tags question: http://stackoverflow.com/q/52231982
tags question: http://stackoverflow.com/q/52238579
tags question: http://stackoverflow.com/q/52190189
tags question: http://stackoverflow.com/q/52257639
tags question: http://stackoverflow.com/q/52124222
tags question: http://stackoverflow.com/q/52179223
tags question: http://stackoverflow.com/q/52266350
tags question: http://stackoverflow.com/q/52228651
tags question: http://stackoverflow.com/q/52114201
tags question: http://stackoverflow.com/q/52226280
tags question: http://stackoverflow.com/q/52232973
tags question: http://stackoverflow.com/q/52220065
tags question: http://stackoverflow.com/q/52251912
tags question: http://stackoverflow.com/q/52118969
tags question: http://stackoverflow.com/q/52158047
tags question: http://stackoverflow.com/q/52223419

http://stackoverflow.com/comment/91367995
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52208802
score: 0
has text: "why it turns N/A?" Because you iterate over . If the first year iterated over doesn't match the test in if-statement, the else-clause fires and returns `N/A`. So this method will only succeed when you try to fetch the first year in the iteration order of `yearly_weather.items()`. For your approach to work you need get rid of the else-clause and move the `return N/A` outside of the loop. But that's the wrong way to do it. See @jpp's answer for the right way.

http://stackoverflow.com/comment/91396031
type: AnswerComment
score: 0
type: Comment
has text: @KoYan That is some weird stuff. Possibly worthy of a separate SO question. ;-D All i can tell you is that your code works on my linux machine with python 3.6.
comment on: http://stackoverflow.com/a/52220950

http://stackoverflow.com/comment/91436675
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52244188
has text: You can't. Dynamic calls, `Any` and static type checking can't mix.

http://stackoverflow.com/comment/91257301
comment on: http://stackoverflow.com/q/52153364
type: Comment
has text: Hello, what have tried so far? Could you show some code and tell where you got stuck?
score: 1
type: QuestionComment

http://stackoverflow.com/q/52259900
has comment: http://stackoverflow.com/comment/91467279
has comment: http://stackoverflow.com/comment/91467689
has answer: http://stackoverflow.com/a/52271706
type: Question
tagged with: combinations
has comment: http://stackoverflow.com/comment/91486696
possible better answer: http://stackoverflow.com/a/52272202
has body: I would like to generate all possible combination with some condition. Given that I have a data frame contain condition I needed. Variable Cluster_no sub_group GDP_M3 1 GDP HPI_M3_lg2 1 HPI FDI_C_lg5 1 FDI FDI_M6 2 FDI Export_M9 2 Export GDP_M9 2 GDP GDP_M12_lg7 3 GDP Export_M12 3 Export I have found itertools.combinations that giving me all possible combination of 3 for example. However, I would like to consider more criteria with cluster_no and sub_group. Having said that if I start with GDP_M3 from cluster 1, it will not be matched with either HPI_M3_lg2 or FDI_C_lg5 because it comes from the same cluster. Given cluster condition, it will look for other clusters, which are cluster 2 or cluster 3. In cluster 2, there are 2 possible variables, which are FDI_M6 or Export_M9 because I would like to consider sub_group condition as well. If selecting FDI_M6, it will move to the next cluster because again it is allowed only 1 variable from each cluster. For now, my list is [GDP_M3, FDI_M6]. The next variable for the combination is Export_M12 because it is from cluster 3 and sub_group Export. I would like to set up to 3 possible combination (1 to 3). Any suggestion on this. Thank you. Edit to add my code. N=3 combination=[] for i in range(1, N+1): for j in itertools.combinations(a, i): combination.append(list(j))
has comment: http://stackoverflow.com/comment/91486686
has answer: http://stackoverflow.com/a/52272202
has comment: http://stackoverflow.com/comment/91468024
answer count: 2
accepted answer: http://stackoverflow.com/a/52271706
downvote count: 0
has title: All possible combination with condition
favorite count: 0
has comment: http://stackoverflow.com/comment/91467482
has comment: http://stackoverflow.com/comment/91487407
upvote count: 2
has comment: http://stackoverflow.com/comment/91487549
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/91273853
type: AnswerComment
has text: Thanks a ton for the code. But after executing the same I am getting a errorMessage File Name Line Position Traceback <module> <module1> 2 FileNotFoundError: [Errno 2] No such file or directory: 'HOXgenewithpromoters.txt'. Where Do I need to place this file , I mean where python is installed in that directory
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52153894

http://stackoverflow.com/a/52207429
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52205005
upvote count: 1
has body: as noted by @Severin, a gamma looks to be a reasonable fit. e.g: import matplotlib.pyplot as plt import numpy as np import scipy.stats as sps x = np.linspace(75) plt.plot(x, sps.gamma.pdf(x, 4) '.-') plt.show() if they really need to sum to 1, rather than integrate, I'd use the cdf and then use np.diff on the result
type: Answer

http://stackoverflow.com/comment/91415963
comment on: http://stackoverflow.com/a/52229957
has text: Thank you very much! This solved the issue. I used w+ because the file I want to open may have to be created first, but I'm gonna deal with that using a try statement now I guess. I did read this description of w+, but must've completely read over the part telling me about the truncation. ` w+'' Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file. `
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91408347
type: QuestionComment
score: 0
has text: I recommend you work through some Python tutorials to become familiar with its syntax and functionality. An internet search should get you started nicely.
comment on: http://stackoverflow.com/q/52225467
type: Comment

http://stackoverflow.com/comment/91480314
type: Comment
comment on: http://stackoverflow.com/a/52237882
score: 0
type: AnswerComment
has text: I am not able to recreate the problem. Please share you code for changing the popup's background.

http://stackoverflow.com/a/52201537
answers question: http://stackoverflow.com/q/52201197
has comment: http://stackoverflow.com/comment/91352230
has comment: http://stackoverflow.com/comment/91354420
has body: You are confusing string representations with string values. When you echo a string object in the Python interpreter, the output is really produced by printing the result of the repr() function. This function outputs debugging friendly representations, and for strings, that representation is valid Python syntax you can copy and paste back into Python. print on the other hand, just writes the actual value in the string to the terminal. That's rather different from the Python syntax that creates the value. A backslash in the string prints as a backslash, you wouldn't see a backslash if there wasn't one in the value. In Python string literal syntax, the \ backslash character has special meaning, it's the first character of an escape sequence. So if you want to have an actual backslash in the value of the string, you would need to use \\ to 'escape the escape'. There is other syntax where the backslash would not have special meaning, but the repr() representation of a string doesn't use that other syntax. So it'll output any backslash in the value as the escape sequence \\. That doesn't mean that the value has two backslashes. It just means that you can copy the output, and paste it into Python, and it'll produce the same string value. You can see that your string value doesn't have double backslashes by looking at individual characters: &gt;&gt;&gt; value2 = '"\\x01\\x02\\x03\\x04\\x05"' &gt;&gt;&gt; value2 '"\\x01\\x02\\x03\\x04\\x05"' &gt;&gt;&gt; print value2 "\x01\x02\x03\x04\x05" &gt;&gt;&gt; print value2[0] " &gt;&gt;&gt; print value2[1] \ &gt;&gt;&gt; print value2[2] x &gt;&gt;&gt; value2[0] '"' &gt;&gt;&gt; value2[1] '\\' &gt;&gt;&gt; value2[2] 'x' Printing value2[1] shows that that single character is a backslash. Echoing that single character shows '\\', the Python syntax to recreate a string with a single character. When you echo dictionaries or lists or other standard Python containers, they too are echoed using valid Python syntax, so their contents all ar…
has comment: http://stackoverflow.com/comment/91353745
upvote count: 2
has comment: http://stackoverflow.com/comment/91352259
has comment: http://stackoverflow.com/comment/91352347
has comment: http://stackoverflow.com/comment/91354444
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91352554
has comment: http://stackoverflow.com/comment/91354371

http://stackoverflow.com/a/52132726
has body: Try the following: list_df = [] for i, row in enumerate(df.values): df_values = df.loc[i,"orderitems"] for i, row in enumerate(df_values): list_df.append(pd.DataFrame([row])) df_values_final=pd.concat(list_df)
accepted answer of: http://stackoverflow.com/q/52132207
answers question: http://stackoverflow.com/q/52132207
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/52174512
tagged with: regex
favorite count: 0
answer count: 0
type: UnansweredQuestion
downvote count: 1
duplicate of: http://stackoverflow.com/q/50444346
score: 2
has comment: http://stackoverflow.com/comment/91300253
upvote count: 3
tagged with: dataframe
type: Question
has body: I have a large DataFrame in Pandas. Its col column contains text (sequence of words). For each value in this column, I would like all the words to be stripped of all non-alphanumeric characters. Here are some examples of things I want dropped: , . ' " { } [ ] ( ) ! @ # $ % &amp; * - + all numbers/digits symbols like trademark, registered trademark, copyright, etc all non-English characters And most importantly, I want the results to be put back where they were. For example, if one field in col has value I'll be there @ 5, no $hit!, the output should be Ill be there no hit and it should be set as the new value for that row/column (Making a copy of the DataFrame is okay). If dropping unwanted characters leads to an empty string, the value should be an empty string. What is the most efficient way of doing this in Pandas? (The dataframe has about 5 million rows, and each row has an average length of 50 for the col field.)
has title: Removing all non-alphanumeric chars from a Pandas DataFrame
tagged with: pandas
linked to: http://stackoverflow.com/q/50444346
tagged with: python

http://stackoverflow.com/a/52254540
score: 8
accepted answer of: http://stackoverflow.com/q/52236655
downvote count: 0
answers question: http://stackoverflow.com/q/52236655
has comment: http://stackoverflow.com/comment/126605369
upvote count: 8
has comment: http://stackoverflow.com/comment/92167768
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/126907381
has body: {{geocodeArea: xxx }} is a special feature of overpass turbo and not part of Overpass API. overpy uses Overpass API directly which means you can't use this keyword. However {{geocodeArea: xxx }} just tells overpass turbo to perform a geocoding request, i.e. transform an address into a geographic location. You can do the same, e.g. by making a call to Nominatim, Photon or any other geocoder.
type: Answer

http://stackoverflow.com/q/52126579
score: 2
has title: Incorporating dim parameter of torch.topk in tf.nn.top_k
has body: Pytorch provide torch.topk(input, k, dim=None, largest=True, sorted=True) function to calculate k largest elements of the given input tensor along a given dimension dim. I have a tensor of shape (16, 512, 4096) and I am using torch.topk in the following manner- # inputs.shape (16L, 512L, 4096L) dist, idx = torch.topk(inputs, 64, dim=2, largest=False, sorted=False) # dist.shape (16L, 512L, 64L), idx.shape (16L, 512L, 64L) I found similar tensorflow implementaion as following - tf.nn.top_k(input, k=1, sorted=True, name=None). My question is how to Incorporate dim=2 parameter in tf.nn.top_k so as to achieve the tensor of the same shape as calculated by pytorch?
downvote count: 0
tagged with: tensorflow
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/52126997
answer count: 1
favorite count: 0
tagged with: pytorch
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/52165862
upvote count: 7
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52165705
has body: The library doesn't use the warnings module. Instead, it logs a message using the logging framework, by calling the top-level logging.warning() function. See the imageio.core.util._precision_warn() function: from logging import warning as warn # ... def _precision_warn(p1, p2, extra=""): t = ( "Lossy conversion from {} to {}. {} Convert image to {} prior to " "saving to suppress this warning." ) warn(t.format(p1, p2, extra, p2)) This is... unfortunate, as you can't easily disable this using the logging API. Best practice is to use a dedicated named logger for libraries. As such, it is probably best to patch the library no make the above function a no-op: import imageio.core.util def silence_imageio_warning(*args, **kwargs): pass imageio.core.util._precision_warn = silence_imageio_warning You could also silence all logging, adjusting configurion on the root logger. This is not ideal, as you may want to use logging yourself or use third-party libraries that are better behaved. I've filed an issue with the project to ask them to fix their logging story.
accepted answer of: http://stackoverflow.com/q/52165705
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/91281535

http://stackoverflow.com/q/52231714
accepted answer: http://stackoverflow.com/a/52237342
score: 0
has comment: http://stackoverflow.com/comment/91413028
has comment: http://stackoverflow.com/comment/91412910
answer count: 1
has comment: http://stackoverflow.com/comment/91413057
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/91413046
tagged with: python
has title: How can I get link in href with specified class by using python
has comment: http://stackoverflow.com/comment/91421944
has comment: http://stackoverflow.com/comment/91412915
tagged with: jupyter-notebook
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91413143
has comment: http://stackoverflow.com/comment/91412974
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/91419257
has body: Here are the html details: Google Map I would like to get only latitude and longitude which are 18 and 1813z how could I do that? I'm using two url pages for getting text in the secondpage. The other info like Title or Name work as it appears as text so I can use get_text(). But this case, I could not get the link after href. So I Please help. The code I tried: from bs4 import BeautifulSoup import urllib.request def get_page(url): request = urllib.request.Request(url) response = urllib.request.urlopen(request) mainpage = response.read().decode('utf-8') return mainpage mainpage = get_page('https://www.something.com') mainpage_parser = BeautifulSoup(mainpage,'html.parser') secondpage = get_page('https://www.something2.com/') secondpage_parser = BeautifulSoup(secondpage,'html.parser') try: for gps in secondpage_parser.find_all('a',{"data-track-id":"Google Map"}, href=True): gpslocation = gps['href'] print(gpslocation) except: print(gpslocation)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91412957
type: Question
has answer: http://stackoverflow.com/a/52237342

http://stackoverflow.com/q/52256560
has answer: http://stackoverflow.com/a/70401596
type: AnsweredQuestion
has title: Fuzzy Match columns of Different Dataframe
linked to: http://stackoverflow.com/q/31806695
has body: Background I have 2 data frames which has no common key to which I can merge them. Both df have a column that contains "entity name". One df contains 8000+ entities and the other close to 2000 entities. Sample Data: vendor_df= Name of Vendor City State ZIP FREDDIE LEES AMERICAN GOURMET SAUCE St. Louis MO 63101 CITYARCHRIVER 2015 FOUNDATION St. Louis MO 63102 GLAXOSMITHKLINE CONSUMER HEALTHCARE St. Louis MO 63102 LACKEY SHEET METAL St. Louis MO 63102 regulator_df = Name of Entity Committies LACKEY SHEET METAL Private PRIMUS STERILIZER COMPANY LLC Private HELGET GAS PRODUCTS INC Autonomous ORTHOQUEST LLC Governmant Problem Stmt: I have to fuzzy match the entities of these two(Name of vendor &amp; Name of Entity) columns and get a score. So, need to know if 1st value of dataframe 1(vendor_df) is matching with any of the 2000 entities of dataframe2(regulator_df). StackOverflow Links I checked: fuzzy match between 2 columns (Python) create new column in dataframe using fuzzywuzzy Apply fuzzy matching across a dataframe column and save results in a new column Code import pandas as pd from fuzzywuzzy import fuzz from fuzzywuzzy import process vendor_df = pd.read_excel('C:\\Users\\40101584\\Desktop\\AUS CUB AML\\Vendors_Sheet.xlsx', sheet_name=0) regulator_df = pd.read_excel('C:\\Users\\40101584\\Desktop\\AUS CUB AML\\Regulated_Vendors_Sheet.xlsx', sheet_name=0) compare = pd.MultiIndex.from_product([vendor_df['Name of vendor'], regulator_df['Name of Entity']]).to_series() def metrics(tup): return pd.Series([fuzz.ratio(*tup), fuzz.token_sort_ratio(*tup)], ['ratio', 'token']) #compare.apply(metrics) -- Either this works or the below line result = compare.apply(metrics).unstack().idxmax().unstack(0) Problems with Above Code: The code works if the two dataframes are small but it is taking forever when I give the complete dataset. Above code is taken from 3rd link. Any solution if the same thing can work fast or can work with large dataset? UPDATE 1 Can the above code be made fa…
type: Question
linked to: http://stackoverflow.com/q/40143675
tagged with: fuzzy-logic
score: 5
has comment: http://stackoverflow.com/comment/101801731
upvote count: 5
accepted answer: http://stackoverflow.com/a/52271721
linked to: http://stackoverflow.com/q/66856883
tagged with: fuzzywuzzy
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/91460403
tagged with: fuzzy-comparison
has comment: http://stackoverflow.com/comment/91460379
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/36138886
linked to: http://stackoverflow.com/q/38577332
has answer: http://stackoverflow.com/a/60283520
possible better answer: http://stackoverflow.com/a/70401596
tagged with: python
has answer: http://stackoverflow.com/a/52271721

http://stackoverflow.com/comment/91711963
comment on: http://stackoverflow.com/q/52206251
score: 0
type: Comment
type: QuestionComment
has text: Yeah, it's okay. Thanks

http://stackoverflow.com/comment/139335869
score: 0
type: AnswerComment
has text: blake2b is a hashing function. Hashing function are irreversible. Password managers must be able to retrieve the original value, so hashing is not the solution to OPs question. For a password manager it would make sense to use symmetric encryption, which IS reversible, given a secret key (master password as OP puts it). Hashing is used for password, or authenticity verification - not retrieval.
type: Comment
comment on: http://stackoverflow.com/a/52158173

http://stackoverflow.com/q/52159037
accepted answer: http://stackoverflow.com/a/52159234
type: Question
tagged with: group-by
has title: How to find delta for same number and name in pandas?
tagged with: pandas-groupby
tagged with: pandas
score: 2
has answer: http://stackoverflow.com/a/52159234
answer count: 1
downvote count: 0
has body: I have the below dataframe and I need to subtract and find the delta between next quater and current quater plus next to next quater and current quater. Input data: Number Name Year Quater value 1 an 2018 1 2.5 2 bn 2018 1 1.5 1 an 2018 2 3.5 2 bn 2018 2 4.5 1 an 2018 3 4.5 1 an 2018 4 2.5 2 bn 2018 4 1.5 1 an 2019 1 5.5 2 bn 2019 1 1.5 Output: d_1 is the difference between next quater and current quater for same number and name, whereas d_2 is the diff between next to next quater and current quater for same number and name. Number Name Year Quater value d_1 d_2 1 an 2018 1 2.5 1 2 2 bn 2018 1 1.5 3 1 an 2018 2 3.5 1 -1 2 bn 2018 2 4.5 -3 1 an 2018 3 4.5 -2 1 1 an 2018 4 2.5 3 2 bn 2018 4 1.5 0 1 an 2019 1 5.5 2 bn 2019 1 1.5
favorite count: 0
upvote count: 2
tagged with: lead
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/52208401
tagged with: function
has comment: http://stackoverflow.com/comment/91366260
has body: Im doing an exercise, where im defining a function that takes two inputs - a sentence and a word, that will be replaced by stars in the sentence input. Problem is, I cant get the final output to put spaces in between words, ie it prints all the words crammed together. Any help please ? def censor(text, word): lis = text.split() output ="" p = [] for w in lis: if w != word: p.append(w) else: l = len(w) y = "*" * l p.append(y) output = output.join(p) print output censor("Hello world televison", "world")
possible better answer: http://stackoverflow.com/a/52209157
favorite count: 0
has answer: http://stackoverflow.com/a/52209157
has answer: http://stackoverflow.com/a/52208544
tagged with: python
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91366200
accepted answer: http://stackoverflow.com/a/52208544
type: AnsweredQuestion
has title: Function, that turns a word in a string to stars
type: Question
has comment: http://stackoverflow.com/comment/91366156
answer count: 2
has comment: http://stackoverflow.com/comment/91366325

http://stackoverflow.com/comment/91301989
type: AnswerComment
type: Comment
has text: These are not coordinates. they are pixel values.
score: 0
comment on: http://stackoverflow.com/a/52175584

http://stackoverflow.com/comment/91381300
has text: Possible duplicate of [How to deal with SettingWithCopyWarning in Pandas?](https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas)
comment on: http://stackoverflow.com/q/52216260
score: 0
type: Comment
type: QuestionComment

web-crawler
tags question: http://stackoverflow.com/q/52191148
tags question: http://stackoverflow.com/q/52216446
tags question: http://stackoverflow.com/q/52208305
tags question: http://stackoverflow.com/q/52240620
tag name: web-crawler
tags question: http://stackoverflow.com/q/52213455
type: Tag
tags question: http://stackoverflow.com/q/52157632
tags question: http://stackoverflow.com/q/52135929
tags question: http://stackoverflow.com/q/52124737
tags question: http://stackoverflow.com/q/52128922
tags question: http://stackoverflow.com/q/52128097

http://stackoverflow.com/q/52184147
favorite count: 0
has comment: http://stackoverflow.com/comment/91339319
tagged with: python
type: AnsweredQuestion
downvote count: 0
has body: I am installing a rather long list of packages with conda with the following command: conda install -c conda-forge \ 'nomkl' \ 'ipywidgets=7.4.0' \ 'pandas=0.23.4' \ 'numexpr=2.6.5' \ 'matplotlib=2.2.2' \ 'scipy=1.1.0' \ 'seaborn=0.9.0' \ 'scikit-learn=0.19.1' \ 'scikit-image=0.14.0' \ 'sympy=1.2' \ 'cython=0.28.5' \ 'patsy=0.5.0' \ 'statsmodels=0.8.0' \ 'dill=0.2.8.2' \ 'numba=0.38.1' \ 'bokeh=0.13.0' \ 'sqlalchemy=1.2.10' \ 'hdf5' \ 'libnetcdf' \ 'netcdf4' \ 'h5py=2.8.0' \ 'vincent=0.4.4' \ 'beautifulsoup4=4.6.1' \ 'protobuf=3.6.0' \ 'tensorflow=1.10' \ 'opencv' \ 'keras=2.1' \ 'dask=0.19.0' \ 'dask-glm=0.1.0' \ 'dask-ml=0.9.0' \ 'dask-xgboost=0.1.5' \ 'dask-kubernetes=0.5.0' \ 'msgpack-python' \ 'distributed=1.23' \ 'cloudpickle=0.5.3' \ 'python-blosc' \ 'numpy=1.14.2' \ 'xarray=0.10.8' \ 'gcsfs=0.1.2' \ 'pymc3=3.5' \ 'hdbscan=0.8.15' \ 'pystan=2.17.1.0' \ 'yaafe=0.70' \ 'aubio=0.4.6' \ 'librosa=0.6.2' \ 'nltk=3.2.5' \ 'spacy=2.0.11' \ 'gensim=3.5.0' \ 'textblob=0.15.1' \ 'xlrd=1.1.0' &amp;&amp; \ conda clean -tipsy As a side effect, following downgrade happens: python: 3.6.5-1 conda-forge --&gt; 3.5.5-1 Which actually breaks my environment, as I rely on Python 3.6. What's the best way to check which package causes the downgrade? Maybe there's a way to fix Python version and make conda throw an error on a package that does not meet the constraint?
type: Question
has answer: http://stackoverflow.com/a/52208569
accepted answer: http://stackoverflow.com/a/52208569
tagged with: anaconda
score: 1
has comment: http://stackoverflow.com/comment/91319989
tagged with: conda
has comment: http://stackoverflow.com/comment/91337151
upvote count: 1
has title: Which package makes conda downgrade a package?
answer count: 1

http://stackoverflow.com/a/55110782
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52121730
accepted answer of: http://stackoverflow.com/q/52121730
has body: In the end, I created this little Python script to get chat data of a given Twitch Clip. Apparently, you can fetch chat data of a given video with the API call : https://api.twitch.tv/v5/videos/$VODID/comments?cursor=$NEXT where vodid is the id of the clip's video and the cursor works like this: you can fetch chat data by in chunks and every chunk has a cursor value which indicates the next chunk. So, you can keep getting next chunk UNTIL you find the offset where the clip's offset matches, and writing/keeping the chat data until it supresses clip's duration. If anyone needs it: https://github.com/OgulcanCelik/twitch-clip-chat
upvote count: 1
type: AcceptedAnswer
score: 0

http://stackoverflow.com/a/52248714
has comment: http://stackoverflow.com/comment/91445870
score: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91445695
has body: Using mask and ffill: df.assign(TAIR=df.TAIR.mask(df.TAIR.le(-999)).ffill()) TIMESTAMP TAIR 0 2011-06-01 00:00:00 24.3 1 2011-06-01 00:05:00 24.5 2 2011-06-01 00:10:00 24.2 3 2011-06-01 00:15:00 24.1 4 2011-06-01 00:20:00 24.2 5 2011-06-01 00:25:00 24.2 6 2011-06-01 00:30:00 15.1 7 2011-06-01 00:35:00 15.1 8 2011-06-01 00:40:00 13.9 9 2011-06-01 00:45:00 13.7
has comment: http://stackoverflow.com/comment/91445730
has comment: http://stackoverflow.com/comment/91445859
accepted answer of: http://stackoverflow.com/q/52248704
type: Answer
answers question: http://stackoverflow.com/q/52248704
has comment: http://stackoverflow.com/comment/91445773
upvote count: 4
has comment: http://stackoverflow.com/comment/91445938
has comment: http://stackoverflow.com/comment/91445916

http://stackoverflow.com/q/52123106
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/52123292
type: UnansweredQuestion
tagged with: dataframe
has answer: http://stackoverflow.com/a/52123258
tagged with: pandas
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52123277
favorite count: 0
type: Question
has title: Add subsection suffix values to pandas column values
has body: Let's say that I have a dataframe with multiple columns. One column establish an identification number (ID) for some guys and other column establish some feature of them, let's say the degree of misdeeds that have committed. An example of that: `df Out[63]: Crime ID 0 13 1 1 13 1 2 12 1 3 12 1 4 13 3 5 13 3 6 13 3 7 63 3 8 63 3 9 63 3 10 63 3 11 3 3 12 7 6 13 7 6 14 13 6 15 13 6 16 45 6` Is possible to categorize the IDs by the diversity of crimes? A possible output would be: `df1 Out[64]: Crime ID 0 13 1 1 13 1 2 12 1.1 3 12 1.1 4 13 3 5 13 3 6 13 3 7 63 3.1 8 63 3.1 9 63 3.1 10 63 3.1 11 3 3.2 12 7 6 13 7 6 14 13 6.1 15 13 6.1 16 45 6.2` Thanks in advance
tagged with: python

http://stackoverflow.com/q/52152482
answer count: 5
has comment: http://stackoverflow.com/comment/91255494
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91255833
downvote count: 2
has comment: http://stackoverflow.com/comment/91255399
has body: a = int(input()) l1 = [] for i in range(a): l1[i] = 5 print(l1) I keep getting the error: list assignment index out of range i will always be smaller than a so why am I getting this error? I don't wish to use append().
tagged with: python
has comment: http://stackoverflow.com/comment/91255650
has comment: http://stackoverflow.com/comment/91255983
has comment: http://stackoverflow.com/comment/91256248
has comment: http://stackoverflow.com/comment/91256115
has comment: http://stackoverflow.com/comment/91255368
type: Question
has answer: http://stackoverflow.com/a/52152513
has comment: http://stackoverflow.com/comment/91255464
has answer: http://stackoverflow.com/a/52152607
has comment: http://stackoverflow.com/comment/91255396
has comment: http://stackoverflow.com/comment/91255468
has answer: http://stackoverflow.com/a/52152718
has answer: http://stackoverflow.com/a/76900369
has comment: http://stackoverflow.com/comment/91255302
score: 0
has comment: http://stackoverflow.com/comment/91255496
has answer: http://stackoverflow.com/a/52152511
has comment: http://stackoverflow.com/comment/91255335
has comment: http://stackoverflow.com/comment/91256279
has title: Populating a list in python using for loop
has comment: http://stackoverflow.com/comment/91255753
favorite count: 0
has comment: http://stackoverflow.com/comment/91255407
upvote count: 2

http://stackoverflow.com/comment/91296547
type: Comment
has text: @d_kennetz, you are right. I already edited the answer. Thanks.
comment on: http://stackoverflow.com/a/52172780
type: AnswerComment
score: 0

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

http://stackoverflow.com/comment/91405463
type: QuestionComment
type: Comment
score: 3
comment on: http://stackoverflow.com/q/52228001
has text: Would it make sense for your code to instead pause for 1 second ten times? Or check the time periodically to see if 10 seconds has elapsed? There are many strategies for problems like this, and choosing the correct one will require more details about what exactly you're trying to do.

http://stackoverflow.com/q/52195539
tagged with: matrix
favorite count: 0
has answer: http://stackoverflow.com/a/52195676
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52196526
upvote count: 1
tagged with: python
downvote count: 1
has body: I want to create a matrix with n columns of k 1s in each row rolling from left to right. (n-k elements in each row are 0) example: k = 4, n = 10 result: 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 how can I create this matrix fast and smart?
has comment: http://stackoverflow.com/comment/91340734
has title: Python create a matrix of rolling 1s along the diagonal
type: Question
answer count: 2
score: 0

http://stackoverflow.com/comment/91232034
comment on: http://stackoverflow.com/q/52141100
has text: Please, just look: https://www.google.com/search?q=xlswriter+python+write+multiple+sheets
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52180315
answer count: 3
tagged with: http://stackoverflow.com/tag/pdf
has answer: http://stackoverflow.com/a/52181302
favorite count: 0
has answer: http://stackoverflow.com/a/52183983
has body: I am currently working on a project where I want to extract text from a PDF and then check if one of the words in the extracted text appears in a certain dictionary. If so, I want to us example.replace(file, x, y) to replace the word from my text with the value from my dictionary. I'm struggling with the loop for checking all words in my text and compare them to the dictionary automatically. The goal is that I don't have to type "old" and "new" on my own but the programme checks all words in the text and if it finds one in the dictionary "old" shall be the word from the text and "new" the value of the key. The manual version works. Here is my code from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage from io import StringIO def convert_pdf_to_txt(path): rsrcmgr = PDFResourceManager() retstr = StringIO() codec = 'utf-8' laparams = LAParams() device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams) fp = open(path, 'rb') interpreter = PDFPageInterpreter(rsrcmgr, device) password = "" maxpages = 0 caching = True pagenos=set() for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True): interpreter.process_page(page) text = retstr.getvalue() fp.close() device.close() retstr.close() return text dictionary = {"Die" : "Der", "Arbeitsfläche":"Platz"} def convert(file, old, new): translation = convert_pdf_to_txt(file).replace(old, new) return translation print(convert('mytest.pdf','Die' ,'Der')) Thanks for help!
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/52180572
tagged with: python
possible better answer: http://stackoverflow.com/a/52181302
tagged with: text
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52183983
downvote count: 1
linked to: http://stackoverflow.com/q/17730788
type: Question
tagged with: python-2.7
has title: Extracting text from PDF and compare to dictionary

http://stackoverflow.com/a/52115045
has body: Actually, there isn't much to optimize in the above code, I am afraid. To make argmin faster I would suggest you to get (or otherwise compile yourself) NumPy with multi-threaded support (or you could re-implement some multi-threaded argmin yourself). As far as Cython goes, you get the real deal when you start using C types, but this is something I would not see a large improvement with the code you posted. That's mostly glue-code, no number-crunching involved there. I would expect number-crunching to happen in the function fun, and this is probably the only place where actual manual optimization may make a difference, as long as it is not so easy to vectorize (read: there is a for or other manual looping). Then, I would start off with numba, which is a much simpler drop-in speed-up for your code, if it works. If it doesn't, it is probably appropriate to start looking into Cython.
type: Answer
accepted answer of: http://stackoverflow.com/q/52114107
downvote count: 0
answers question: http://stackoverflow.com/q/52114107
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/91490320
has text: Ok, .iloc[] is more correct because the column notation is: 1, 2, 3. If the column notation will be: 'A', 'B', 'C'. the answer will use .loc[]. That's right?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52270389
type: AnswerComment

http://stackoverflow.com/comment/91243155
has text: I think it's formatted fine once it's explained what bold means.
score: 1
comment on: http://stackoverflow.com/q/52146661
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91310574
type: Comment
comment on: http://stackoverflow.com/q/52179044
type: QuestionComment
has text: i thought django standard django template language is the same as jinja. I must have mixed that up. so it's django standard
score: 0

http://stackoverflow.com/a/52227422
upvote count: 1
has comment: http://stackoverflow.com/comment/91404285
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/91404312
type: Answer
has comment: http://stackoverflow.com/comment/91404379
answers question: http://stackoverflow.com/q/52227344
accepted answer of: http://stackoverflow.com/q/52227344
has body: The first one means that the object isn't re-evaluated every time, however numbers always refer to a new object so this doesn't have any effect. However, take this: l = [[0] * 3] * 3 This will make a list full of 3 lists containing 3 zeros. Now try changing one element: l[0][0] = 1 &gt;&gt;&gt; l[0] [1, 0, 0] &gt;&gt;&gt; l[1] [1, 0, 0] You see that it affected the other list too. This is because the list being multiplied referred to the same object. But your example with a proper for loop re-evaluates each object and could save debugging problems You could also do the following why does re-evaluate the object. l = [0 for _ in range(3)]
score: 0

http://stackoverflow.com/comment/91353400
type: Comment
has text: I liked the suggestion. I will try it and if it worked for me I will accept your answer for sure, amigo.
type: AnswerComment
comment on: http://stackoverflow.com/a/52201937
score: 0

http://stackoverflow.com/comment/91423269
type: QuestionComment
has text: I have not used this before but `faker` seems to be a highly used and well received python library. Take a look: https://github.com/joke2k/faker
comment on: http://stackoverflow.com/q/52236463
score: 0
type: Comment

http://stackoverflow.com/comment/91290129
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52169024
has text: not needed :) i've answered the last question but haven't solve the issue...

http://stackoverflow.com/comment/91183112
score: 0
type: Comment
type: QuestionComment
has text: i do use index.html as flask template but its not its place to there. Can you show me how to evaluate it outside of the string? you are right its dumb to except it to be evaluated(that what i meant by interpolate) within a string.
comment on: http://stackoverflow.com/q/52114198

http://stackoverflow.com/q/52145678
score: 1
type: Question
has title: How to load a date column from a CSV straight as datetime[ns] type into a Pandas DataFrame?
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
upvote count: 1
tagged with: datetime
duplicate of: http://stackoverflow.com/q/21269399
favorite count: 0
has comment: http://stackoverflow.com/comment/91245990
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/21269399
has body: I have a huge CSV file with date columns like this: a,b,c 10-15,2008-10-20,2008-10-21 1996-06-20,1996-06-21,1996-07-25 1998-06-22,1998-06-23,1998-06-23 . . . I want to read thsi file into a Pandas DataFrame while storing the dates straight as datetime64[ns] type. So I tried pd.read_csv(fname, dtype={ 'a': np.datetime64, 'b': np.datetime64, 'c': np.datetime64 }) but the Pandas parser complains. I want to avoid using the parse_dates option or post-processing the DataFrame with astype, because the CSV has 50 million rows and each time I load the CSV the conversion takes a long time. Is there a way to read the dates straight into datetime64[ns] types? Update: As it turns out, reading the CSV with the parse_dates option (as suggested in the answers of the proposed duplicate) is performance-wise *not too bad**: On my machine reading the 50 million records takes without conversion to date objects 2:30 min with conversion to date objects 5:50 min

http://stackoverflow.com/q/52144073
has comment: http://stackoverflow.com/comment/91274573
linked to: http://stackoverflow.com/q/52112560
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91273101
tagged with: image-processing
has comment: http://stackoverflow.com/comment/91283735
has title: Processing Xray Images (.dcm files) using pydicom (could not find SliceThickness Attribute)
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/91304861
accepted answer: http://stackoverflow.com/a/52187544
answer count: 2
tagged with: dicom
has answer: http://stackoverflow.com/a/52197539
has comment: http://stackoverflow.com/comment/91269049
tagged with: pydicom
favorite count: 0
has comment: http://stackoverflow.com/comment/91240004
has answer: http://stackoverflow.com/a/52187544
score: 0
downvote count: 2
possible better answer: http://stackoverflow.com/a/52197539
has body: I am new to Image Processing and want to know how can I pre-process dicom images using python. I am following the below tutorial:dicom in python I do not have the SliceThickness attribute in my data. How can I calculate it? This is a sample dataset which I have: Here is my code: import pydicom import os import numpy from matplotlib import pyplot, cm PathDicom = "xyz\images" lstFilesDCM = [] # creating an empty list for dirName, subdirList, fileList in os.walk(PathDicom): for filename in fileList: if ".dcm" in filename.lower(): # checking whether the file's DICOM lstFilesDCM.append(os.path.join(dirName,filename)) RefDs = pydicom.read_file(lstFilesDCM[0]) ConstPixelDims = (int(RefDs.Rows), int(RefDs.Columns), len(lstFilesDCM)) #Load dimensions based on the number of rows, columns, and slices (along the Z axis) ConstPixelSpacing = (float(RefDs.PixelSpacing[0]), float(RefDs.PixelSpacing[1]), float(RefDs.SliceThickness)) # Load spacing values (in mm) This is the error I got: 'FileDataset' object has no attribute 'SliceThickness'

http://stackoverflow.com/a/52249230
has body: When the outcome of a single random trial is a "success" with probability p, we call that a Bernoulli trial with parameter p, a.k.a. a Bernoulli(p). The binomial distribution evaluates the probability of getting a particular number of "successes" if we run n independent Bernoulli trials with the same p. We call that a binomial distribution with parameters n and p, a.k.a. a binomial(n, p). By convention, Bernoulli successes are encoded as a 1, and failures as a 0. Consequently, a Bernoulli(p) and a binomial(1, p) are the same thing. If we're generating values from a binomial(n, p) the outcome is a count of how many successes were observed in a realization of n trials. The number of successes is thus the sum of n Bernoulli results. Now to NumPy. Invoking np.random.binomial(1000, .10, 1) generates one realization of a binomial with n = 1000 and p = 0.1. Using np.random.binomial(1, .10, 1000) generates 1000 realizations of a binomial with n = 1 and p = 0.1, i.e., 1000 Bernoulli(0.1)'s. These are not the same thing, but if you sum the Bernoulli values using sum(np.random.binomial(1, .10, 1000)) the result will have the same distribution as np.random.binomial(1000, .10, 1). Is one of them better than the other? While they are interchangeable from a distributional perspective, there are more efficient computational methods to generate binomials than just generating n Bernoullis and summing them. Assuming the implementers of NumPy are competent, you're probably better off using np.random.binomial(1000, .10, 1).
score: 0
answers question: http://stackoverflow.com/q/52240956
type: Answer

http://stackoverflow.com/a/52315841
accepted answer of: http://stackoverflow.com/q/52271154
has comment: http://stackoverflow.com/comment/91798367
answers question: http://stackoverflow.com/q/52271154
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91912639
type: Answer
has body: Ok, this looks like it's a gap in the ValueAxis code that we missed when adding DateAxis a while back. Try this. Add this function to your code somewhere convenient: from ..enum.chart import XL_AXIS_CROSSES def set_date_crosses(value_axis, value): """*value* is a member of XL_AXIS_CROSSES.""" xAx = value_axis._elemement def _cross_xAx(self): """Axis element in same group (pri/sec) that crosses this axis.""" crossAx_id = xAx.crossAx.val expr = ( '(../c:catAx | ../c:valAx | ../c:dateAx)/c:axId[@val="%d"]' % crossAx_id ) cross_axId = xAx.xpath(expr)[0] return cross_axId.getparent() cross_xAx = _cross_xAx() if value == XL_AXIS_CROSSES.CUSTOM: if cross_xAx.crossesAt is not None: return cross_xAx._remove_crosses() cross_xAx._remove_crossesAt() if value == XL_AXIS_CROSSES.CUSTOM: cross_xAx._add_crossesAt(val=0.0) return cross_xAx._add_crosses(val=value) And then change chart.value_axis.crosses = XL_AXIS_CROSSES.MINIMUM to this: set_date_crosses(chart.value_axis, XL_AXIS_CROSSES.MINIMUM) And see if that does the trick. If that works, let me know and I'll open a case to incorporate the change into the next version.
downvote count: 0
score: 1

http://stackoverflow.com/comment/91184070
comment on: http://stackoverflow.com/q/52115503
score: 0
has text: I imported roc_curve from sklearn and replaced ['accuracy'] with it. I received the following error: Invalid metric: roc_curve. Actually I want to print out each folds prediction and the corresponding actual output for each fold. Furthermore I want to plot the overall ROC-Curve if that is possible. But most importantly for me it is to use roc as the metric and not the overall accuracy, since this generates a bad model in my case. I hope you can help. If you need more information, please ask! Thanks!
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52235017
type: AnsweredQuestion
upvote count: 0
has title: Parse a string between special characters and build a list
has answer: http://stackoverflow.com/a/52235181
accepted answer: http://stackoverflow.com/a/52235181
type: Question
score: -1
has body: I was trying to make a script that will give the devices that are connected to my network. My last question was the issue with finding elements with selenium, but i found another way to get them. Now i get a full string of the details of all devices that are connected to my wifi network. It looks like this: @ @ pc/devicename1/ConnectedProtocol (usually 802.11)/Device mac address/DHCP/local ip adress/a random number that i don't want to use /another number that i don't want to use/ipv6 address/:ipv6::|pc/devicename1/ConnectedProtocol (usually 802.11)/Device mac address/DHCP/local ip adress/a random number that i don't want to use/another number that i don't want to use/ipv6 address/:ipv6 address::|@ 0@ 0|0|0|0@ 1@ So a normal device list looks like this: @ @pc/android-d45cb2db4c2da/802.11/12:34:56:78:90:ab/DHCP/192.168.1.2/2/1/fe60::84c5:6de3:fe65:6bd8/:84c5:6de3:fe65:6bd8/::|pc/android-cd4b56add5/802.11/12:34:56:78:90:ab/DHCP/192.168.1.3/2/35/fe60::1547:bbb:fe69:8441/:2605:fff:fe97:9145/::@ 0@ 1|0|0|0@ 1@ Output should be like this: Device name: android-d45cb2db4c2da Mac address: 12:34:56:78:90:ab Local ip: 192.168.1.2 Connection Protocol: Wlan And then another device. How do i do that?
answer count: 1
downvote count: 1
tagged with: parsing
favorite count: 0
tagged with: python-3.x
tagged with: python
linked to: http://stackoverflow.com/q/52230128

http://stackoverflow.com/comment/91248987
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52149198
type: Comment
has text: Yes, but that isn't the answer you provided.

http://stackoverflow.com/a/52209654
has comment: http://stackoverflow.com/comment/91369655
has body: You can use get_dummies() by assigning a 1 to the maximum index df[df.filter(like='level').columns] = pd.get_dummies(df.filter(like='level').idxmax(1)) id level1 level2 level3 0 1 0 1 0 1 2 0 0 1 2 3 0 1 0 3 4 0 0 1 4 5 1 0 0
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/52209356
answers question: http://stackoverflow.com/q/52209356
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91261117
comment on: http://stackoverflow.com/q/52155213
type: QuestionComment
score: 2
has text: Indeed it would be helpful to see a [mcve], i.e. a code where all input variables are defined and that can be run. Also, which version matplotlib version is used here?
type: Comment

http://stackoverflow.com/a/52242260
answers question: http://stackoverflow.com/q/52242140
has comment: http://stackoverflow.com/comment/91433103
upvote count: 2
has comment: http://stackoverflow.com/comment/91433120
type: Answer
has comment: http://stackoverflow.com/comment/91433046
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91433090
has body: An easy way to sort the set by the index of the element is the list l: def unique(l): return list(sorted(set(l),key=l.index)) print(unique([1,2,3,3])) Output: [1, 2, 3]

http://stackoverflow.com/comment/91475571
type: Comment
has text: the old toolbar is being added in the `actions.extend(DecoratedScene._actions_default(self))` line.
score: 1
comment on: http://stackoverflow.com/a/52222953
type: AnswerComment

http://stackoverflow.com/comment/91331515
score: 0
comment on: http://stackoverflow.com/a/52190756
type: Comment
has text: I added more details to my post, hope that makes sense.
type: AnswerComment

http://stackoverflow.com/q/52227248
has comment: http://stackoverflow.com/comment/91404293
upvote count: 1
has answer: http://stackoverflow.com/a/52227474
tagged with: dataframe
type: UnansweredQuestion
has title: Create a new column if one dataframe's row value is in another data frame's column and get that index
has comment: http://stackoverflow.com/comment/91404171
tagged with: pandas
has answer: http://stackoverflow.com/a/52227447
downvote count: 0
has body: I may be overcomplicating this problem, however I can't seem to find a simple solution. I have two DataFrame's. Let's call them df1 and df2. To keep things simple. Let's say df1 has one column called "Some Data" and df2 has two columns called "some data" and "other data". Example: df1 Some Data "Lebron James 123" "Lebron James 234" df2 some data other data "Lebron James 123 + other text" "I want this in df1["New?"]" "Michael Jordan" "Doesn't Matter" So basically I want to create a new column in df1 called "New?". This new column (in df1) will say "New" if df1["Some data"] is in df2["Some other data"]. However, if there is no instance in df2["some data"], then I set the df1["New?"] to that specific row's value in df2["other data"]. Desired result after running: df1 Some Data New? "Lebron James 123" "I want this in df1["New?"]" "Lebron James 234" "New" So as you can see The New? column would include that specific row's value from the other data column. Lebron James 234 isn't anywhere in some data in df2 so it says new. I am able to get it to say True or False using the .isin() method, however don't know how to grab the index of the other df and get the value from the other data column. Thank you EDIT: From what I know will work df["New?"] = df1["Some Data"].isin(df2["some data"]) Would render df1["New?"] True False So I want True to be the "I want this in df1["New?"]" and False to be New
score: 1
has comment: http://stackoverflow.com/comment/91404012
favorite count: 0
type: Question
answer count: 2
tagged with: python

http://stackoverflow.com/q/52248558
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52248739
type: Question
has answer: http://stackoverflow.com/a/52248719
has body: So for example I have the following list of lists A = [['PokedexNumber', 'Name', 'Type', 'Total'], [1.0, 'Bulbasaur', 'GrassPoison', 318.0], [2.0, 'Ivysaur', 'GrassPoison', 405.0],[3.0, 'Venusaur', 'GrassPoison', 525.0]] How do i change it to dictionary of dictionaries? B = { 1.0 : { 'Name' : 'Bulbasaur', 'Type' : 'GrassPoison', 'Total' : 318.0}, 2.0 : {'Name' : 'Ivysaur', 'Type' : 'GrassPoison', 'Total' : 405.0}, 3.0 : {'Name' : 'Venusaur', 'Type' : 'GrassPoison', 'Total' : 525.0} }
has answer: http://stackoverflow.com/a/52248634
accepted answer: http://stackoverflow.com/a/52248634
favorite count: 0
upvote count: 3
has title: How to change a list of list to a dictionary of dictionary?
answer count: 4
tagged with: python-3.x
downvote count: 0
possible better answer: http://stackoverflow.com/a/52248883
tagged with: python
has answer: http://stackoverflow.com/a/52248883
tagged with: dictionary

http://stackoverflow.com/comment/110153082
score: 0
type: Comment
has text: @JohnS can you accept the answer now? the comment has been moved into the answer section.
type: AnswerComment
comment on: http://stackoverflow.com/a/52211409

http://stackoverflow.com/comment/91232931
type: Comment
comment on: http://stackoverflow.com/a/52141172
has text: I’ve edited the answer to add a bit more exposition about dict internals, and why that matters here.
type: AnswerComment
score: 0

http://stackoverflow.com/a/52189190
downvote count: 0
score: 1
has body: You can try, mask = tf.sign(images)*255 (if images is of values >=0) For replacing values greater than a threshold, you can do: thres = 10 cond = tf.greater(images, tf.ones(tf.shape(images))*thres) mask = tf.where(cond, tf.ones(tf.shape(images))*255, tf.zeros(tf.shape(images)))
type: Answer
accepted answer of: http://stackoverflow.com/q/52188742
answers question: http://stackoverflow.com/q/52188742
upvote count: 1
has comment: http://stackoverflow.com/comment/91356794
type: AcceptedAnswer

http://stackoverflow.com/a/52188931
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52188616
answers question: http://stackoverflow.com/q/52188616
has comment: http://stackoverflow.com/comment/91327835
type: Answer
score: 2
has body: First convert numeric data to numeric series: num_cols = ['birthYear', 'deathYear'] df[num_cols] = df[num_cols].apply(pd.to_numeric, errors='coerce') Specifying errors='coerce' forces non-convertible elements to NaN. Then create masks for your 3 conditions, combine via the vectorised | "or" operator, negate via ~, and apply Boolean indexing on your dataframe: m1 = df['birthYear'].isnull() m2 = df['birthYear'] &lt; 1950 m3 = df['deathYear'].notnull() res = df[~(m1 | m2 | m3)]
has comment: http://stackoverflow.com/comment/91327931
upvote count: 2

http://stackoverflow.com/q/52231917
accepted answer: http://stackoverflow.com/a/52232931
has comment: http://stackoverflow.com/comment/91414489
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91414561
has comment: http://stackoverflow.com/comment/91414462
upvote count: 1
has answer: http://stackoverflow.com/a/52232931
type: Question
has title: Pandas/NumPy -- Plotting Dates as X axis
has comment: http://stackoverflow.com/comment/91414492
score: 1
has comment: http://stackoverflow.com/comment/91414435
has comment: http://stackoverflow.com/comment/91414417
tagged with: numpy
has comment: http://stackoverflow.com/comment/91414443
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91414407
tagged with: python
has body: My Goal is just to plot this simple data, as a graph, with x data being dates ( date showing in x-axis) and price as the y-axis. Understanding that the dtype of the NumPy record array for the field date is datetime64[D] which means it is a 64-bit np.datetime64 in 'day' units. While this format is more portable, Matplotlib cannot plot this format natively yet. We can plot this data by changing the dates to DateTime.date instances instead, which can be achieved by converting to an object array: which I did below view the astype('0'). But I am still getting this error : view limit minimum -36838.00750000001 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-DateTime value to an axis that has DateTime units code: import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv(r'avocado.csv') df2 = df'Date','AveragePrice','region' df2 = (df2.loc[df2['region'] == 'Albany']) df2['Date'] = pd.to_datetime(df2['Date']) df2['Date'] = df2.Date.astype('O') plt.style.use('ggplot') ax = df2'Date','AveragePrice'.plot(kind='line', title ="Price Change",figsize=(15,10),legend=True, fontsize=12) ax.set_xlabel("Period",fontsize=12) ax.set_ylabel("Price",fontsize=12) plt.show() df.head(3) Unnamed: 0 Date AveragePrice Total Volume 4046 4225 4770 Total Bags Small Bags Large Bags XLarge Bags type year region 0 0 2015-12-27 1.33 64236.62 1036.74 54454.85 48.16 8696.87 8603.62 93.25 0.0 conventional 2015 Albany 1 1 2015-12-20 1.35 54876.98 674.28 44638.81 58.33 9505.56 9408.07 97.49 0.0 conventional 2015 Albany 2 2 2015-12-13 0.93 118220.22 794.70 109149.67 130.50 8145.35 8042.21 103.14 0.0 conventional 2015 Albany

http://stackoverflow.com/comment/91226994
type: QuestionComment
has text: For example: JavaScript in Internet Explorer 3.x and 4.x, and Netscape 2.x, 3.x and 4.x.
comment on: http://stackoverflow.com/q/52134226
score: 0
type: Comment

http://stackoverflow.com/comment/91471721
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52256408
has text: Instead of the single line 'mol = Chem.MolFromSmiles(row['SMILES'])' use the try and except loop, without the break, to exclude invalid SMILES.
score: 0

http://stackoverflow.com/comment/91269014
type: Comment
type: QuestionComment
has text: @Onyambu - I have clearly mentioned the details in the question itself, if you need any extra information then feel free to ask.
score: 0
comment on: http://stackoverflow.com/q/52159364

http://stackoverflow.com/comment/91298530
type: QuestionComment
has text: "...export it into Python (being the only supported language of target application)." Can you clarify this? Does this mean the target application exposes a Python API? Does target application provide an interface for a common data transfer format like XML?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52173409

http://stackoverflow.com/a/54001756
score: 1
upvote count: 1
downvote count: 0
type: Answer
has body: Short answer: community_infomap from python-igraph is a stochastic algorithm by nature. To produce reproducible output for it (and possibly other stochastic algorithms, such as graph generation), you can initialize the random number generator by python's built-in RNG In [1]: import random In [2]: random.seed(11) source: answer from the developer
answers question: http://stackoverflow.com/q/52135415

http://stackoverflow.com/q/52172859
score: 7
answer count: 2
tagged with: deep-learning
accepted answer: http://stackoverflow.com/a/52173844
tagged with: loss
downvote count: 0
tagged with: keras
has comment: http://stackoverflow.com/comment/91298896
favorite count: 0
possible better answer: http://stackoverflow.com/a/59819584
tagged with: python
has answer: http://stackoverflow.com/a/59819584
has comment: http://stackoverflow.com/comment/91298558
linked to: http://stackoverflow.com/q/52034983
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91296998
has answer: http://stackoverflow.com/a/52173844
has comment: http://stackoverflow.com/comment/91299559
upvote count: 7
has comment: http://stackoverflow.com/comment/91298156
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/91297721
has title: loss calculation over different batch sizes in keras
type: Question
has body: I know that in theory, the loss of a network over a batch is just the sum of all the individual losses. This is reflected in the Keras code for calculating total loss. Relevantly: for i in range(len(self.outputs)): if i in skip_target_indices: continue y_true = self.targets[i] y_pred = self.outputs[i] weighted_loss = weighted_losses[i] sample_weight = sample_weights[i] mask = masks[i] loss_weight = loss_weights_list[i] with K.name_scope(self.output_names[i] + '_loss'): output_loss = weighted_loss(y_true, y_pred, sample_weight, mask) if len(self.outputs) &gt; 1: self.metrics_tensors.append(output_loss) self.metrics_names.append(self.output_names[i] + '_loss') if total_loss is None: total_loss = loss_weight * output_loss else: total_loss += loss_weight * output_loss However, I noticed that when I train a network with a batch_size=32 and a batch_size=64, the loss value for every epoch still comes out to more or less the same with only a ~0.05% difference. However, the accuracy for both networks remained the exact same. So essentially, the batch size didn't have too much effect on the network. My question is when I double the batch size, assuming the loss is really being summed, shouldn't the loss in fact be double the value it was previously, or at least greater? The excuse that the network probably learned better with the bigger batch size is negated by the fact the accuracy has stayed exactly the same. The fact that the loss stays more or less the same regardless of the batch size makes me think it's being averaged.

http://stackoverflow.com/comment/91197668
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52121833
has text: @alonisser I've expanded the answer, hope this will solve your problem.

http://stackoverflow.com/q/52179551
has comment: http://stackoverflow.com/comment/91309250
tagged with: leaflet
has title: Python data won't load properly in JavaScript Leaflet map
has comment: http://stackoverflow.com/comment/91311991
has comment: http://stackoverflow.com/comment/91312749
has comment: http://stackoverflow.com/comment/91309297
has comment: http://stackoverflow.com/comment/91309180
score: 2
has body: I'm trying to take user input of a home address from a text box, geocode the address, and load the data on a leaflet map. I'm getting the correct latitude and longitude, and it's appearing on my html template as intended. However, if I try to pass that python data to JavsScript, the data doesn't load. Not sure if I'm explaining this correctly; I'm very new to programming. Here's my code: HTML index &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Examples&lt;/title&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;enter your address&lt;/h1&gt; &lt;form method="POST" action="/"&gt; &lt;div class="form-group"&gt; &lt;input type="text" name="address"&gt; &lt;/div&gt; &lt;input class="btn btn-primary" type="submit" value="submit"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; HTML template that loads after button is clicked &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Examples&lt;/title&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"&gt; &lt;link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" /&gt; &lt;link rel="stylesheet" href="static/style.css"&gt; &lt;script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"&gt;&lt;/script&gt; &lt;script src="https://code.jquery.com/jquery-2.1.4.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="static/map.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;address is {{ userlat, userlng }}&lt;/h1&gt; &lt;div id="map"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; Python/Flask file from flask import Flask, render_template, request from geopy.geocoders import GoogleV3 app = Flask(__name__)…
answer count: 0
downvote count: 0
tagged with: javascript
type: UnansweredQuestion
tagged with: flask
type: Question
has comment: http://stackoverflow.com/comment/91313431
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/91317468
tagged with: python

http://stackoverflow.com/comment/91455399
type: AnswerComment
has text: I _do_ enjoy it, actually.
type: Comment
comment on: http://stackoverflow.com/a/52253716
score: 0

http://stackoverflow.com/comment/91474226
has text: I don't think your quantile calculation is right
comment on: http://stackoverflow.com/q/52263060
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/53364128
score: 2
answers question: http://stackoverflow.com/q/52139110
downvote count: 0
upvote count: 2
has body: you still can use sorted and specify the items(). ordered_dict_items = sorted(Not_Ordered.items(), key=lambda x: key_order.index(x[0])) return dict((x, y) for x, y in ordered_dict_items) # to convert tuples to dict or directly using lists: ordered_dict_items = [(k, Not_Ordered[k]) for k in key_order] return dict((x, y) for x, y in ordered_dict_items) # to convert tuples to
type: Answer

attributeerror
tags question: http://stackoverflow.com/q/52135651
type: Tag
tags question: http://stackoverflow.com/q/52176570
tags question: http://stackoverflow.com/q/52221931
tag name: attributeerror
tags question: http://stackoverflow.com/q/52126837
tags question: http://stackoverflow.com/q/52170130
tags question: http://stackoverflow.com/q/52230219

http://stackoverflow.com/q/52121006
has body: Notes: I am using Python v3.6 I have read the documentation regarding Modules and Packages I have read and gone through the Packaging project tutorial I have looked at the Sample Project (different from tutorial project) I have a simple package I want to make myPackage/ The project directory myPackage/ Top-level package __init__.py Initialize my package myClass.py a file with a single class in it setup.py README.md ... dist/ where myClass.py is just class myClass: __init__(self): print('here') and my myPackage/__init__.py file is just like the demo name = "myPackage" I have successful got it on pypi and pip installed it. I can import myPackage but unlike the tutorial where example_pkg.name works, myPackage.name does not. The above linked Sample project doesn't exactly elaborate any more on the init.py file. So my question is as follows: suppose one had a package like that under the documentation for Modules and Packages: sound/ Top-level package __init__.py Initialize the sound package formats/ Subpackage for file format conversions __init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py ... effects/ Subpackage for sound effects __init__.py echo.py surround.py reverse.py ... filters/ Subpackage for filters __init__.py equalizer.py vocoder.py karaoke.py ... where the actual file structure is (following the packaging project tutorial) sound/ sound/ (Top-level package) __init__.py ... dist/ build/ sound.egg/ README.md ... What goes in sound/__init__.py (or myPackage/__init__.py) so that I can import it and access the functions, submodules, and classes therein? Sorry for being an noob at python packaging. # contents of setup.py import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="progil", version="0.0.4", author="name", author_email="name@web", description="Progress In Line", long_description=long_description, long_description_content_type="text/markdown", url="https://pypi.org/project/progil/…
has comment: http://stackoverflow.com/comment/91194966
accepted answer: http://stackoverflow.com/a/52121935
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/91193522
upvote count: 4
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91195014
has answer: http://stackoverflow.com/a/52121935
tagged with: python-module
tagged with: python
has comment: http://stackoverflow.com/comment/91194938
type: AnsweredQuestion
has title: Python3 preparing packages for PyPi not including submodules
tagged with: python-packaging
has comment: http://stackoverflow.com/comment/91194886
tagged with: pypi
type: Question

http://stackoverflow.com/q/52204265
has answer: http://stackoverflow.com/a/52849378
type: Question
has comment: http://stackoverflow.com/comment/91358123
has comment: http://stackoverflow.com/comment/91358463
has comment: http://stackoverflow.com/comment/91358235
score: 0
tagged with: deep-learning
answer count: 1
has comment: http://stackoverflow.com/comment/91362643
has comment: http://stackoverflow.com/comment/91358371
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Facing Issues while importing Tensorflow
has comment: http://stackoverflow.com/comment/91357875
has comment: http://stackoverflow.com/comment/91358221
linked to: http://stackoverflow.com/q/50430086
has body: I am new to tensorflow. I have installed tensorflow. But while i am executing below query: import tensorflow as tf I am getting below error: --------------------------------------------------------------------------- ImportError Traceback (most recent call last) C:\ProgramData\Anaconda3\lib\site- packages\tensorflow\python\pywrap_tensorflow_internal.py in swig_import_helper() 13 try: ---&gt; 14 return importlib.import_module(mname) 15 except ImportError: C:\ProgramData\Anaconda3\lib\importlib\__init__.py in import_module(name, package) 125 level += 1 --&gt; 126 return _bootstrap._gcd_import(name[level:], package, level) 127 C:\ProgramData\Anaconda3\lib\importlib\_bootstrap.py in _gcd_import(name, package, level) C:\ProgramData\Anaconda3\lib\importlib\_bootstrap.py in _find_and_load(name, import_) C:\ProgramData\Anaconda3\lib\importlib\_bootstrap.py in _find_and_load_unlocked(name, import_) C:\ProgramData\Anaconda3\lib\importlib\_bootstrap.py in _load_unlocked(spec) C:\ProgramData\Anaconda3\lib\importlib\_bootstrap.py in module_from_spec(spec) C:\ProgramData\Anaconda3\lib\importlib\_bootstrap_external.py in create_module(self, spec) C:\ProgramData\Anaconda3\lib\importlib\_bootstrap.py in _call_with_frames_removed(f, *args, **kwds) ImportError: DLL load failed with error code -1073741795 During handling of the above exception, another exception occurred: ModuleNotFoundError Traceback (most recent call last) C:\ProgramData\Anaconda3\lib\site- packages\tensorflow\python\pywrap_tensorflow.py in &lt;module&gt;() 57 ---&gt; 58 from tensorflow.python.pywrap_tensorflow_internal import * 59 from tensorflow.python.pywrap_tensorflow_internal import __version__ C:\ProgramData\Anaconda3\lib\site- packages\tensorflow\python\pywrap_tensorflow_internal.py in &lt;module&gt;() 16 return importlib.import_module('_pywrap_tensorflow_internal') ---&gt; 17 _pywrap_tensorflow_internal = swig_import_helper() 18 del swig_import_helper C:\ProgramData\Anaconda3\lib\site- packages\tensorflow\pyt…
tagged with: tensorflow

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

http://stackoverflow.com/comment/91187476
type: QuestionComment
has text: Also, where are the examples that put the coefficients and p-value on the chart?
comment on: http://stackoverflow.com/q/52118245
score: 0
type: Comment

global
type: Tag
tag name: global
tags question: http://stackoverflow.com/q/52131147
tags question: http://stackoverflow.com/q/52225266

http://stackoverflow.com/comment/91334843
has text: All your items in the sizers don't change its size, except the area for the pair of buttons, This area will grow horizontally, but not the buttons it contains. The BackButton should stay always size-unchanged at bottom-left corner. Apart from what Igor asked you, please edit the question and explain the desired behaviour when the window is resized.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52190821

matplotlib
tags question: http://stackoverflow.com/q/52202032
tags question: http://stackoverflow.com/q/52202014
tags question: http://stackoverflow.com/q/52117705
tags question: http://stackoverflow.com/q/52115896
tags question: http://stackoverflow.com/q/52251582
tags question: http://stackoverflow.com/q/52208987
tags question: http://stackoverflow.com/q/52120470
tags question: http://stackoverflow.com/q/52243616
tags question: http://stackoverflow.com/q/52171040
tags question: http://stackoverflow.com/q/52165938
tags question: http://stackoverflow.com/q/52191695
tags question: http://stackoverflow.com/q/52133926
tags question: http://stackoverflow.com/q/52140376
tags question: http://stackoverflow.com/q/52182322
tags question: http://stackoverflow.com/q/52164612
tags question: http://stackoverflow.com/q/52239312
tags question: http://stackoverflow.com/q/52189613
tags question: http://stackoverflow.com/q/52217601
tags question: http://stackoverflow.com/q/52161219
tags question: http://stackoverflow.com/q/52227678
tags question: http://stackoverflow.com/q/52122392
tags question: http://stackoverflow.com/q/52147558
tags question: http://stackoverflow.com/q/52261620
tags question: http://stackoverflow.com/q/52208322
tags question: http://stackoverflow.com/q/52197740
tags question: http://stackoverflow.com/q/52117827
tags question: http://stackoverflow.com/q/52263769
tags question: http://stackoverflow.com/q/52134845
tags question: http://stackoverflow.com/q/52199282
tags question: http://stackoverflow.com/q/52259574
tags question: http://stackoverflow.com/q/52132584
tags question: http://stackoverflow.com/q/52265575
tags question: http://stackoverflow.com/q/52127800
tags question: http://stackoverflow.com/q/52214776
tags question: http://stackoverflow.com/q/52146103
tag name: matplotlib
tags question: http://stackoverflow.com/q/52258535
tags question: http://stackoverflow.com/q/52206998
tags question: http://stackoverflow.com/q/52173126
tags question: http://stackoverflow.com/q/52253114
tags question: http://stackoverflow.com/q/52171321
tags question: http://stackoverflow.com/q/52177938
tags question: http://stackoverflow.com/q/52203981
tags question: http://stackoverflow.com/q/52182547
tags question: http://stackoverflow.com/q/52165481
tags question: http://stackoverflow.com/q/52132289
tags question: http://stackoverflow.com/q/52229875
tags question: http://stackoverflow.com/q/52259384
tags question: http://stackoverflow.com/q/52261435
tags question: http://stackoverflow.com/q/52152833
tags question: http://stackoverflow.com/q/52245074
tags question: http://stackoverflow.com/q/52165037
tags question: http://stackoverflow.com/q/52217438
tags question: http://stackoverflow.com/q/52228956
tags question: http://stackoverflow.com/q/52121498
tags question: http://stackoverflow.com/q/52172227
tags question: http://stackoverflow.com/q/52222233
tags question: http://stackoverflow.com/q/52146100
tags question: http://stackoverflow.com/q/52212326
tags question: http://stackoverflow.com/q/52124240
tags question: http://stackoverflow.com/q/52240633
tags question: http://stackoverflow.com/q/52182746
tags question: http://stackoverflow.com/q/52236996
tags question: http://stackoverflow.com/q/52118454
tags question: http://stackoverflow.com/q/52190649
tags question: http://stackoverflow.com/q/52244319
tags question: http://stackoverflow.com/q/52185398
tags question: http://stackoverflow.com/q/52126542
tags question: http://stackoverflow.com/q/52162794
tags question: http://stackoverflow.com/q/52122193
tags question: http://stackoverflow.com/q/52121335
tags question: http://stackoverflow.com/q/52264242
tags question: http://stackoverflow.com/q/52231010
tags question: http://stackoverflow.com/q/52254498
tags question: http://stackoverflow.com/q/52225713
tags question: http://stackoverflow.com/q/52118110
tags question: http://stackoverflow.com/q/52160432
tags question: http://stackoverflow.com/q/52234935
tags question: http://stackoverflow.com/q/52238567
tags question: http://stackoverflow.com/q/52260907

http://stackoverflow.com/comment/91398306
score: 0
type: AnswerComment
type: Comment
has text: @Mkike Yes but I think this is not a big problem here since the OP probably doesn't want the player to be able to do anything in the GUI while the moves are displayed.
comment on: http://stackoverflow.com/a/52223449

http://stackoverflow.com/q/52116762
type: Question
has comment: http://stackoverflow.com/comment/91185397
has comment: http://stackoverflow.com/comment/91187654
answer count: 2
possible better answer: http://stackoverflow.com/a/52118883
has answer: http://stackoverflow.com/a/52116844
downvote count: 0
has answer: http://stackoverflow.com/a/52118883
tagged with: string
has title: How to find substrings between substrings within a python string?
favorite count: 0
tagged with: bioinformatics
tagged with: python
has body: Let the string be "AAAGQWERTYUIOPAGCTHJKLAAAGZXCVBNMAGCT". I want to find the strings between AAAG and AGCT. I would like the output to be ["QWERTYUIOP","ZXCVBNM"], i.e. a list of strings. How can I use regex or similar techniques to do this? I tried this def find_distances_between_motifs(positions1, positions2, motif_length1): diff1 = [] diff2 = [] pos2 = 0 flag = 0 for pos1 in range(len(positions1)): if pos2 &gt;= len(positions2): break if flag == 1: flag = 0 pos1 -= 1 if positions2[pos2] - positions1[pos1] &gt; 30: diff1.append(NaN) diff2.append(NaN) continue elif positions2[pos2] - positions1[pos1] &lt; 1: pos2 += 1 diff2.append(NaN) flag = 1 elif pos1 &lt; len(positions1) - 1 and positions1[pos1+1] &gt; positions2[pos2]: diff1.append(positions[pos2] - positions[pos1] - motif_length1) diff2.append(pos2) pos2 += 1 else: continue return diff1, diff2 I wanted to return two arrays - one with location of length of sequences in between motifs and second with the location of second motif which will give the previous distances.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52116844
score: 1
upvote count: 1

http://stackoverflow.com/comment/91268946
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52159531
has text: Could you provide a link to the library docs and source please?
score: 0

http://stackoverflow.com/comment/91344772
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52197487
type: Comment
has text: How are you populating the data in the table?

http://stackoverflow.com/q/52173272
has comment: http://stackoverflow.com/comment/91300880
has answer: http://stackoverflow.com/a/52176711
tagged with: algorithm
has comment: http://stackoverflow.com/comment/91300805
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/91297307
has comment: http://stackoverflow.com/comment/91303918
has title: How to generate all possible max-heaps from a list of numbers?
upvote count: 0
has comment: http://stackoverflow.com/comment/91303881
has comment: http://stackoverflow.com/comment/91301243
has comment: http://stackoverflow.com/comment/91301214
favorite count: 0
has comment: http://stackoverflow.com/comment/91300856
has comment: http://stackoverflow.com/comment/91301242
has comment: http://stackoverflow.com/comment/91300915
has comment: http://stackoverflow.com/comment/91297987
type: Question
tagged with: heap
has comment: http://stackoverflow.com/comment/91302980
tagged with: python
has comment: http://stackoverflow.com/comment/91301256
has comment: http://stackoverflow.com/comment/91297365
has comment: http://stackoverflow.com/comment/91298117
downvote count: 3
has body: The max-heaps can have arbitrary branching factors within the same tree itself. For instance given [8,5,3,1] some of the heaps generated could be 8 or 8 or 8 /|\ | | 5 1 3 5 5 and so on..... (a) / \ | 3 1 3 (b) | 1 (c) For my purposes , I consider tree (a) above the same as trees (d) and (e) below 8 8 /|\ /|\ and so on..... 3 5 1 1 5 3 (d) (e) Edit : (1) I have tried an algorithm to generate all possible trees and then filter based on the max-heap property. But clearly that is exponential and hence even a list with greater than 10 elements takes a while in Python. (2) I would like to construct thus only those trees that obey the max-heap property rather than filtering but am unable to formulate a recursive sub-problem out of this.
tagged with: max-heap
has comment: http://stackoverflow.com/comment/91303854
answer count: 1
tagged with: tree
has comment: http://stackoverflow.com/comment/91297798

http://stackoverflow.com/comment/91237335
score: 0
type: QuestionComment
type: Comment
has text: I think you need to use jsom dump. look here https://developer.rhino3d.com/guides/rhinopython/python-xml-json/
comment on: http://stackoverflow.com/q/52143587

http://stackoverflow.com/q/52260844
type: Question
has comment: http://stackoverflow.com/comment/91470058
upvote count: 0
has comment: http://stackoverflow.com/comment/91470229
score: -2
has answer: http://stackoverflow.com/a/52261525
has comment: http://stackoverflow.com/comment/91470153
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/52261525
linked to: http://stackoverflow.com/q/19500530
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91469599
downvote count: 2
tagged with: python
type: AnsweredQuestion
has body: Background I'm working on a python project (version 2.7) that generates a large amount of data over a long span of time (i.e. days to weeks). The amount of data generated over a week can be anywhere from 50MB to 2GB of data, roughly. The embedded system that runs this project has a decent amount of RAM (i.e. 64GB), but no persistent storage (data is offloaded over the network at random intervals), and I'd like to keep the amount of memory used by this project to minimum, while holding onto the in-memory data as long as possible. Problem This program is holding onto a massive in-memory list of string data, and I need to get the memory usage down. This data is not ready frequently (i.e. once per day), but is updated frequently (i.e. 1MB of data added at random intervals). I'm considering compressing it in-memory, since it's just a bunch of human-readable strings of ASCII-formatted text, and could hold onto data for a longer period of time before having to prune/delete the "oldest" entries. Question Is there a way, using standard/built-in Python functionality (i.e. no third party modules permitted), to: Create an in-memory, compressed list (to reduce the in-memory size of this massive list-of-strings). Allow for individual list entries to be extracted on-demand from the list. Allow for deleting individual entries (i.e. the "oldest" entries if the compressed in-memory list grows too large). Work So Far Compression: I've found examples on using zlib and pickle to store a compressed copy of data in-memory, but this doesn't appear to allow me to index into the compressed data to extract individual entries without first de-compressing the entire object. Deletion and extraction: Same issue as above, where it's an all-or-nothing approach. I could also create a list of compressed entries, but I'd prefer to compress the entire list rather than one entry at a time, to improve the compression ratio (i.e. take advantage of solid compression, since the same data is repeated often f…
has title: In-memory compressed seldom-accessed data
tagged with: compression

http://stackoverflow.com/comment/91454418
has text: I uploaded it from a local folder
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52253247

http://stackoverflow.com/q/52156445
downvote count: 0
has answer: http://stackoverflow.com/a/52156754
has title: pandas multiply multiple columns to make new df
favorite count: 0
has body: I'm starting with two dataframes - one filled with dummy variables for the day of the week, and another filled with dummies for the hour of the day (HE - hour ending). df1 = days of week = n x m, where n is number of observations, m is 6: Mon Tue Wed Thu Fri Sat 0 1 0 0 0 0 0 1 0 1 0 0 0 0 2 0 0 1 0 0 0 3 0 0 0 1 0 0 df2 = hours of the day = n x l, where n is num of obs, m is 23: HE1 HE2 HE3 HE4 HE5 ... HE22 HE23 0 1 0 0 0 0 ... 0 0 1 0 1 0 0 0 ... 0 0 2 0 0 1 0 0 ... 0 0 3 0 0 0 1 0 ... 0 0 I want to create a new df with dimensions n x (m times l), where m times l = 6*23 = 138: MonHE1 MonHE2 MonHE3 MonHE4 MonHE5 ... SatHE22 SatHE23 0 1 0 0 0 0 ... 0 0 1 0 1 0 0 0 ... 0 0 2 0 0 1 0 0 ... 0 0 3 0 0 0 1 0 ... 0 0 I am successful with this: hoursXdays = pd.DataFrame() Mon = hours.multiply(days['Mon'],axis='index').add_prefix('Mon') Tue = hours.multiply(days['Tue'],axis='index').add_prefix('Tue') Wed = hours.multiply(days['Wed'],axis='index').add_prefix('Wed') Thu = hours.multiply(days['Thu'],axis='index').add_prefix('Thu') Fri = hours.multiply(days['Fri'],axis='index').add_prefix('Fri') Sat = hours.multiply(days['Sat'],axis='index').add_prefix('Sat') hoursXdays = pd.concat([Mon, Tue, Wed, Thu, Fri, Sat],axis=1) I'm going to need to do this for a lot more dfs than just these few. If there's any way I can generalize this, I'd appreciate the help. Basically, is there a way in pandas to multiply two dataframes dimension n x m, n x l, to make a new df of dimension n x (m times l) ?
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/52156755
upvote count: 1
type: Question
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52156755
answer count: 2
possible better answer: http://stackoverflow.com/a/52156754

http://stackoverflow.com/comment/91326643
comment on: http://stackoverflow.com/q/52188408
score: 0
type: Comment
type: QuestionComment
has text: Just the number of same letters and all the words in my list are equal length, sadly idk what the coding would be i only have coding for the rest of the program

http://stackoverflow.com/comment/91339158
comment on: http://stackoverflow.com/q/52194605
has text: @ShadowRanger - sounds worth a try...if you be exactly specific with the regex, I would be able to share info if that's working or not
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91470923
type: QuestionComment
comment on: http://stackoverflow.com/q/52261458
type: Comment
has text: Thanks guys! `isin` did it :)
score: 0

http://stackoverflow.com/q/52191015
tagged with: http://stackoverflow.com/tag/html
accepted answer: http://stackoverflow.com/a/52191132
tagged with: python
tagged with: selenium-chromedriver
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91332113
score: 1
has comment: http://stackoverflow.com/comment/91332190
tagged with: selenium
has comment: http://stackoverflow.com/comment/91331952
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91332140
has comment: http://stackoverflow.com/comment/91332025
has answer: http://stackoverflow.com/a/52191132
has comment: http://stackoverflow.com/comment/91332294
answer count: 1
has title: Find and click element based on @onclick w/ Selenium
has body: I am trying to find a element using Selenium in Python that has the html like this: Work area Contained in a simple tag. I have tried using work_area = driver.find_element_by_css_selector('td[contains(@onclick, "work_area.php?SID"]') and using an absolute xpath work_area = driver.find_element_by_xpath("/html/body/table/tbody/tr[2]/td[1]/div/table/tbody/tr[2]/td/table/tbody/tr[3]/td") My buttons structure: +---------------------+ | Menu | +---------------------+ | Work Area | +---------------------+ | Details | +---------------------+ I am using Python 3.6, and Selenium is up to date, any suggestions? I have also tried different suggestions that I could find on stackoverflow but nothing helped.
favorite count: 0
upvote count: 2

http://stackoverflow.com/a/52238885
accepted answer of: http://stackoverflow.com/q/52238507
score: 5
type: Answer
answers question: http://stackoverflow.com/q/52238507
upvote count: 5
type: AcceptedAnswer
downvote count: 0
has body: There is no equivalent to opcode tracing in versions before 3.7. If there were, the feature wouldn't have been added to 3.7 in the first place. If you can upgrade to 3.7, then what you want is easy: def tracefunc(frame, event, arg): if event == 'call': frame.f_trace_opcodes = True elif event == 'opcode': if frame.f_code.co_code[frame.f_lasti] == dis.opmap['MAKE_FUNCTION']: makefunctiontracefunc(frame) return tracefunc sys.settrace(tracefunc) But if you can't… there are a number of more complicated things you could do, depending on what your reasons are for wanting this, but none of them are remotely easy: Use line tracing, and inspect the code until the next line. This is trivial for def, but for lambda (and comprehensions1) it's going to be a big pain, because a lambda (or even five of them) can appear in the middle of a statement. You could ast.parse the source, or examine the bytecode, to figure out that there are functions being defined within, but there's still no way to call your hook right at the time of definition. Instead of using tracing, write an import hook that modifies the code as it's being imported. The easy way to do this is probably at the AST level: after you parse the source, use a NodeTransformer to inject calls to some function2 before or after each def and lambda node, then compile the transformed tree. But you could also do it at the bytecode level with bytecode or byteplay, before or after each MAKE_FUNCTION.3 Script pdb instead of writing your own debugger. I'm not sure if this will even help, because pdb has no way to step through part of an expression in the first place. Debug CPython itself, and add a breakpoint in the MAKE_FUNCTION handler in the ceval loop that calls your code. Of course your code is in the debugger's interpreter—which can be Python for gdb and lldb, but it's still not the same Python interpreter you're debugging. And, while it's possible to recursively evaluate code into the debugged interpreter (or trigger its pdb), …

http://stackoverflow.com/comment/91413748
type: QuestionComment
comment on: http://stackoverflow.com/q/52224239
has text: I agree that packing the data as JSON seems to be overdoing it, but I am still curious to know what performance you get from this. You state it is too slow, so how many samples can this code handle? At a CPU speed of 1 GHz you should still have some 250.000 instructions per sample.
score: 0
type: Comment

http://stackoverflow.com/q/52133732
tagged with: python-unicode
has title: How to get SciKit-Learn to recognize my kernel in SVC?
type: Question
has body: I am using python 2.7. Documentation for SVC. When I try the following: from sklearn.svm import SVC base_learner = SVC(random_state=4,probability=True) It throws the following error: TypeError: Argument 'kernel' has incorrect type (expected str, got unicode) So I thought I would try this: from builtins import str from sklearn.svm import SVC base_learner = SVC(kernel=str('rbf'), random_state=4,probability=True) Still doesn't recognize the kernel. What am I doing wrong?
tagged with: scikit-learn
tagged with: python-2.7
score: 0
answer count: 1
tagged with: string
has answer: http://stackoverflow.com/a/52135622
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52135622
has comment: http://stackoverflow.com/comment/91220530

http://stackoverflow.com/q/52176055
tagged with: sympy
accepted answer: http://stackoverflow.com/a/52176187
answer count: 1
has comment: http://stackoverflow.com/comment/91302640
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91302672
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/52176187
type: Question
has comment: http://stackoverflow.com/comment/91302756
has body: I am a newbie to Python. I wondered if there is any way to access different elements of a symbolic block matrix using the sympy module. For example, I have generated the following code, I would want to see C_11+C_12 by using C[0] but instead I see C_11[0, 0] + C_13[0, 0] from sympy import * C_11 = MatrixSymbol('C_11', 5, 5) C_12 = MatrixSymbol('C_12', 5, 3) C_13 = MatrixSymbol('C_13', 5, 5) C_21 = C_12.T C_22 = MatrixSymbol('C_22', 3, 3) C_23 = MatrixSymbol('C_23', 3, 5) C_31 = C_13.T C_32 = C_23.T C_33 = MatrixSymbol('C_33', 5, 5) C = BlockMatrix([[C_11+C_13, C_12, C_13], [C_21, C_22, C_23], [C_31, C_32, C_33]]) C C[0]
has title: Access different blocks (submatrices) of a symbolic block matrix in SymPy

http://stackoverflow.com/a/75990476
type: Answer
answers question: http://stackoverflow.com/q/52171593
score: 2
has body: if you are trying to install the dependencies from pipfile using pipenv then its simple, first start or create new virtual environment by running this in your project directory pipenv shell then to install dependencies from pipfiles run this in the directory where your pipfile is located pipenv install
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/106960951
type: AnswerComment
has text: I'v wondered if DJango does this better. surely there is an established design pattern by now that works. maybe useful link https://www.youtube.com/watch?v=AuBai920D0E
type: Comment
comment on: http://stackoverflow.com/a/52238332
score: 0

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

http://stackoverflow.com/comment/91299566
has text: `N = 8192` Do you actually have this many samples? It seems you design your frequency axis based on hard-coded numbers rather than the information in the file. Use `len(data)` and `fs` instead!
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52174178
score: 1

http://stackoverflow.com/q/52132778
answer count: 1
has body: I have a couple of firebase python files, one that writes to my database fine, and one that retrieves data from my firebase database no problem. They are both written in Python 3.5.3. I have a flask website that I am developing, as soon as I use the import firebase_admin in MyFlaskApp.py it throws up the error no module named firebase_admin and I get the following error. flask.cli.NoAppException: While importing "TrialPage", an ImportError was raised: Traceback (most recent call last): File "/home/pi/Documents/WebFlask/venv/lib/python3.5/site- packages/flask/cli.py", line 236, in locate_app __import__(module_name) File "/home/pi/Documents/WebFlask/TrialPage.py", line 1, in &lt;module&gt; from firebase_admin import firebase_admin ImportError: No module named 'firebase_admin' my other files work completely fine, I can understand why this wont work with my flask file. I have even tried creating a brand new MyFlaskApp.py file just incase something was corrupt with the existing file I am using. This did not work. This error is thrown up regardless of whether the import firebase_admin is at the very top of my file or underneath my other imports, or in the middle of a function.
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: firebase
linked to: http://stackoverflow.com/q/56536650
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/56541695
type: Question
tagged with: firebase-admin
has title: firebase_admin works in Python but cannot import to Python Flask file
has comment: http://stackoverflow.com/comment/99656668
upvote count: 1

http://stackoverflow.com/q/52233115
tagged with: dataframe
upvote count: 8
has answer: http://stackoverflow.com/a/52233242
answer count: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52233292
has title: Filter pandas dataframe that has arrays in cells
tagged with: arrays
downvote count: 0
has body: I have a Pandas dataframe with a column 'htgt' this column consists of array with numbers inside. The size of the array is not constant. An example of the data: 11 [16, 69] 12 [61, 79] 13 [10, 69] 14 [81] 15 [12, 30, 45, 68] 16 [10, 76] 17 [9, 39] 18 [67, 69, 77] How can I filter all the rows that has the number 10 for example.
favorite count: 0
has answer: http://stackoverflow.com/a/52233292
has answer: http://stackoverflow.com/a/52233420
tagged with: python
has comment: http://stackoverflow.com/comment/91415442
score: 8
type: Question
possible better answer: http://stackoverflow.com/a/52233242
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91415450

http://stackoverflow.com/q/52147628
tagged with: python
has comment: http://stackoverflow.com/comment/91246536
has comment: http://stackoverflow.com/comment/91245251
type: UnansweredQuestion
upvote count: 1
has body: I want the print to update the days, hours, minutes and seconds, and not to write a new sentence with the updated data. So now it shows per example: 1 tage, 2 stunden, 3 minuten, 40 sekunden 1 tage, 2 stunden, 3 minuten, 39 sekunden and so on... All i want is to update the numbers, without writing a new line. I hope you can help me, Here's the code: #%%Import stuff import time import webbrowser import os #%% Type in your Values days = 0 hours = 4 mins = 0 secs = 0 #%% Functions counter = ((days * 86400) + (hours * 3600) + (mins * 60) + secs) def StartCounter(counter): if counter &lt; 0: print("Error, type in a positiv counter, Idiot") Music(counter) while counter &gt; 0: Darstellung(counter) time.sleep(1) counter += -1 message = "Fertig" return message def Check(): if StartCounter(counter) == "Fertig": print("Counter finished!") os.system("H:\Bearbeitet\Stopuhr\Song\Wecker.mp3") else: StartCounter(counter) def Music(counter): if counter &gt;= 90: if counter &gt;= 200: if counter &gt;= 3600: if counter &gt;= 86400: webbrowser.open("spotify:user:vostry.janek:playlist:3Rxuq9vevFUYJh4fJ7T9kC") else: webbrowser.open("H:\Bearbeitet\Stopuhr\Song\LangWarten.m4a") else: webbrowser.open("H:\Bearbeitet\Stopuhr\Song\Warten.mp3") else: webbrowser.open("H:\Bearbeitet\Stopuhr\Song\Song.mp3") else: webbrowser.open("H:\Bearbeitet\Stopuhr\Song\Sarah.mp3") def Darstellung(counter): tage = 0 stunden = 0 minuten = 0 sekunden = 0 while counter &gt; 0: if counter &gt;= 86400: counter += -86400 tage += +1 else: if counter &gt;= 3600: counter += -3600 stunden += +1 else: if counter &gt;= 60: counter += -60 minuten += +1 else: counter += -1 sekunden += +1 print("%s Tage, %s Stunden, %s Minuten und %s Sekunden" % (tage, stunden, minuten, sekunden), "\n") #%% Run Check()
type: Question
score: 1
has title: Update the print text
has answer: http://stackoverflow.com/a/52148468
tagged with: printing
answer count: 1
downvote count: 0
favorite count: 0
tagged with: stopwatch

http://stackoverflow.com/comment/91367771
type: AnswerComment
type: Comment
has text: Definitely. I for sure need to start debugging more and thinking by line instead of by group. This was great, thank you again.
comment on: http://stackoverflow.com/a/52209071
score: 0

http://stackoverflow.com/a/58959537
downvote count: 0
has body: I know it has been answered but I think there a moret pythonic way using calendar module import calendar current = 11 last_12_months = [calendar.month_name[1:][i] for i in range(current - 12, current)] # starting from the last reverse_last_12_months = reversed(last_12_months) # starting from the current
type: Answer
answers question: http://stackoverflow.com/q/52259242
upvote count: 1
score: 1

kivy-language
tags question: http://stackoverflow.com/q/52266572
type: Tag
tags question: http://stackoverflow.com/q/52126516
tags question: http://stackoverflow.com/q/52202538
tags question: http://stackoverflow.com/q/52200823
tags question: http://stackoverflow.com/q/52168199
tags question: http://stackoverflow.com/q/52207252
tag name: kivy-language
tags question: http://stackoverflow.com/q/52176106
tags question: http://stackoverflow.com/q/52232740

http://stackoverflow.com/q/52135293
has answer: http://stackoverflow.com/a/52249610
has comment: http://stackoverflow.com/comment/91232555
has comment: http://stackoverflow.com/comment/91232626
possible better answer: http://stackoverflow.com/a/52616554
tagged with: python
has title: Google Drive API: The user has not granted the app error
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91229830
downvote count: 0
score: 13
tagged with: google-oauth
type: Question
has comment: http://stackoverflow.com/comment/91229806
upvote count: 13
has body: I'm following the Quickstart on https://developers.google.com/drive/api/v3/quickstart/python. I've enabled the drive API through the page, loaded the credentials.json and can successfully list files in my google drive. However when I wanted to download a file, I got the message `The user has not granted the app ####### read access to the file` Do I need to do more than putting that scope in my code or do I need to activate something else? SCOPES = 'https://www.googleapis.com/auth/drive.file' client.flow_from_clientsecrets('credentials.json', SCOPES)
has comment: http://stackoverflow.com/comment/91234773
accepted answer: http://stackoverflow.com/a/52249610
answer count: 3
has comment: http://stackoverflow.com/comment/91232460
tagged with: google-api-python-client
has answer: http://stackoverflow.com/a/52616554
favorite count: 0
has answer: http://stackoverflow.com/a/65013767
tagged with: google-drive-api

http://stackoverflow.com/a/52196236
has comment: http://stackoverflow.com/comment/91341804
has body: Use numpy broadcasting s = pd.Series([1,2,3,4,5,6], index=dates) df.loc[:,:] = s.values[:,None] Using index matching df.loc[:] = pd.concat([s]*df.columns.size, axis=1)
has comment: http://stackoverflow.com/comment/137224889
downvote count: 0
has comment: http://stackoverflow.com/comment/91341930
answers question: http://stackoverflow.com/q/52196134
score: 14
accepted answer of: http://stackoverflow.com/q/52196134
has comment: http://stackoverflow.com/comment/91341850
upvote count: 14
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91341976
type: Answer

http://stackoverflow.com/q/52153912
has comment: http://stackoverflow.com/comment/91258624
type: AnsweredQuestion
has body: I would like to make console program which ping remote IPs. I use multithreading to ping several IP simulteneously. When all IPs is reachable, all look great, but when one IP is not reachable, other threads have to wait long until the bad ping is finished (I chose one unpingable IP in purpose), due to join method, which waits until all threads is ended. When I just removed join method my PC crushed. I did the following to overcome the issue (created infinite ping function, so no thead can be ended due to infinite method inside) and kept joinmethod in code, it works right, but is there any better choice? I guess the solution can have some drawbacks in resourse consuming or any other. My working code, which I have doubts with: The method below do one ping to b (IP) within t100 time interval def do_ping(b,t100): a=os.system(f"ping -n 1 {b}") h=good_time(time.localtime(),1) with open(f"noob_{h}_{b}.txt",mode="a") as f: t=good_time(time.localtime(),0) if(a==int(0)): f.write(f"The remote destination {b} is reachable, everyting is enter code hereOKAY. {t} \n") elif(a==int(1)): f.write(f"Ping {b} failed! {t} \n") time.sleep(int(t100)) infinite ping of one IP adress: def ping1(b,t100): while(True): IP_Op.do_ping(b,t100) main program: while(True): treadsN=[] for i in b: b is a list of IPs (the whole program also writes results in files and in future will send emails if ping fail for long period treadsN.append(threading.Thread(target=IP_Op.ping1, args=(i,3))) for i in treadsN: i.start() for i in treadsN: i.join()
has answer: http://stackoverflow.com/a/52154195
accepted answer: http://stackoverflow.com/a/52154195
tagged with: multithreading
has comment: http://stackoverflow.com/comment/91258479
type: Question
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91258650
has title: Multithreading. How to ping several IPs simultaneously properly?
tagged with: python

http://stackoverflow.com/comment/91295066
has text: I had answered but Im also confused. Shouldn't `df.loc[~df'p_x', 'p_y'.agg(frozenset,1).duplicated(keep=False)]` suffice?
comment on: http://stackoverflow.com/q/52171957
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91416053
score: 1
has text: Did you mean `numpy` instead of `bumpy`? ...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52233512

http://stackoverflow.com/comment/91408354
type: QuestionComment
has text: Can you confirm that the uploaded photos are showing up in `/static/uploads`?
score: 0
comment on: http://stackoverflow.com/q/52229010
type: Comment

http://stackoverflow.com/q/52186108
has comment: http://stackoverflow.com/comment/91321938
has body: I have a problem where I have a massive nested dictionary running and am looking to speed things up as the time it takes to go through the entire dictionary is about a week worth of processing time. Is there a faster way to iterating through something like the following (I'm not opposed to reworking the structure)? I need to iterate and not vectorize because the state for 2 depends on what happens in 1. I'm nesting like what happens below where the structure basically is def function(x): return 1 d = {'1': {'1a': 0, '1b': 0}, '2': {'2a': 0, '2b': 0, '2c': 0 } , '3': {'3a':0}} s = {} for outer_key, inner_dict in d.iteritems(): for inner_key, inner_value in inner_dict.iteritems(): s = function(inner_value) print(s)
type: Question
downvote count: 4
answer count: 1
favorite count: 0
score: -3
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52186653
has comment: http://stackoverflow.com/comment/91322362
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/91322297
has title: Python Optimizing Dict iteration

http://stackoverflow.com/comment/91466974
comment on: http://stackoverflow.com/a/52259742
has text: Hmm.. that gives me: >>> from .test import foo Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Attempted relative import in non-package
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91179103
comment on: http://stackoverflow.com/a/52114349
has text: Why? he already has `from tkinter import *`. why doesn't `Tk()` work as is?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/52158475
score: 0
has body: this functions can do it def replace_split(s, old, new): return sum([[blk, new for blk] in s.split(old)], [])[:-1]
type: Answer
has comment: http://stackoverflow.com/comment/91267178
upvote count: 1
answers question: http://stackoverflow.com/q/52158344
downvote count: 1

http://stackoverflow.com/q/52118251
has comment: http://stackoverflow.com/comment/91187800
has answer: http://stackoverflow.com/a/52118572
has comment: http://stackoverflow.com/comment/91187615
tagged with: python
possible better answer: http://stackoverflow.com/a/52118651
type: AnsweredQuestion
has title: easy tool to filtering columns with specific conditions using pandas
type: Question
has body: I'm wondering if exist a tool in python to filter data between columns that follow an specific condition. I need to generate a clean dataframe where all the data in column 'A' must have the same consecutive number in column 'E'(and this number is repeated at least twice). Here an example: df Out[30]: A B C D E 6 1 2.366 8.621 10.835 1 7 1 2.489 8.586 10.890 2 8 1 2.279 8.460 10.945 2 9 1 2.296 8.559 11.000 2 10 2 2.275 8.620 11.055 2 11 2 2.539 8.528 11.110 2 50 2 3.346 5.979 10.175 5 51 3 3.359 5.910 10.230 1 52 3 3.416 5.936 10.285 1 The output will be: df Out[31]: A B C D E 7 1 2.489 8.586 10.890 2 8 1 2.279 8.460 10.945 2 9 1 2.296 8.559 11.000 2 10 2 2.275 8.620 11.055 2 11 2 2.539 8.528 11.110 2 51 3 3.359 5.910 10.230 1 52 3 3.416 5.936 10.285 1
accepted answer: http://stackoverflow.com/a/52118572
has comment: http://stackoverflow.com/comment/91187526
tagged with: dataframe
score: 0
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/91187782
has answer: http://stackoverflow.com/a/52118651
has comment: http://stackoverflow.com/comment/91187546

http://stackoverflow.com/a/52152038
upvote count: 1
answers question: http://stackoverflow.com/q/52151831
score: 1
has body: Not sure, what you meant by messy but pd.concat handles it pretty well here: pd.concat([s for i in range(9)], axis=1) you can pass keys=[f'A{i}' for i in range(9)] to pd.concat to make distinct column names.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91254722
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52151831
type: Answer

http://stackoverflow.com/comment/91260746
score: 0
comment on: http://stackoverflow.com/q/52125009
type: QuestionComment
has text: You can check my answer.
type: Comment

http://stackoverflow.com/comment/91229335
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52120530
type: QuestionComment
has text: Don't copy nothing

http://stackoverflow.com/comment/91196982
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52121773
has text: @AndrasDeak Fine, that's a good point. Perhaps I was overzealous.
score: 1

odoo
tags question: http://stackoverflow.com/q/52173005
tags question: http://stackoverflow.com/q/52112891
tags question: http://stackoverflow.com/q/52206679
tags question: http://stackoverflow.com/q/52175453
tags question: http://stackoverflow.com/q/52145402
tags question: http://stackoverflow.com/q/52133965
tags question: http://stackoverflow.com/q/52261821
tags question: http://stackoverflow.com/q/52186692
tags question: http://stackoverflow.com/q/52161585
tags question: http://stackoverflow.com/q/52198414
type: Tag
tags question: http://stackoverflow.com/q/52230863
tags question: http://stackoverflow.com/q/52184713
tags question: http://stackoverflow.com/q/52149081
tags question: http://stackoverflow.com/q/52155705
tags question: http://stackoverflow.com/q/52163045
tags question: http://stackoverflow.com/q/52219202
tags question: http://stackoverflow.com/q/52203217
tags question: http://stackoverflow.com/q/52116711
tags question: http://stackoverflow.com/q/52164820
tag name: odoo

http://stackoverflow.com/comment/91445272
type: QuestionComment
score: 1
has text: if your camera is static (relative to the plane/space you measured once) you only have to do it once. But probably that's not the case?
comment on: http://stackoverflow.com/q/52246874
type: Comment

http://stackoverflow.com/a/52250953
type: Answer
has comment: http://stackoverflow.com/comment/91449613
score: 7
upvote count: 7
accepted answer of: http://stackoverflow.com/q/52250812
answers question: http://stackoverflow.com/q/52250812
has comment: http://stackoverflow.com/comment/91449566
type: AcceptedAnswer
downvote count: 0
has body: Here is how you can make a semi-opacity watermark appear of the color you requested: from PIL import Image, ImageDraw, ImageFont base = Image.open('cats.jpg').convert('RGBA') width, height = base.size # make a blank image for the text, initialized to transparent text color txt = Image.new('RGBA', base.size, (255,255,255,0)) # get a font fnt = ImageFont.truetype('arial.ttf', 40) # get a drawing context d = ImageDraw.Draw(txt) x = width/2 y = height/2 # draw text, half opacity d.text((x,y), "Hello", font=fnt, fill=(255,255,255,128)) txt = txt.rotate(45) out = Image.alpha_composite(base, txt) out.show()

http://stackoverflow.com/q/52140176
has body: I have installed a new font on my computer and have installed it on my computer as well. Now i am using it in my Python code using the tkinter Library but its not working. self.master = master self.my_font = tkinter.font.Font(self.master, family="My Girl Is Retro Regular") self.master.grid_rowconfigure(0, weight=2) self.master.grid_columnconfigure(0, weight=1) self.playPhoto = PhotoImage(file='toppic.png') self.toppic = Label(self.master,image=self.playPhoto) self.toppic.grid(pady=(0,50)) self.youtubeLinkLabel = Label(self.master, text="Paste the YouTube Link Below: ", font=("My Girl Is Retro Regular", 30),fg='red') self.youtubeLinkLabel.grid(pady=(0,20)) self.youtubeEntryVar = StringVar() self.youtubeEntry = Entry(self.master, width=70, textvariable=self.youtubeEntryVar,font=("Agency FB", 25),fg='green') self.youtubeEntry.grid(pady=(0, 15),ipady=10) self.youtubeEntryError = Label(self.master, text="", font=("Concert One", 20)) self.youtubeEntryError.grid(pady=(0, 8)) # Asking where to save file label self.youtubeFileLocationLabel = Label(self.master, text="Choose Directory: ",font=("My Girl Is Retro Regular", 60)) self.youtubeFileLocationLabel.grid() self.youtubeFileLocationEntry = Button(self.master, text="Directory", command=self.openDirectory) self.youtubeFileLocationEntry.grid(pady=(10, 3)) # Entry label if user don`t choose directory # openDirectory func self.fileLocationLabelError = Label(self.master, text="", font=("My Girl Is Retro Regular", 20)) self.fileLocationLabelError.grid() # What to download MP3 or MP4 label self.youtubeChooseLabel = Label(self.master, text="Please choose what to download: ", font=("My Girl Is Retro Regular", 30)) self.youtubeChooseLabel.grid() I have searched on Google but i can't figure it out
type: UnansweredQuestion
tagged with: python
tagged with: tkinter
tagged with: fonts
score: 1
has title: I am using a new Font in Python Tkinter
type: Question
has answer: http://stackoverflow.com/a/52140618
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/52123351
has body: Instead of this: int(iinventory.getCarrots()) += number What you want is: iinventory.carrots_num += number You may also create a method addCarrots(), so that you isolate the internal attribute from external calls, which has advantages in terms of testing and code maintainability. You could also rename the internal attribute to self._carrot_num and create a method carrot_num with a @property decorator.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52123234

http://stackoverflow.com/q/52135538
score: 0
answer count: 1
has body: I'm surprised, but I couldn't find anybody with the exact same requirements in Google, so here I go. I'm designing a Django project, and I know that sensitive documents will be uploaded by the users, so I need to introduce some kind of permission control mechanism (thinking about using JWT at the moment). To make my project stateless from an operational point of view (planning to run it in containers), I'd like to store my user-uploaded files in a distributed object storage system (S3/minio). This is where I'm getting lost. I know that in a "regular" Django production environment, the user-uploaded media files tend to go to the ./media folder, and the webserver serves it directly from there, without any kind of authentication. To me, this is risky and unacceptable, because shared direct links can be sniffed/leaked, and unauthorized people can get access to sensitive documents. Wrapping it up: What's the accepted practice to store/serve user-uploaded contents in/from S3/minio? How do I control access to these files? Thanks!
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: amazon-s3
type: Question
has answer: http://stackoverflow.com/a/52135595
has title: Serve media files with S3 backend and user permissions

http://stackoverflow.com/a/52144008
answers question: http://stackoverflow.com/q/52143854
has body: pandas.factorize and array slice assignment j, h = pd.factorize(df.Hour) i = np.arange(len(df)) b = np.zeros((len(df), len(h)), dtype=h.dtype) b[i, j] = 1 df.join(pd.DataFrame(b, df.index, h).add_prefix('HE')) Date Hour HE1 HE2 HE3 HE4 0 2005-01-01 1 1 0 0 0 1 2005-01-01 2 0 1 0 0 2 2005-01-01 3 0 0 1 0 3 2005-01-01 4 0 0 0 1
type: Answer
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/52115873
tagged with: python
favorite count: 0
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91184225
type: Question
has body: I have the following csv data, data.csv. It should be noted that the csv-file is properly formatted, and does not contain any 'weird' stuff. id,date,time,name,value,description 0,2017-01-07,2017-01-07 11:49:29,cool_name1,2,something 1,2017-01-07,2017-01-07 11:51:50,cool_name1,-1,something 2,2017-01-07,2017-01-07 14:03:42,cool_name2,9,something I read it in via: schema = {'id': float, 'date': str, 'time': str, 'name': str, 'value': float, 'description': str} df = pd.read_csv('data.csv', header=0, dtype=schema, parse_dates=['date', 'time']) which results in df.dtypes: id int64 date datetime64[ns] time datetime64[ns] name object value float64 description object Due to where the data is going, id has to be auto-parsed as specified by schema (float in this case). However, after trying a bunch of different keyword arguments in combination with each other, I can't get id to obey my dtype. List of what I have tried: dtype=schema converters=schema low_memory=False engine='c' AND 'python' index_col=False parse_dates=False It should be noted that the column value does obey dtype, and without it specified it becomes int64. What is the missing ingredient (pandas version 0.23.4)?
score: 1
has title: Make sure pandas read_csv obeys given dtypes
has comment: http://stackoverflow.com/comment/91182555
has comment: http://stackoverflow.com/comment/91182663
upvote count: 1
tagged with: pandas

http://stackoverflow.com/q/52134803
has comment: http://stackoverflow.com/comment/91219646
tagged with: python-3.x
has title: How to properly plot labels in a graph?
type: Question
has comment: http://stackoverflow.com/comment/91219827
has answer: http://stackoverflow.com/a/52134946
tagged with: python
has comment: http://stackoverflow.com/comment/91219795
has comment: http://stackoverflow.com/comment/91219815
possible better answer: http://stackoverflow.com/a/68141646
linked to: http://stackoverflow.com/q/16992038
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/68141646
has body: I want to plot a 'Sequence of function' in Python with the corresponding label for function inside the plot. I use matplotlib, however, I am facing the below issues. (1). The graph should label $f_n$ corresponding to each function. (2). It must save to a file with the labels included. Here is my code : import matplotlib as mpl mpl.rc('text', usetex = True) #for LaTex notation in the Plot mpl.rc('font', family = 'serif') import matplotlib.pyplot as plt import numpy as np plt.gca().set_aspect('equal', adjustable='box') plt.style.use(['ggplot','dark_background']) x=np.arange(-1,1,0.001) for i in range(1,5,1): y = 1 - (1 / (1+x**2)**i) plt.plot(x,y,label=i) plt.xlabel('$x$') plt.ylabel('$y$') plt.savefig('seqn_of_function1.eps', format='eps', dpi=1000) plt.legend() plt.show() The problem with this code is : This code gives the following output but cannot save the .eps file with the labels (plt.savefig('seqn_of_function1.eps', format='eps', dpi=1000)) It only labels 'i', however, I want it to label as $f_i$. I changed the line in my code as : plt.plot(x,y,label='$f_$',i) but it gives an "invalid_syntax" error.
accepted answer: http://stackoverflow.com/a/52134946
has comment: http://stackoverflow.com/comment/91219709
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91219630

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

http://stackoverflow.com/q/52206232
accepted answer: http://stackoverflow.com/a/52221653
has comment: http://stackoverflow.com/comment/91362757
has comment: http://stackoverflow.com/comment/91391990
has comment: http://stackoverflow.com/comment/91363095
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91363053
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/91391557
has title: Python 3.6 pointer being freed was not allocated when running mainloop in Pygame
has comment: http://stackoverflow.com/comment/91363202
has body: I have been working on a pygame project for a while now and started making the intro screens. Running the game and going through the intro screens works fine, but when I reach the main_loop() the game starts but quickly crashes afterwards. I had no problems with the main_loop() before this and was at a point I could go from intro_loop() to main_loop() and it worked, Its after I added story_screen_1() that now the main_loop() crashes with this error: Error Message /usr/local/bin/python3 "/Users/brucepouncey/Game_0/venv/Game_0_MASTERcopy.py" Python(1323,0x101931380) malloc: *** error for object 0x1040b64f0:pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug Process finished with exit code 134 (interrupted by signal 6: SIGABRT) So I back-tracked and removed everything I had implemented, back to the point that it was working. But the same error occured and now my main_loop() isnt even running even when its alone, I get the same error. Iv been over my code numerous times removing and moving things around and still no luck. I can usually pinpoint an error through its message but this one is a first. If I can know what this error message means I will hopefully be able to find the source of the bug. Alot of answers iv searched for are related to C languages and Im not familiar with them.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91362317
has answer: http://stackoverflow.com/a/52221653
has comment: http://stackoverflow.com/comment/91362391
has comment: http://stackoverflow.com/comment/91382200
has comment: http://stackoverflow.com/comment/91364660
type: Question

http://stackoverflow.com/q/52241456
has title: Idiomatic, Linear-time, Dictionary of Counts in Python
upvote count: 1
linked to: http://stackoverflow.com/q/26731675
favorite count: 0
has answer: http://stackoverflow.com/a/52241477
tagged with: python-3.x
tagged with: idioms
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/20510768
has comment: http://stackoverflow.com/comment/91432895
has comment: http://stackoverflow.com/comment/91431459
has body: I have some list: list = ["apple", "orange", "orange", "apple", "grape"] I want to turn this into a dictionary where the key is the fruit, and the value is the number of times it occurs in the list. The list could be rather large, so it would be good for it to be linear time. This is rather easy to do in a verbose way: from collections import DefaultDict dict_of_counts = DefaultDict(int) for item in list: dict_of_counts[item] += 1 This is clearly O(n) time, but it feels like I should be able to do it via a dictionary comprehension. The only things I can think of though involve multiple calls to len or count, so it would be O(kn) time (where k is the distinct number of keys in my list). Can someone point to a more "pythonic" way to do this (which I'd imagine involves the comprehension), or should I keep the above, verbose, implementation?
has comment: http://stackoverflow.com/comment/91431593
has comment: http://stackoverflow.com/comment/91432085
downvote count: 0
has comment: http://stackoverflow.com/comment/91431566
score: 1
type: Question
has comment: http://stackoverflow.com/comment/91431600
has answer: http://stackoverflow.com/a/52241473
has comment: http://stackoverflow.com/comment/91431720
has comment: http://stackoverflow.com/comment/91431658
has comment: http://stackoverflow.com/comment/91431485
duplicate of: http://stackoverflow.com/q/20510768
answer count: 2

http://stackoverflow.com/q/52137047
score: 16
downvote count: 1
tagged with: tensorflow
upvote count: 17
linked to: http://stackoverflow.com/q/49626572
has body: I'm on Keras 2.2.2 and I'm trying to generate augmentations of my training data with zca_whitening and an ImageDataGenerator. But when I try to fit the generator (which is mandatory when using zca_whitening) the python process eats more and more memory (100Gb+) until it gets killed by the system. This small example can cause the leak: import numpy as np from keras.preprocessing.image import ImageDataGenerator def cause_leak(): idg = ImageDataGenerator(zca_whitening = True) random_sample = np.random.random((1, 250, 250, 3)) idg.fit(random_sample) cause_leak() Update: Yesterday this was marked as a bug in the Keras repository.
has comment: http://stackoverflow.com/comment/91499370
type: Question
has title: Keras ImageDataGenerator Fit causes memory leak
has comment: http://stackoverflow.com/comment/91288641
answer count: 1
has comment: http://stackoverflow.com/comment/91283343
has comment: http://stackoverflow.com/comment/91288778
tagged with: keras
has answer: http://stackoverflow.com/a/57516511
favorite count: 0
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/52143172
answer count: 0
has comment: http://stackoverflow.com/comment/104747170
has title: tf.data.dataset from avro files
has body: I'm trying to parallelize my input pipeline using tf.data.Dataset and TFRecordDataset. files = tf.data.Dataset.list_files("./data/*.avro") dataset = tf.data.TFRecordDataset(files, num_parallel_reads=16) dataset = dataset.apply(tf.contrib.data.map_and_batch( preprocess_fn, 512, num_parallel_batches=16) ) I'm not sure how to write preprocess_fn if the input is an AVRO file (which is like JSON). Currently, I am using tf.data.Dataset.from_generator and feeding it avro records parsed by pyavroc or similar avro readers. But I'm not sure how to parallelize this as from_generator method does not have num_parallel_reads option available. def gen(): for file in all_avro_files: x, y = read_local_avro_data(file) for i, sample in enumerate( x ): yield sample, y[i] dataset = tf.data.Dataset.from_generator( gen, (tf.float32, tf.float64), ( tf.TensorShape([13000]), tf.TensorShape([]) ) ) Reading file by file is clearly a bottleneck and I see all cores waiting for data after exhausting the data from previous batch. How to optimize either of the approaches?
type: UnansweredQuestion
tagged with: tensorflow
linked to: http://stackoverflow.com/q/52179857
type: Question
tagged with: tfrecord
tagged with: keras
score: 4
has comment: http://stackoverflow.com/comment/104745121
tagged with: tensorflow-datasets
favorite count: 0
has comment: http://stackoverflow.com/comment/104710679
tagged with: python
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/91388051
score: 0
has text: "does not parse that" - you have to find out why that is, and I think Jieter has a good find in his answer. Not getting an error message could mean: the template engine decides to just ignore the variable values - without throwing an error. Which would (imho) indicate that it's not just a parsing problem.
type: QuestionComment
comment on: http://stackoverflow.com/q/52197487
type: Comment

http://stackoverflow.com/comment/91300003
type: Comment
score: 2
comment on: http://stackoverflow.com/a/52173996
type: AnswerComment
has text: so I tried this statement: if message.attachments[0]['url']: good thing is that the program works and it detects that an image has been sent and replies with the message that I want. But it throws up this error: line 67, in on_message if message.attachments[0]['url']: IndexError: list index out of range

http://stackoverflow.com/a/52264058
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52263978
has body: Can you share your format from the text file? It's important for the sake of how to filter through the code. I found this snippet at this link: Read line by line a large text file and search for a string. I believe it will accomplish what you want so much as the format of your file works. using (StreamReader streamReader = new StreamReader(this.MyPath)) { while (streamReader.Peek() &gt; 0) { string line = streamReader.ReadLine(); if (line.Contains(Resources.Constants.SpecificString) { // Do some action with the string. } } }
has comment: http://stackoverflow.com/comment/91476638

http://stackoverflow.com/q/52211219
favorite count: 0
has comment: http://stackoverflow.com/comment/91372053
type: Question
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/52211857
has answer: http://stackoverflow.com/a/52211318
answer count: 3
upvote count: 1
tagged with: python
has body: I am trying to plot two columns from two different dataframes in one graph. I have figured out the code to plot it in one but the x axis needs to be in ascending order. Can we do that in this case? df1=pd.DataFrame({ 'ID': ['A1','A2','A6','A7','A9'], 'F1_S': [23,75,42,77,54] }, columns=['ID', 'F1_S']) df2=pd.DataFrame({ 'ID': ['A3','A4','A5','A8'], 'F1_S': [66,43,56,86] }, columns=['ID', 'F1_S']) x1 = list(df1['ID']) y1= list(df1['F1_S']) lists1 = sorted(zip(*[x, y1])) x1, y1 = zip(*sorted(zip(x1, y1))) x2 = list(df2['ID']) y2= list(df2['F1_S']) lists2 = sorted(zip(*[x2, y2])) x2, y2 = zip(*sorted(zip(x2, y2))) plt.plot (x1,y1) plt.plot(x2,y2)
possible better answer: http://stackoverflow.com/a/52211892
tagged with: matplotlib
has answer: http://stackoverflow.com/a/52211892
has title: Can we sort the x axis in a Python plot after plotting it?
accepted answer: http://stackoverflow.com/a/52211857
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/a/52218377
downvote count: 0
score: 1
has body: The magic square problem is NP-hard so it will be time-consuming to find a solution for N>=4. The problem can be formulated as a CSP (constraint satisfaction problem) and with constraint package we can try to solve it for a general N like the following, you may try to see if this approach is faster: N = 4 #5 # number of rows / columns n = N**2 # number of cells s = n*(n+1)//6 # sum of each row from constraint import * p = Problem() p.addVariables(range(n), range(1, n+1)) p.addConstraint(AllDifferentConstraint(), range(n)) p.addConstraint(ExactSumConstraint(s), [k*(N+1) for k in range(N)]) p.addConstraint(ExactSumConstraint(s), [(k+1)*(N-1) for k in range(N)]) for row in range(N): p.addConstraint(ExactSumConstraint(s), [row*N+i for i in range(N)]) for col in range(N): p.addConstraint(ExactSumConstraint(s), [col+N*i for i in range(N)]) sols = p.getSolutions() for s in sols: for row in range(N): for col in range(N): print s[row*N+col], print print For N=3 it is very fast and immediately prints all possible solutions: 6 7 2 1 5 9 8 3 4 6 1 8 7 5 3 2 9 4 8 1 6 3 5 7 4 9 2 8 3 4 1 5 9 6 7 2 4 3 8 9 5 1 2 7 6 4 9 2 3 5 7 8 1 6 2 7 6 9 5 1 4 3 8 2 9 4 7 5 3 6 1 8
has comment: http://stackoverflow.com/comment/91385816
upvote count: 1
answers question: http://stackoverflow.com/q/52216696
type: Answer

http://stackoverflow.com/comment/91232217
has text: @I'-'I Perfect!!!
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52141113

http://stackoverflow.com/a/52237015
type: Answer
answers question: http://stackoverflow.com/q/52235173
has body: Both Bear Brown and Sunitha fail to mention that the loading they propose to do can be unsafe. For PyYAML this is clearly indicated at the start of the tutorial: Warning: It is not safe to call yaml.load with any data received from an untrusted source! yaml.load is as powerful as pickle.load and so may call any Python function Pickle has a similar warning: Warning The pickle module is not secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source At least using YAML, it is not necessary to run any risks now or in the future. First do: pip install ruamel.yaml Then: from ruamel.yaml import YAML class Dog: # yaml_tag = u'!Doggie' def __init__(self, name): self.name = name def bark(self): print('BARK') b = '' a = Dog('Test') yaml = YAML(typ='safe') yaml.register_class(Dog) with open('Dog.yaml','w') as ofp: yaml.dump(a, ofp) with open('Dog.yaml') as ifp: b = yaml.load(ifp) print(b.name, b) b.bark() print('==========') with open('Dog.yaml') as ifp: print(ifp.read(), end='') which gives: Test &lt;__main__.Dog object at 0x7f88a5479320&gt; BARK ========== !Dog {name: Test} Notes: The "official" FAQ on yaml.org asks to use .yaml as the file extension for files containing YAML. You can uncomment the "yaml_tag =" line, to use a different tag in YAML document than the default (i.e. your class name) Not only is this safe, it also doesn't have __main__ in the YAML file, which is essential if you ever decide to move the class definition to a different file. Although not as fast as using pickle, the above is much (~10x) faster than the solution Bear Brown proposes. That might be relevant if you have 101 Dalmatians to dump and load. It is not noticeable in your example data, but the above loads/dumps YAML according to the YAML 1.2 specification (published 2009) and also supports the long outdated YAML 1.1 specification. PyYAML has never been updated and still only supports YAML 1.1. (Disclaimer: I am the author o…
score: 0

http://stackoverflow.com/a/52218853
has body: Let's explain you step by step: you should first get the 6th element of the list meta_list through meta_list[5] (because the 6th element has the index 5, indexing starting from 0 in Python): you get a dictionary then you should get the value associated with the key 'name' in this dictionary, through meta_list[5]['name'] and you're done ! The solution is: print(meta_list[5]['name']) # Zhangjiagang ATP Challenger Regarding your original code that doesn't work, the statement for i in meta_list iterates over each element of meta_list, so over each dictionary. When you do event_name = i['name'][6], you try to get the 7th character of the value associated with the name key, which raises an error because 'Tennis' (in the first dictionary) is shorter than 7 characters. The error IndexError: string index out of range is quite clear.
score: 1
answers question: http://stackoverflow.com/q/52218717
downvote count: 0
type: Answer
upvote count: 1

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

http://stackoverflow.com/comment/91365017
has text: Please check your formatting and, if is possible, share your `df ` as `df.to_dict()` so the problem it's easier to reproduce.
comment on: http://stackoverflow.com/q/52207582
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91214819
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52131343
score: 0
has text: https://serverfault.com/questions/178469/set-puttys-window-title-to-name-of-loaded-session , the 1st in Google on "putty window title".

http://stackoverflow.com/comment/91260075
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52154924
type: AnswerComment
has text: As you can see, I already formatted it, just didn't pass it to format function. The real problem isn't formatting it, it is avoiding the SQL Injections. If I just format it, a user might use " in his data, which would give an error and makes SQL Injections possible.

http://stackoverflow.com/q/52180653
type: UnansweredQuestion
has title: RegEx with Python.
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91347905
has comment: http://stackoverflow.com/comment/91312714
has body: I have the following code in Python: import sys, os, requests, datetime, time from bs4 import BeautifulSoup import urllib.request import re import json def get_html(url): headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'} r = requests.get(url, headers=headers) return r.content link = 'https://www.clubx.com.au/products/womanizer-pro?variant=37834367948' soup = BeautifulSoup(get_html(link), 'html.parser') obj = soup.find_all('script')[18] m = re.search(r"\"variants\":\[(.*?)\]", obj.string) if m: data = json.loads(m.group(1)) print(data) The print result is: json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 495 (char 494) If i print obj.string, i get the result: var BOLD = BOLD || {}; BOLD.products = BOLD.products || {}; BOLD.variant_lookup = BOLD.variant_lookup || {};BOLD.variant_lookup[37834367948] ="womanizer-pro";BOLD.variant_lookup[37834368076] ="womanizer-pro";BOLD.variant_lookup[37834368140] ="womanizer-pro";BOLD.variant_lookup[37834368204] ="womanizer-pro";BOLD.variant_lookup[37834368268] ="womanizer-pro";BOLD.products["womanizer-pro"] ={"id":10346996748,"title":"Womanizer Pro","handle":"womanizer-pro","description":"\u003cdiv style=\"text-align: center;\"\u003e\u003cstrong\u003eThis is a web only offer and excludes all retail stores. \u003c/strong\u003e\u003c/div\u003e\n\u003cdiv style=\"text-align: center;\"\u003e\u003cstrong\u003eLimited Time Only\u003c/strong\u003e\u003c/div\u003e\n\u003cp\u003e \u003c/p\u003e\n\u003cdiv style=\"text-align: center;\"\u003e\u003cstrong\u003e\u003c/strong\u003e\u003c/div\u003e\n\u003cp\u003eThe world's most advanced clitoral stimulator - The Womanizer® is in the big world surely only a small novelty in the world of sex toys and erotic products the Womanizer® is a real revolution.\u003c/p\u003e\n\u003cp\u003eThe revolutionary Womanizer® technology makes it possible to stimulate the clitoris without contact for the…
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91312924
score: 0
tagged with: regex
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/91311567

http://stackoverflow.com/q/52190140
has body: I have two lists with data: COURSES = [C1, C2, C3] ROOMS = [R1, R2, R3] and I already created a list of tuples containing their cartesian product: L_CR = list(itertools.product(COURSES, ROOMS)) #print(L_CR): [('C1', 'R1'), ('C1', 'R2'), ('C1', 'R3'), ('C2', 'R1')..... Now I have created two dictionaries storing integer values about the amount of people attending a course and the maximum amount of people fitting into a room: dic_courses = {'C1': 10, 'C2': 5, 'C3': 20} dic_rooms = {'R1': 5, 'R2': 10, 'R3': 20} What I can't figure out is how I can create a dictionary which has the tuples as keys and the absolut difference between the maximum amount of people possible for a room and the number of people attending a course. What I did so far was creating a dictionary which stores each tuple as a key and where each key gets assigned a value of 1: Dic_Courses_Room_Capacity = {} for Element in L_CR: Dic_Courses_Room_Capacity_Temp = {Element: 1} Dic_Courses_Room_Capacity.update(Dic_Students_Room_Capacity_Temp) Which results in: #print(Dic_Courses_Room_Capacity): {('C1', 'R1'): 1, ('C1', 'R2'): 1, ('C1', 'R3'): 1... But what I am looking for would be: #print(Dic_Courses_Room_Capacity): {('C1', 'R1'): 5 , ('C1', 'R2'): 0, ('C1', 'R3'): 10 where e.g.: ('C1', 'R3'): 10 = abs('C1' -'R3') = abs(10-20) = abs(-10) = 10 So I have to update my existing dictionary (Dic_Courses_Room_Capacity) with all calculated combinations of the other two dictionaries. I tried to loop through those two dictionaries with two for loops but that resulted in always getting the same number for each key(=tuple). Any ideas?
has answer: http://stackoverflow.com/a/52190261
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91330388
tagged with: cartesian-product
tagged with: python
tagged with: dictionary
score: 2
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/52190261
has title: Cartesian Product of Dictionary Keys and Values Python
upvote count: 3

http://stackoverflow.com/q/52175351
tagged with: loops
type: Question
answer count: 1
has body: Struggling with doing this and was wondering if someone can help. I have a code that generates a large list of 300 items. I want to write this to a csv file using pandas but write different sub lists to different rows. for example Take items 0-7 and write to one row, then 1-8, 2-9 and so on until 293-300. currently what i have being doing is this and manually changing the selection in df.iloc[:,2:9] but i was hoping there would be a way to automate this with a loop. This is what i have as an example so far. sncomo is just a package to generate data. its output is what I want to split up and save to a csv file. import sncosmo import pandas as pd days_apart = list(range(55, 300)) model = sncosmo.Model(source="hsiao") model.set(z=1.5, t0=100) y = model.bandmag('desr', 'ab', days_apart) df = pd.DataFrame([y]) df1 = df.iloc[:,2:9] with open("test_data.csv", "a") as f: df1.to_csv(f, header=False) Hope someone can help thanks!
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/52175482
accepted answer: http://stackoverflow.com/a/52175482
tagged with: python
has title: iterating over long list to generate smaller lists and append to csv
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/91186496
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52117628
score: 1
has text: Take a look at this other answer: https://stackoverflow.com/questions/600536/why-does-google-search-return-http-error-403

http://stackoverflow.com/comment/114593798
type: Comment
type: QuestionComment
has text: Hi @JamesAndrewBush, I didn't find a direct connection with Python to HFM (OLAP Cube), but as a shortcut, I created a visual basic script Excel Macro that runs all the steps like connection, refresh, and save the file then from then I manipulated using Python Pandas. The ESSBASEPY works if you have replicated the ESSBASE database as the HFM, not my case.
score: 0
comment on: http://stackoverflow.com/q/52117172

http://stackoverflow.com/a/52131825
answers question: http://stackoverflow.com/q/52131774
has body: names = ['ed', 'edd', 'eddy'] found = False end = False while(end != True): user_input = input('enter name... ') for name in names: if name == user_input: found = True if found: print('yep! the name {} is available'.format(name)) else: print('hold up! wait a minute! no name found!') again = input('continue? [y/n] ? ') if again == 'n': end = True else: found = False
type: Answer
has comment: http://stackoverflow.com/comment/91214693
has comment: http://stackoverflow.com/comment/91223625
has comment: http://stackoverflow.com/comment/91214197
score: 0
has comment: http://stackoverflow.com/comment/91225798

http://stackoverflow.com/q/52160366
has answer: http://stackoverflow.com/a/52183412
has comment: http://stackoverflow.com/comment/91291943
has comment: http://stackoverflow.com/comment/91270418
has title: Is there any way for console programs to change their execution way, due to some event, like e.g. key press or some event in code?
tagged with: python-multithreading
has comment: http://stackoverflow.com/comment/91272296
accepted answer: http://stackoverflow.com/a/52183412
tagged with: multithreading
has body: All programs which I see in tutorials are console and code is executed from first line to the last line and if there is while everything starts from the first line. Is there any way for console programs to change their execution way, due to some event, like e.g. key press or some event in code? The best example of what I want to do is router CLI. Where can I find such examples? def main(): while(True): initial_setup() #choose IPs to monitor while(True): do_some_work() # do monitor the IPs I need some listener in the secons while which detects keypresses and then I go to initial setup, meanwhile do_some_work works and only after I finish adittional changes in initial_setup do_some_work restarts. Sorry I am noob and not very good in explaining probaly because English is not native for me. The best example from real life I can name is CLI of router, you can setup intreface and meanwhile router do routing in the background. Code for Sergio S: import threading import time def hello(): while(True): print("Hello") time.sleep(2) def hi(): while(True): print("hi") time.sleep(2) def press_key(): a=input() a=False return a def circle(): MrBoolean=True while(MrBoolean): thr=[] thr.append(threading.Thread(target=hello)) thr.append(threading.Thread(target=hi)) thr.append(threading.Thread(target=press_key)) for i in thr: i.start() for i in thr: i.join() mrBoolean=thr[3] def main(): while(True): circle() main()
linked to: http://stackoverflow.com/q/2846653
tagged with: python
type: AnsweredQuestion
tagged with: algorithm
has comment: http://stackoverflow.com/comment/91287465
type: Question
linked to: http://stackoverflow.com/q/18018033
answer count: 2
has comment: http://stackoverflow.com/comment/91291767
has answer: http://stackoverflow.com/a/52165992
tagged with: workflow
score: 0
has comment: http://stackoverflow.com/comment/91270528
possible better answer: http://stackoverflow.com/a/52165992

masking
tag name: masking
tags question: http://stackoverflow.com/q/52193464
type: Tag

http://stackoverflow.com/a/52206169
upvote count: 1
has comment: http://stackoverflow.com/comment/91362282
downvote count: 0
has comment: http://stackoverflow.com/comment/91362425
type: Answer
accepted answer of: http://stackoverflow.com/q/52206075
has body: Change your loop to this: for name,df in m.items(): for index, row in df.iterrows(): if df.at[index,'B']&lt;0: df.drop(index,axis=0, inplace=True)
score: 1
answers question: http://stackoverflow.com/q/52206075
type: AcceptedAnswer

http://stackoverflow.com/comment/91418789
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52234634
score: 0
has text: Unfortunately, you are using JPEG format to save your images and losing quality which you were already lacking at the start... Are you using a Raspberry Pi? Can you acquire at higher quality setting or as raw RGB? Can you save intermediate results of your processing as PNG or NetPBM PPM files? Try installing **ImageMagick** and separating out the Hue, Saturation and Lightness and look at the Hue image (`chan-0.png`) and you will see what I mean `magick AdjustedNewMaze3.jpg -colorspace hsl -separate chan-%d.png`

http://stackoverflow.com/comment/91244248
has text: @confk: well like the HTTP specs say: https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html "*GET and HEAD methods SHOULD NOT have the significance of taking an action other than retrieval.*". By doing so, you do not follow the specifications, and this can result in for example search engines "triggering" deletion of parts of your database.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52115337

http://stackoverflow.com/q/52176249
downvote count: 0
tagged with: zope
favorite count: 0
answer count: 3
score: 5
tagged with: python
tagged with: plone
has answer: http://stackoverflow.com/a/52184721
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91451097
tagged with: sandbox
type: Question
has body: I'm running the following code using RestrictedPython (using safeglobals['_print_'] = PrintCollector and compile_restricted_exec/exec(compiled_code, safe_globals, locals)). def foo(): print 'bar' print '123' foo() After the code executed, I can obtain the print output via locals.pop('_print') which holds an instance of PrintCollector, but only for the print '123' statement that is outside of the function. When debugging this, I see two instances of PrintCollector being created, presumably for the two contexts (module level and function) in which the print statement is being used. However, I can't find a way to access the PrintCollector instance that was created when entering def foo(). The documentation for RestrictedPython is quite scant which is why I ask here for any advice on how one could access the function's print output the RestrictedPython-way. Example: from RestrictedPython import compile_restricted from RestrictedPython.PrintCollector import PrintCollector _print_ = PrintCollector code_string = """ def foo(): print 'bar' print '123' foo() """ loc = {'_print_': PrintCollector, '_getattr_': getattr} compiled_code = compile_restricted(code_string, '&lt;string&gt;', 'exec') exec(compiled_code, loc) loc['_print']()
has answer: http://stackoverflow.com/a/55765804
upvote count: 5
has title: RestrictedPython: get print output when printing from within a function
has answer: http://stackoverflow.com/a/76214209
has comment: http://stackoverflow.com/comment/91493992
has comment: http://stackoverflow.com/comment/91386540

http://stackoverflow.com/comment/91302122
score: 0
type: Comment
type: QuestionComment
has text: Look at samples like https://github.com/oracle/python-cx_Oracle/blob/master/samples/PLSQLFunction.py
comment on: http://stackoverflow.com/q/52130262

http://stackoverflow.com/a/52185161
type: Answer
score: 2
downvote count: 0
upvote count: 2
has body: After discussion in the comments, the answer is: df = pd.DataFrame(json.loads(codecs.decode(bytes(r.text, 'utf-8'), 'utf-8-sig'))['data'])
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52183449
answers question: http://stackoverflow.com/q/52183449

http://stackoverflow.com/a/52161467
has comment: http://stackoverflow.com/comment/91273714
has comment: http://stackoverflow.com/comment/91272738
type: Answer
has comment: http://stackoverflow.com/comment/91272489
has comment: http://stackoverflow.com/comment/91272931
accepted answer of: http://stackoverflow.com/q/52160584
score: 0
has comment: http://stackoverflow.com/comment/91272599
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52160584
has body: I would convert your data into Pandas dataframe and use the diff() function. Is this you are looking for? df = pd.DataFrame({'Open': [187.88, 185.14, 186.35, 187.25], 'High': [189.22, 186.33, 187.2, 188.35], 'Low': [187.2, 183.45, 185.73, 184.94]}, index=range(1, 5)) df.index.name = 'ID' spread = df.diff()

http://stackoverflow.com/comment/91189786
type: QuestionComment
has text: Can you post your actual dataframe, as text, not as an image?
type: Comment
comment on: http://stackoverflow.com/q/52119429
score: 0

http://stackoverflow.com/comment/91355033
type: Comment
has text: I have edited the code using p_record.entries() but it gave me an error AttributeError: 'dict' object has no attribute 'entries'
comment on: http://stackoverflow.com/a/52194950
type: AnswerComment
score: 0

http://stackoverflow.com/q/52132465
has comment: http://stackoverflow.com/comment/91215415
has comment: http://stackoverflow.com/comment/91215450
tagged with: python
has body: I have an array of list containing lemmatized words. When I print many of them at once, this is the output: print(data[:3]) [list(['@', 'switchfoot', 'http', ':', '//twitpic.com/2y1zl', '-', 'Awww', ',', 'that', "'s", 'a', 'bummer', '.', 'You', 'shoulda', 'got', 'David', 'Carr', 'of', 'Third', 'Day', 'to', 'do', 'it', '.', ';', 'D']) list(['is', 'upset', 'that', 'he', 'ca', "n't", 'update', 'his', 'Facebook', 'by', 'texting', 'it', '...', 'and', 'might', 'cry', 'a', 'a', 'result', 'School', 'today', 'also', '.', 'Blah', '!']) list(['@', 'Kenichan', 'I', 'dived', 'many', 'time', 'for', 'the', 'ball', '.', 'Managed', 'to', 'save', '50', '%', 'The', 'rest', 'go', 'out', 'of', 'bound'])] I tried many thing to get rid of it but it never does, but when I tried: a = [[i for i in range(5)] for _ in range(5)] print(np.array(a)) the output is not with list() around every list: array([[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]) does it mean they are different lists? Does it just happen with list of string? How can I get rid of it, if it is necessary of course, thanks for your time.
has comment: http://stackoverflow.com/comment/91215948
has answer: http://stackoverflow.com/a/52132600
tagged with: list
has title: numpy prints list() around each list
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52133168
has comment: http://stackoverflow.com/comment/91215424
has comment: http://stackoverflow.com/comment/91215390
score: 0
answer count: 2
tagged with: printing
type: UnansweredQuestion

http://stackoverflow.com/comment/91328657
comment on: http://stackoverflow.com/a/52189233
type: AnswerComment
type: Comment
has text: then just do not use it :-) `pd.get_dummies(pd.DataFrame(test.values.tolist()),prefix_sep ='',prefix='').sum(level=0, axis = 1) `
score: 3

http://stackoverflow.com/comment/91472141
score: 0
type: Comment
has text: I just tested your code to see what is going on, and I think I now understand your issue. It lies within the redirect url_for statement. You try to pass arguments to be used inside the template, but instead it shows them in the url (and not in the template). As far as I know, this is not possible. url_for expects url arguments, it is not possible to use them in a template. As a solution you could use a render_template or use session to store any request.form post data.
type: QuestionComment
comment on: http://stackoverflow.com/q/52241131

http://stackoverflow.com/comment/91308674
score: 1
type: QuestionComment
has text: Possible duplicate of [Python reverse / invert a mapping](https://stackoverflow.com/questions/483666/python-reverse-invert-a-mapping)
comment on: http://stackoverflow.com/q/52179239
type: Comment

http://stackoverflow.com/q/52135513
has body: I have two dataframes of the same shape and am trying to find all the rows in df A where every value is greater than the corresponding row in df B. Mini-example: df_A = pd.DataFrame({'one':[20,7,2],'two':[11,9,1]}) df_B = pd.DataFrame({'one':[1,8,12],'two':[10,5,3]}) I'd like to return only row 0. one two 0 20 11 I realise that df_A &gt; df_B gets me most of the way, but I just can't figure out how to return only those rows where everything is True. (I tried merging the two, but that didn't seem to make it simpler.)
possible better answer: http://stackoverflow.com/a/52135563
answer count: 4
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52135638
has answer: http://stackoverflow.com/a/52135576
type: Question
has title: Find greater row between two dataframes of same shape
tagged with: python
has comment: http://stackoverflow.com/comment/91221720
score: 0
has answer: http://stackoverflow.com/a/52135563
accepted answer: http://stackoverflow.com/a/52135638
has answer: http://stackoverflow.com/a/52136531
has comment: http://stackoverflow.com/comment/91220943

http://stackoverflow.com/comment/91386373
has text: Please post code as an edit to the question, properly formatted.
comment on: http://stackoverflow.com/q/52218791
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91186203
score: 0
comment on: http://stackoverflow.com/q/52113440
type: Comment
has text: So you only have X, Y and Z letters or you can have the whole alphabet or any kind of strings?
type: QuestionComment

http://stackoverflow.com/comment/91281643
score: 1
comment on: http://stackoverflow.com/q/52166034
type: Comment
type: QuestionComment
has text: semicolons... in python... good lord. In all seriousness your code is very hard to follow. You don't follow the style conventions and you don't use very descriptive variable names. `l` is a classic example of the worst variable name you can use. Use something like `found_set`

http://stackoverflow.com/comment/91463169
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52257555
has text: @Chris, it is for `127.0.0.1`.... not sure why this is not trusted... or maybe there is a setting?

http://stackoverflow.com/a/52187536
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91328399
answers question: http://stackoverflow.com/q/52186716
type: Answer
accepted answer of: http://stackoverflow.com/q/52186716
has body: The expected type for hypothesis is list(str), from documentation: :type hypothesis: list(str) candidate is a list(list(str)), you can compute the bleu_score like this: from nltk.translate.bleu_score import sentence_bleu references = [['two', 'passenger', 'planes', 'on', 'a', 'grassy', 'plain'], ['An', 'airplane', 'sitting', 'on', 'the', 'tarmac', 'at', 'an', 'airport', 'with', 'another', 'plane', 'in', 'the', 'background', '.'], ['A', 'white', 'an', 'blue', 'airplane', 'parked', 'at', 'the', 'airport', 'near', 'another', 'small', 'plane', '.'], ['Blue', 'and', 'white', 'airplane', 'parked', '.'], ['two', 'airplanes', 'are', 'waiting', 'on', 'the', 'tarmac'], ['Two', 'airplanes', 'parked', 'at', 'the', 'airport', '.'], ['A', 'passenger', 'aircraft', 'with', 'landing', 'gear', 'down', '.'], ['A', 'passenger', 'jet', 'flies', 'through', 'the', 'air', '.'], ['A', 'passenger', 'plane', 'fly', 'through', 'the', 'sky', '.'], ['The', 'Austrian', 'plane', 'soars', 'in', 'the', 'sky', '.']] candidates = [ ['An', 'airplane', 'sitting', 'on', 'the', 'tarmac', 'at', 'an', 'airport', 'with', 'another', 'plane', 'in', 'the', 'background', '.'], ['A', 'passenger', 'jet', 'flies', 'through', 'the', 'air', '.']] for candidate in candidates: print(sentence_bleu(references, candidate)) Output 1.0 1.0

http://stackoverflow.com/q/52194612
score: 2
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/91339593
has comment: http://stackoverflow.com/comment/91340464
tagged with: python-3.6
tagged with: pandas
has title: Import from pandas.io.json only works when running from python command line
downvote count: 0
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: pip
tagged with: python
has body: I am having an issue when trying to import: from pandas.io.json import json_normalize when running a python program I have made. The same import works when running the code manually from the command line. I am using Windows 10, with Python 3.6.5 installed. Example - working from command line: &gt;&gt;&gt; import pandas &gt;&gt;&gt; from pandas.io.json import json_normalize &gt;&gt;&gt; json_normalize &lt;function json_normalize at 0x08319C90&gt; Example - same code in test.py: Traceback (most recent call last): File "pandas.py", line 3, in &lt;module&gt; import pandas as pd File "C:\Users\Test\test.py", line 4, in &lt;module&gt; from pandas.io.json import json_normalize ModuleNotFoundError: No module named 'pandas.io'; 'pandas' is not a package Any idea what I could check to see if I can resolve this?

http://stackoverflow.com/a/52255706
score: 3
upvote count: 3
has body: Just using split() will split at any whitespace characters (tabs, or multiple spaces). So line = raw_input() args = line.split() Then, because namedtuple accepts multiple arguments, not a list, you just have to unwrap the argument list, using the * operator. person = Person(*args)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91459760
answers question: http://stackoverflow.com/q/52255550
accepted answer of: http://stackoverflow.com/q/52255550
type: Answer
has comment: http://stackoverflow.com/comment/91459808
downvote count: 0

http://stackoverflow.com/comment/91244792
comment on: http://stackoverflow.com/q/52147403
score: 0
type: Comment
type: QuestionComment
has text: For that, you will need a list of primes.

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

http://stackoverflow.com/a/52234206
score: 43
answers question: http://stackoverflow.com/q/52232979
type: Answer
has comment: http://stackoverflow.com/comment/98770825
has body: I usually have this kind of pattern when working with sqlalchemy: session = get_the_session_one_way_or_another() try: # do something with the session except: # * see comment below session.rollback() raise else: session.commit() To make things easier to use, it is useful to have this as a context manager: @contextmanager def get_session(): session = get_the_session_one_way_or_another() try: yield session except: session.rollback() raise else: session.commit() And then: with get_session() as session: # do something with the session If an exception is raised within the block, the transaction will be rolled back by the context manager. *There is an empty except: which catches literally everything. That is usually not what you want, but here the exception is always re-raised, so it's fine.
has comment: http://stackoverflow.com/comment/132626826
has comment: http://stackoverflow.com/comment/98720584
has comment: http://stackoverflow.com/comment/119544386
has comment: http://stackoverflow.com/comment/132605285
upvote count: 43
has comment: http://stackoverflow.com/comment/91433717
downvote count: 0
has comment: http://stackoverflow.com/comment/98783565
has comment: http://stackoverflow.com/comment/91421834

http://stackoverflow.com/a/52177525
type: Answer
accepted answer of: http://stackoverflow.com/q/52177460
score: 0
has comment: http://stackoverflow.com/comment/91316168
type: AcceptedAnswer
has body: I reviewed the page and it seems the "get routes" button has an id associated to it. You can simply use that So the last line in your code should be: driver.find_element_by_id("get_d").click() You can use other selectors as well: xpath: //a[text()='Get routes'] css: #get_d When writing your test scripts, you can always validate selectors in the browser before including them in your test script. Below are a few simple approaches I follow to validate selectors: When using 'id', simply use the following javascript in your browser console: document.getElementById("get_d"). This should return an element in the browser console if the id you are using is valid. When using 'xpath', use the following line: $x("//a[text()='Get routes']") in the browser console. This will also return all elements associated with the xpath you mention When using 'css selector', use the following line: $$("#get_d"). Similar to xpath approach, this will return all elements associated with the css selector you mention
has comment: http://stackoverflow.com/comment/91319266
answers question: http://stackoverflow.com/q/52177460
has comment: http://stackoverflow.com/comment/91316848

http://stackoverflow.com/comment/91269697
comment on: http://stackoverflow.com/q/52158331
has text: If you are replacing each element of a list, it might be faster and simpler to use a list comprehension.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/52255263
score: 2
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/52248614
answers question: http://stackoverflow.com/q/52248614
has body: AWS Lambda limits the maximum execution time of a single invocation to 5 minutes. You can write Lambda functions that perform long-running tasks as recursive functions. context.get_remaining_time_in_millis() When your function is invoked, the context object allows you to find out how much time is left in the current invocation. To minimise the no. of recursions, our function would: Limit the size of the part, use small batch. At the end of each batch, call context.getRemainingTimeInMillis() to check how much time is left in this invocation If there is more than 1 min left in the invocation then process another batch; otherwise recurse Sample links: Recursive Lambda Function Recursive Lambda the right way

http://stackoverflow.com/a/52241128
answers question: http://stackoverflow.com/q/52241109
has body: Each time getType() is called (even inside itself) a new local variable type is created whose content is lost if it isn't returned to the calling function. The content of type in the calling getType() isn't modified.
score: 0
type: Answer

http://stackoverflow.com/q/52133511
answer count: 1
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91221894
has body: I have push a python-django project to heroku and it works well. In my view.py file of django model, I added function that could connect to the local mysql database to retrieve data from the mysql. The function is the view.py is as followed: @login_required def results(request): data=[] data1 = [] owner = request.user owner = str(owner) db = MySQLdb.connect(user='root', db='aaa', passwd='xxxxx', host='localhost') cursor = db.cursor() cursor.execute("SELECT search_content, id, title, author, institute, FROM result_split where username = '%s'" % (owner)) data = cursor.fetchall() db.close() return render(request, "webdevelop/results.html", {"datas": data}) But when I try to open the page that show the data from mysql database in the deployed heroku website, it show the error:"OperationalError at /results/ (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")". How could I have this heroku project to connect to my local mysql database? Or I should choose alternative?
tagged with: django
has title: heroku connect to mysql database
tagged with: heroku
type: AnsweredQuestion
tagged with: mysql
has answer: http://stackoverflow.com/a/52133552
accepted answer: http://stackoverflow.com/a/52133552
type: Question

http://stackoverflow.com/q/52184724
score: 2
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52185581
type: Question
tagged with: pandas-groupby
has body: I have been trying to get my head around the following problem for some time now. Hope someone can help me out. I try to sum up numbercounts (e.g. births) for different areas. As shown in the table below, I have a dataset wherein, as an example, areas 1 and 2 come toghether in the fused area4. Area3 is unaffected. import pandas as pd data1 = { "OldArea" : ['area1','area2','area3'], "numbercount" : [10,20,5], "FusedIntoArea" : ['area4','area4','area3'] } frame1 = pd.DataFrame(data1, columns=['OldArea', 'FusedIntoArea', 'numbercount']) frame1 I want to add up the numercount for area1 and area2 (10 + 20) into the area 4 (30). The numbercount for area3 stays the same (5). This works by using groupby and sum to get a pd.series series1 as shown below. series1 = frame1.groupby(['FusedIntoArea'])['numbercount'].sum() series1 The problem is that I want to extend this groupby and sum operation for several fusions of areas through several years. The extended fusion data for the areas is shown in frame3. Area1 and area2 fuse to form area4 (just like before) but now there is more: in the year after that area4 and area3 fuse to form area5, whereas area6 stays the same through the years. The fusion data is in a format like the one in frame2 below: data2 = { 'year0' : ['area1', 'area2', 'area3', 'area6'], 'year1' : ['area4', 'area4', 'area3', 'area6'], 'year2' : ['area5', 'area5', 'area5', 'area6'] } frame2 = pd.DataFrame(data2, columns = ['year0', 'year1', 'year2']) frame2 The data for the numbercounts (e.g. births before a fusion or from the moment of a fusion onwards) is in a separate frame now, frame3. data3 = { "area" : ['area1', 'area2','area3', 'area4', 'area5', 'area6'], "numbercount" : [10,20,5,35, 15,25], } frame3 = pd.DataFrame(data3, columns=['area', 'numbercount']) frame3 The result that I am trying to get is the total numbercount (TotalNumber) for the newly formed areas5 (1 + 2 + 3 + 4 + 5 after the fusion) and 6 (unchanged through the years) as shown in frame4. Any h…
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has title: repeated operation in pandas with Groupby and sum
tagged with: python
accepted answer: http://stackoverflow.com/a/52185581

http://stackoverflow.com/comment/91302993
has text: I removed the downvote. I generally consider wrong information to warrant a downvote since the purpose is to be helpful to others. I do try to leave meaningful comments though. Thanks for making the fix.
type: AnswerComment
comment on: http://stackoverflow.com/a/52176231
score: 0
type: Comment

http://stackoverflow.com/comment/91259428
score: 0
comment on: http://stackoverflow.com/q/52154593
type: Comment
type: QuestionComment
has text: Your second example uses an undefined variable `DD`, for one thing.

http://stackoverflow.com/comment/91328801
type: Comment
comment on: http://stackoverflow.com/a/52189511
has text: Thanks chief. I have to wait 9 minutes to set as answer but thanks!
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91345584
has text: Yup, either of the options I outlined above will work for creating users with whatever options you want! Can't give good code samples in these tiny comment fields so feel free to post a new and more specific question if you'd like an answer more geared to what you're trying to do specifically. :)
type: Comment
comment on: http://stackoverflow.com/a/52194032
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91478847
has text: It might be looking clean and shorter but you do realize it will calculate max at each iteration
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52264928
type: Comment

http://stackoverflow.com/comment/91204812
has text: What is "Inotifier"? Is that a third-party tool, library or some code you wrote?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52119326

http://stackoverflow.com/a/52270389
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52270185
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52270185
has comment: http://stackoverflow.com/comment/91569953
has comment: http://stackoverflow.com/comment/91489990
type: Answer
has comment: http://stackoverflow.com/comment/91526205
has comment: http://stackoverflow.com/comment/91490320
has comment: http://stackoverflow.com/comment/92115248
score: 2
downvote count: 0
has body: Don't use loops in pandas, they are slow compared to a vectorized solution - convert boolean mask to integers by astype True, False are converted to 1, 0: dataframe = pd.DataFrame({'A':list('abcdef'), 'B':[4,5,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1,3,5,7,1,0], 'E':list('aaabbb'), 'F':[5,3,6,9,2,4], 'G':[5,3,6,9,2,4] }) a = 5 dataframe['new'] = (dataframe.iloc[:,5] &gt;= a).astype(int) print (dataframe) A B C D E F G new 0 a 4 7 1 a 5 5 1 1 b 5 8 3 a 3 3 0 2 c 4 9 5 a 6 6 1 3 d 5 4 7 b 9 9 1 4 e 5 2 1 b 2 2 0 5 f 4 3 0 b 4 4 0 If you want to overwrite the 7th column: a = 5 dataframe.iloc[:,6] = (dataframe.iloc[:,5] &gt;= a).astype(int) print (dataframe) A B C D E F G 0 a 4 7 1 a 5 1 1 b 5 8 3 a 3 0 2 c 4 9 5 a 6 1 3 d 5 4 7 b 9 1 4 e 5 2 1 b 2 0 5 f 4 3 0 b 4 0
has comment: http://stackoverflow.com/comment/91490178
has comment: http://stackoverflow.com/comment/91490257
has comment: http://stackoverflow.com/comment/91526153
has comment: http://stackoverflow.com/comment/91490403
has comment: http://stackoverflow.com/comment/91568873
has comment: http://stackoverflow.com/comment/91490383

http://stackoverflow.com/a/52181579
type: Answer
answers question: http://stackoverflow.com/q/52181407
score: 0
has body: Using count and index: lst = ['new york', 'school', 'new'] text = 'i am going to a school in new york and therefore i have to buy a new uniform to go to new york' for x in lst: print(f"{x} = {text.count(' ', 0, text.index(x))}") # new york = 7 # school = 5 # new = 7 count counts whitespaces in text from start till you meet the first appearance of phrase which is same as the number of words preceding that phrase.

http://stackoverflow.com/comment/91453160
type: QuestionComment
has text: I'm using Python 2.7.5
score: 0
comment on: http://stackoverflow.com/q/52239271
type: Comment

http://stackoverflow.com/a/52246021
has comment: http://stackoverflow.com/comment/91440573
type: Answer
has comment: http://stackoverflow.com/comment/91440668
accepted answer of: http://stackoverflow.com/q/52245035
score: 1
upvote count: 1
has body: Try to update alphabetical_links with its own Threads: import requests import threading from lxml import html main_url = "https://www.houzz.com/proListings/letter/{}" def alphabetical_links(mainurl): response = requests.get(mainurl).text tree = html.fromstring(response) links_on_page = [container.attrib['href'] for container in tree.cssselect(".proSitemapLink a")] threads = [] for link in links_on_page: thread = threading.Thread(target=sub_links, args=(link,)) thread.start() threads.append(thread) for thread in threads: thread.join() def sub_links(process_links): response = requests.get(process_links).text root = html.fromstring(response) for container in root.cssselect(".proListing"): try: name = container.cssselect("h2 a")[0].text except Exception: name = "" try: phone = container.cssselect(".proListingPhone")[0].text except Exception: phone = "" print(name, phone) if __name__ == '__main__': linklist = [] for link in [main_url.format(chr(page)) for page in range(97,123)]: thread = threading.Thread(target=alphabetical_links, args=(link,)) thread.start() linklist+=[thread] for thread in linklist: thread.join() Note that this is just an example of how to manage "inner Threads". Because of numerous threads that are starting at the same time your system might fail to start some of them due to lack of resources and you will get RuntimeError: can't start new thread exception. In this case you should try to implement ThreadPool
answers question: http://stackoverflow.com/q/52245035
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91400623
score: 1
has text: Actually, we create a new tensor “w”, and it is assigned to “original w - lr*grad”
type: AnswerComment
comment on: http://stackoverflow.com/a/52218977
type: Comment

http://stackoverflow.com/a/52216395
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52213829
answers question: http://stackoverflow.com/q/52213829
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/91401086
has body: I guess the most straightforward way in some languages would be to use the ' format modifier in printf. I Julia this WOULD look like so: using Printf # a stdlib that ships with julia which defines @printf @printf "%'d" 12345678 However, unfortunately, this flag is not yet supported as you can see from the error you'll get: julia&gt; @printf "%'d" 12345678 ERROR: LoadError: printf format flag ' not yet supported If you like this feature, maybe you should think about adding it to the Printf stdlib so that everyone would benefit from it. I don't know how difficult this would be though. UPDATE: Note that although the macro is defined in stdlib Printf, the error above is explicitly thrown in Base/printf.jl:48. I also filed an issue here
score: 3
type: AcceptedAnswer

http://stackoverflow.com/q/52253479
score: 0
answer count: 1
type: UnansweredQuestion
has body: I have 2 inputs (x,y) and 3 classes for that inputs which i mark by different colors. Using scaling I can see how many times does particular class is found at particular (x,y) point. To show points on the chart i use such code: ax.scatter(first_column, second_column, c=outputs_colors, s=labels_mean, alpha=0.3) first_column - x_values; second_column - y_values; c=outputs_colors - colors for different classes; s=labels_mean - class share at a given point When x,y inputs are various floats - the charts are informative: Plot Scatter Image 1 But when x,y are integers and there are many overlaps in classes the chart loses clarity: Plot Scatter Image 2 Is it possible to arrange scatters by size from bigger as background to smaller as foreground without using loop and separate plot.scatter for each class? To get something like this: Plot Scatter Image 3
has title: How to arrange matplotlib scatters one over another by scale
tagged with: python
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91457809
type: Question
has answer: http://stackoverflow.com/a/52254149
tagged with: scatter-plot

http://stackoverflow.com/comment/91375761
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52211993
has text: I only have python 2.7 installed ! and when I run python -3 --version it return python 2.7 and the errorlevel still 0 !!!!

http://stackoverflow.com/q/52253787
score: 3
has comment: http://stackoverflow.com/comment/91455170
has comment: http://stackoverflow.com/comment/91456792
has title: KMeans clustering unbalanced data
upvote count: 4
has answer: http://stackoverflow.com/a/52258663
has comment: http://stackoverflow.com/comment/91455324
tagged with: k-means
tagged with: cluster-analysis
answer count: 1
tagged with: data-science
favorite count: 0
tagged with: feature-engineering
tagged with: python
accepted answer: http://stackoverflow.com/a/52258663
type: AnsweredQuestion
has body: I have a set of data with 50 features (c1, c2, c3 ...), with over 80k rows. Each row contains normalised numerical values (ranging 0-1). It is actually a normalised dummy variable, whereby some rows have only few features, 3-4 (i.e. 0 is assigned if there is no value). Most rows have about 10-20 features. I used KMeans to cluster the data, always resulting in a cluster with a large number of members. Upon analysis, I noticed that rows with fewer than 4 features tends to get clustered together, which is not what I want. Is there anyway balance out the clusters?
downvote count: 1
type: Question

http://stackoverflow.com/comment/91328905
comment on: http://stackoverflow.com/q/52189532
score: 0
type: QuestionComment
type: Comment
has text: Do you _really_ need to create the DataFrame on a loop? If not, you can do something like `dfDaily=data.resample('D').mean()`

http://stackoverflow.com/a/52146423
answers question: http://stackoverflow.com/q/52146051
has comment: http://stackoverflow.com/comment/91242803
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91242836
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/91243012
accepted answer of: http://stackoverflow.com/q/52146051
score: 1
has body: I cannot reproduce your issue, but IMHO you should avoid using exec() in this case. Try below instead: search_method = 'class name' search_word = 'keyword' elem_search_word = driver.find_element(search_method, search_word) elem_search_word.send_keys('python') If you want to search by id, xpath, css... just set search_method with appropriate value Alternatively: from selenium.webdriver.common.by import By search_method = By.CLASS_NAME search_word = 'keyword' elem_search_word = driver.find_element(search_method, search_word) elem_search_word.send_keys('python')
downvote count: 0

http://stackoverflow.com/q/52195887
accepted answer: http://stackoverflow.com/a/52196296
favorite count: 0
tagged with: python-3.x
tagged with: nested-lists
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/91341782
possible better answer: http://stackoverflow.com/a/52196580
type: AnsweredQuestion
has title: Counting "unique pairs" of numbers into a python dictionary?
has answer: http://stackoverflow.com/a/52196580
has comment: http://stackoverflow.com/comment/91360689
has comment: http://stackoverflow.com/comment/91341905
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91341807
tagged with: python-itertools
score: 0
has answer: http://stackoverflow.com/a/52196296
has body: EDIT: Edited typos; the key values of the dictionary should be dictionaries, not sets. I will keep the typos here though, as the questions below address this question. My apologies for the confusion. Here's the problem: Let's say I have a list of integers whereby are never repeats: list1 = [2, 3] In this case, there is a unique pair 2-3 and 3-2, so the dictionary should be: {2:{3: 1}, 3:{2: 1}} That is, there is 1 pair of 2-3 and 1 pair of 3-2. For larger lists, the pairing is the same, e.g. list2 = [2, 3, 4] has the dicitonary {2:{3: 1}, 3:{2: 1}, 3:{4: 1}, 4:{3: 1}, 2:{4: 1}, 4:{2: 1}} (1) Once the size of the lists become far larger, how would one algorithmically find the "unique pairs" in this format using python data structures? (2) I mentioned that the lists cannot have repeat integers, e.g. [2, 2, 3] is impossible, as there are two 2s. However, one may have a list of lists: list3 = [[2, 3], [2, 3, 4]] whereby the dictionary must be {2:{3: 2}, 3:{2: 2}, 3:{4: 1}, 4:{3: 1}, 2:{4: 1}, 4:{2: 1}} as there are two pairs of 2-3 and 3-2. How would one "update" the dictionary given multiple lists within a list? This is an algorithmic problem, and I don't know of the most efficient solution. My idea would be to somehow cache values in a list and enumerate pairs...but that would be so slow. I'm guessing there's something useful from itertools.
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91360698

selenium
tags question: http://stackoverflow.com/q/52207164
tags question: http://stackoverflow.com/q/52141369
tags question: http://stackoverflow.com/q/52239692
tags question: http://stackoverflow.com/q/52134302
tags question: http://stackoverflow.com/q/52244588
tags question: http://stackoverflow.com/q/52132959
tags question: http://stackoverflow.com/q/52141434
tags question: http://stackoverflow.com/q/52239043
tags question: http://stackoverflow.com/q/52128407
tags question: http://stackoverflow.com/q/52126812
tags question: http://stackoverflow.com/q/52255483
tags question: http://stackoverflow.com/q/52216976
tags question: http://stackoverflow.com/q/52153076
tags question: http://stackoverflow.com/q/52225496
tags question: http://stackoverflow.com/q/52122424
tags question: http://stackoverflow.com/q/52191290
tags question: http://stackoverflow.com/q/52191015
tags question: http://stackoverflow.com/q/52137157
tags question: http://stackoverflow.com/q/52243362
tags question: http://stackoverflow.com/q/52225661
tags question: http://stackoverflow.com/q/52144292
tags question: http://stackoverflow.com/q/52232476
tags question: http://stackoverflow.com/q/52121094
tags question: http://stackoverflow.com/q/52230128
tags question: http://stackoverflow.com/q/52245604
tags question: http://stackoverflow.com/q/52115190
tags question: http://stackoverflow.com/q/52229912
tags question: http://stackoverflow.com/q/52262430
tags question: http://stackoverflow.com/q/52223302
tags question: http://stackoverflow.com/q/52223642
tags question: http://stackoverflow.com/q/52133151
tags question: http://stackoverflow.com/q/52249090
tags question: http://stackoverflow.com/q/52251595
tags question: http://stackoverflow.com/q/52177881
tags question: http://stackoverflow.com/q/52262584
tags question: http://stackoverflow.com/q/52236941
tags question: http://stackoverflow.com/q/52222110
tag name: selenium
tags question: http://stackoverflow.com/q/52216449
tags question: http://stackoverflow.com/q/52150058
tags question: http://stackoverflow.com/q/52242957
tags question: http://stackoverflow.com/q/52194839
tags question: http://stackoverflow.com/q/52211968
tags question: http://stackoverflow.com/q/52120798
tags question: http://stackoverflow.com/q/52184465
tags question: http://stackoverflow.com/q/52113469
tags question: http://stackoverflow.com/q/52161326
tags question: http://stackoverflow.com/q/52137903
tags question: http://stackoverflow.com/q/52188524
tags question: http://stackoverflow.com/q/52137096
tags question: http://stackoverflow.com/q/52155252
tags question: http://stackoverflow.com/q/52147253
tags question: http://stackoverflow.com/q/52251019
tags question: http://stackoverflow.com/q/52168241
tags question: http://stackoverflow.com/q/52130358
tags question: http://stackoverflow.com/q/52257843
tags question: http://stackoverflow.com/q/52124258
tags question: http://stackoverflow.com/q/52170647
tags question: http://stackoverflow.com/q/52122354
tags question: http://stackoverflow.com/q/52242509
tags question: http://stackoverflow.com/q/52125153
tags question: http://stackoverflow.com/q/52263610
tags question: http://stackoverflow.com/q/52231034
tags question: http://stackoverflow.com/q/52209043
tags question: http://stackoverflow.com/q/52143316
tags question: http://stackoverflow.com/q/52238137
tags question: http://stackoverflow.com/q/52238291
tags question: http://stackoverflow.com/q/52156566
tags question: http://stackoverflow.com/q/52162157
tags question: http://stackoverflow.com/q/52126435
tags question: http://stackoverflow.com/q/52187248
tags question: http://stackoverflow.com/q/52211523
tags question: http://stackoverflow.com/q/52207464
tags question: http://stackoverflow.com/q/52159434
tags question: http://stackoverflow.com/q/52128266
tags question: http://stackoverflow.com/q/52233552
tags question: http://stackoverflow.com/q/52146051
tags question: http://stackoverflow.com/q/52190799
tags question: http://stackoverflow.com/q/52118182
tags question: http://stackoverflow.com/q/52142180

http://stackoverflow.com/comment/91382924
has text: which cuda version do you have?
comment on: http://stackoverflow.com/q/52217113
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91199182
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52124008
has text: Not very clear to me what the structure of your data frame is? Is it just one line like the one you pasted? What are the columns name?
score: 0

http://stackoverflow.com/q/52241423
has comment: http://stackoverflow.com/comment/91443568
has answer: http://stackoverflow.com/a/52247849
has title: Data matching based on column and conditions
answer count: 2
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91487997
tagged with: scala
type: UnansweredQuestion
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/91434291
has comment: http://stackoverflow.com/comment/91481581
has answer: http://stackoverflow.com/a/52257441
tagged with: java
downvote count: 3
has body: I have two data sets with millions of Rows. The sample looks like below: Data Set 1: Row col1 col2 col3 1 A 01-01-1991 10 2 B 02-01-1991 20 Data set 2: Row col1 col2 col3 1 A 01-01-1991 -10 2 B 02-01-1991 -10 3 B 01-01-1991 -10 I want to match rows based on col1 , col2 -with tolerance of 1 day and if sum of col3 equal to zero then generate a unique id against the data. So base on the above rule the final result should look like this: Data_set Row col1 col2 col3 Group_Id 1 1 A 01-01-1991 -10 1 2 1 A 01-01-1991 10 1 1 2 B 02-01-1991 20 2 1 2 B 02-01-1991 -10 2 1 3 B 01-01-1991 -10 2 I do not want any any code but ideas. I request you guys to point me towards a good logic to achieve this for a big data set. I am open to use Julia or pyspark or scala. I have tried one logic : To aggregate data base on col1 and col2 and then add col3 from both data set. This covers group id 1 but group 2 does not fall into this.
tagged with: julia
type: Question
tagged with: pyspark
has comment: http://stackoverflow.com/comment/91442515

http://stackoverflow.com/q/52177907
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52177929
has comment: http://stackoverflow.com/comment/91305837
downvote count: 3
type: Question
accepted answer: http://stackoverflow.com/a/52177929
tagged with: discord.py
tagged with: python-3.5
upvote count: 0
answer count: 1
favorite count: 0
has title: Python simplify list items
score: -3
tagged with: python
has body: I am using an API wrapper for AniList called PyMoe. And using this for my Discord Bot. Here is the code I am using: &gt;&gt;&gt; import Pymoe &gt;&gt;&gt; An = Pymoe.Anilist() &gt;&gt;&gt; search = An.search.anime('SNK') &gt;&gt;&gt; ide = search['data']['Page']['media'][0]['id'] &gt;&gt;&gt; id = An.get.anime(ide) &gt;&gt;&gt; genres = id['data']['Media']['genres'] &gt;&gt;&gt; genres ['Action', 'Drama', 'Fantasy'] When i use the code for my Discord bot I am getting that result. But I don't want these ['] stuffs. I want this like Genre 1, Genre 2, Genre 3. I researched a little bit about this but i didn't find anything. So if it is possible (or not) let me know.

http://stackoverflow.com/comment/91267465
type: QuestionComment
score: 1
has text: Try to segment the image using [normalized-cut](http://scikit-image.org/docs/dev/auto_examples/segmentation/plot_ncut.html#sphx-glr-auto-examples-segmentation-plot-ncut-py), then take the labels that overlap the edge map you found with Canny. This way, you can prepare a foreground mask from which you can extract the pixels you are interested in, to calculate the histogram. If you just want to color the background, you can easily do it using the foreground mask.
comment on: http://stackoverflow.com/q/52153979
type: Comment

http://stackoverflow.com/comment/91401887
has text: Does wrapping your `yield` in `start_requests` with a `try/except ValueError` then yielding in the except `yield LinkCheckerItem(index=index['index'], url=url[1], code='invalid')` or similar work?
comment on: http://stackoverflow.com/q/52225956
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91251579
score: 0
type: AnswerComment
type: Comment
has text: Yeah, this is the best answer, i will change happily the mine and i will cite you in it. Thanks for the explanation!
comment on: http://stackoverflow.com/a/52148041

http://stackoverflow.com/q/52152753
score: 1
favorite count: 0
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/41815079
duplicate of: http://stackoverflow.com/q/41815079
upvote count: 1
has body: Currently I have two dataframes. One with a few filled columns including Names and a bunch of empty columns. The other dataframe has all the empty columns of the first filled. I'm trying to populate the empty columns of the first dataframe with the data in the second dataframe only if the dataframes share a cell value. Example: DB: Amount Foil? Name Set .... 3 nan purify the grave innistrad 2 nan slayer of the wicked innistrad 1 nan doomed traveler innistrad 1 nan fiend hunter innistrad DF: eur name rarity tix usd set_name .... 0.21 Ballyrush Banneret common 0.02 0.17 Morningtide 0.34 Battletide Alchemist rare 0.01 0.88 Morningtide 0.05 Burrenton Bombardier common 0.01 0.03 Morningtide 0.03 Burrenton Shield-Bearer common 0.01 0.03 Morningtide 0.21 Cenn's Tactician uncommon 0.01 0.22 Morningtide 0.05 Changeling Sentinel common 0.01 0.08 Morningtide 0.04 Coordinated Barrage common 0.01 0.11 Morningtide 0.06 Daily Regimen uncommon 0.01 0.14 Morningtide Now somewhere in DF there should be a row with a matching name and set cell as in db (db has only the cards I have while df has all the cards from all the sets I have). If so I want to be able to update the row in DB with all the info in DF. How should I go about doing this? The wanted end behavior is DB: Amount Foil? Name Set usd .... 3 nan purify the grave innistrad .5 2 nan slayer of the wicked innistrad .7 1 nan doomed traveler innistrad .9 1 nan fiend hunter innistrad ... What I've tried so far is final_db = pd.concat([db, df.loc[df['name'].isin(db['Name'])]],ignore_index=True,sort=True) where my thinking was that it would concatenate (while ignoring index) DB and a new database with the same length of DB but made up of only rows that DF has. This did not work. I'm unsure what to do from here. As an added bonus I would really like to be able to do this with a semi fuzzy search in case they're misspellings in the name.
tagged with: dataframe
type: UnansweredQuestion
has title: How to Concatenate Dataframes if they share cell values
tagged with: pandas
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/91257379
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52153469
has text: The terminal output is the one I show in the main question. The same for the other commands. Just updated the distrib.

http://stackoverflow.com/comment/91259820
has text: it's working but, is it possible to get the data directly from the first loop?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52154610
type: Comment

http://stackoverflow.com/comment/91184791
has text: See the edit to Bazingaa's answer to set the limits to the nearest integer
comment on: http://stackoverflow.com/a/52116849
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52241144
downvote count: 0
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/52241109
has body: How about something simple as this? Get user input, check if it's in dictionary, return if so else continue in the infinite loop. type_details = {'Plain':1.5, 'Waffle':2, 'Cup':1} def getType(): while True: user_in = input("Enter the preferred Type: ") if user_in in type_details: return user_in user_in = getType() print(f'You entered: {user_in}') print(f'Type Price: {type_details[user_in]}')
score: 2

http://stackoverflow.com/q/52226782
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91403215
tagged with: python
has comment: http://stackoverflow.com/comment/91403238
has body: While this is 100% Python related, it's not quite an issue with Python itself. The module, called "web3", is used to interact with Ethereum and solidity, yet when I try to send small transaction running on local node, I am getting read-timeout from "HTTP pool" or so. The error says something about 10 maximum timeout... so maybe if I find/increase 10 to 50 or 100 it will be fixed? Unfortunately there's limited info online and people having the same issue barely manage to solve it with few fixes.
has answer: http://stackoverflow.com/a/69471506
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91403206
type: Question
tagged with: web3py
has comment: http://stackoverflow.com/comment/91403235
has comment: http://stackoverflow.com/comment/91403211
has comment: http://stackoverflow.com/comment/91408343
has title: Getting "read time out" error while trying to use a Python module
tagged with: ethereum
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91403068
favorite count: 0

http://stackoverflow.com/comment/91274490
comment on: http://stackoverflow.com/q/52146955
has text: @tBuLi I have added the standard deviations. The result is even worse! I will add it in the edited version of the OP.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52209231
answer count: 2
has body: I want to make a kind of "level editor" as an exercise. I've got this code: import pygame running = True pygame.init() screen = pygame.display.set_mode((800, 500)) class Cube: def update(self): self.cx, self.cy = pygame.mouse.get_pos() self.square = pygame.Rect(self.cx, self.cy, 50, 50) def draw(self): pygame.draw.rect(screen, (255, 0, 0), self.square) cube = Cube() drawing_cube = False drawing_cube2 = False while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.MOUSEBUTTONDOWN: cube.update() drawing_cube = True screen.fill((0, 255, 0)) if drawing_cube: cube.draw() pygame.display.flip() pygame.quit() However, it doesn't create multiple squares; it just re-locates the already created square.
has title: Make pygame draw cubes wherever the user clicks
possible better answer: http://stackoverflow.com/a/52236579
has answer: http://stackoverflow.com/a/52236579
tagged with: python
tagged with: pygame
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52209303
type: Question
tagged with: draw
score: 0
accepted answer: http://stackoverflow.com/a/52209303

http://stackoverflow.com/q/52174782
has title: django 2 re_path expression passing email verification token
type: Question
tagged with: django-urls
score: 0
linked to: http://stackoverflow.com/q/6269765
has body: I'm quite stuck with using regular expression in django 2 url. All seems to be correct, however i'm getting 404 error. Actual path: http://localhost:8000/user/activate/b'MjQ'/4zb-89a933fe70e0d12de725/ error: Using the URLconf defined in ec2django.urls, Django tried these URL patterns, in this order: user/ ^user/activate/(?P&lt;uidb64&gt;[0-9A-Za-z_\-]+)/(?P&lt;token&gt;[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$ [name='activate'] health/ ^static\/(?P&lt;path&gt;.*)$ The current path, user/activate/b'MjQ'/4zb-89a933fe70e0d12de725/, didn't match any of these. urls.py urlpatterns = [ ..... re_path(r'^user/activate/(?P&lt;uidb64&gt;[0-9A-Za-z_\-]+)/(?P&lt;token&gt;[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', user_activate, name='activate') ] Generating the tokens: from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from django.template.loader import render_to_string from django.contrib.auth.tokens import default_token_generator message = render_to_string('email_account_activate.html', { 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) Verification: try: uid = force_text(urlsafe_base64_decode(uidb64)) user = MyUser.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, MyUser.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): user.is_active = True user.save() Is the problem with the url or token format? Appreciate any help.
tagged with: python-3.x
linked to: http://stackoverflow.com/q/47177696
tagged with: django-2.0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91301838
has comment: http://stackoverflow.com/comment/91300702
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91300478
answer count: 0
has comment: http://stackoverflow.com/comment/91301281

http://stackoverflow.com/q/52245604
has answer: http://stackoverflow.com/a/65825203
tagged with: python
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
type: AnsweredQuestion
tagged with: selenium
has title: DevTools listening on ws://127.0.0.1:57671/devtools/browser/8a586f7c-5f2c-4d10-8174-7a7bf50e49b5 with Selenium and Python
has answer: http://stackoverflow.com/a/52257573
upvote count: 1
tagged with: google-chrome-headless
type: Question
possible better answer: http://stackoverflow.com/a/55337877
has answer: http://stackoverflow.com/a/55337877
score: 1
has answer: http://stackoverflow.com/a/67400951
linked to: http://stackoverflow.com/q/33983860
has answer: http://stackoverflow.com/a/70770328
has body: I am using python + selenium for web browser automation and getting this error. DevTools listening on ws://127.0.0.1:57671/devtools/browser/8a586f7c-5f2c-4d10-8174-7a7bf50e49b5 [5096:1196:0909/183254.362:ERROR:mf_helpers.cc(14)] Error in dxva_video_decode_accelerator_win.cc on line 517 The problem arises when the program reaches this part of code:- def send_comments(driver): add_comments = driver.find_elements_by_class_name('add') comments = driver.find_elements_by_xpath("//form[@class='addCommentexpand']//textarea[contains(@placeholder,'Add a comment')]") submit_comments = driver.find_elements_by_xpath("//button[text()='Comment']") i = 0 for add, comment, submit in zip(add_comments, comments, submit_comments): print("comment begins") add.click() print("+add comment clicked") comment.click() print("comment textbox clicked") comment.send_comments("Amazing Art") print("text typed") submit.click() print("comment submited") i += 1 if i &gt; 5: driver.close() send_comments(driver) Its also not logging in console. Can anyone tell whats the problem?
accepted answer: http://stackoverflow.com/a/52257573
downvote count: 0
favorite count: 0
answer count: 5

http://stackoverflow.com/comment/91436662
type: QuestionComment
comment on: http://stackoverflow.com/q/52242506
score: 0
has text: thanks for quick help. I got my solution. yay!
type: Comment

http://stackoverflow.com/a/52181524
has body: Naive approach, without any performance or NLP considerations: lst = ['new york', 'school', 'new'] # do not use 'list' as a name text = 'i am going to a school in new york and therefore i have to buy a new uniform to go to new york' {p: len(text[:text.find(p)].strip().split()) for p in lst} # {'new york': 7, 'school': 5, 'new': 7}
type: Answer
answers question: http://stackoverflow.com/q/52181407
score: 0

http://stackoverflow.com/comment/91332956
type: Comment
comment on: http://stackoverflow.com/a/52191184
has text: Noooo, `stack` again :(
type: AnswerComment
score: 0

http://stackoverflow.com/q/52210391
has title: Is it possible to have a standard style for a widget?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52210828
tagged with: python
favorite count: 0
has body: I want all of the buttons in my gui to have the same style. Right now I manually write in the attributes I want but it takes up so much space. Also, if I wanted to change the style I would have to go to every single button. Is it possible to have a style i define once and then reference it when making all buttons? Something like the following: basic_style = {'background': 'blue', 'foreground':'white', 'font':'Helvetica 8 bold'} self.btn = tk.Button(text = 'Hello', style = basic_style) I know its possible to do something like this: self.btn['text'] = 'Bye' but that still doesn't help me much.
tagged with: tkinter
type: Question
tagged with: tkinter.style
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/91370916
has answer: http://stackoverflow.com/a/52210978
upvote count: 5
tagged with: user-interface
downvote count: 0

http://stackoverflow.com/q/52204954
has answer: http://stackoverflow.com/a/52216693
type: UnansweredQuestion
tagged with: python
has title: win32com.client.gencache.EnsureDispatch("Outlook.Application") not working
downvote count: 0
score: 1
type: Question
tagged with: outlook
has answer: http://stackoverflow.com/a/77853260
has answer: http://stackoverflow.com/a/77852365
answer count: 3
upvote count: 1
has body: I am trying to send email using my Outlook client through a Python script. When the below Python script is executed separately from IDLE editor, it is working fine. But when the same lines of codes are put at the end of another Python script (so that after the logic execution email is triggered) and the Python script is called from a Web application hosted in Tomcat server, it is not working. Code Snippet: #!/Python36/python.exe -u import win32com.client` mail_subject = "Test Mail Subject" mail_body = "Test Mail Body" Outlook = Win32com.client.gencache.EnsureDispatch("Outlook.Application") mail = Outlook.CreateItem(0) mail.To = 'xxx@abc.com' mail.Subject = mail_subject mail.Body = mail_body mail.Send() To check where it is failing, I had printed some comments after each line. It was found that the line: Outlook = win32com.client.gencache.EnsureDispatch("Outlook.Application") was failing when the Python script was executed from the Web application. Can anyone help with the resolution.
tagged with: email
favorite count: 0

http://stackoverflow.com/a/52136068
accepted answer of: http://stackoverflow.com/q/52135891
type: Answer
answers question: http://stackoverflow.com/q/52135891
score: 2
has comment: http://stackoverflow.com/comment/91224243
downvote count: 0
has body: No matter what kind of object we were iterating over or how that object was implemented, it would be almost impossible for x = 2*x to do anything useful to that object. x = 2*x is an assignment to the variable x; even if the previous contents of the x variable were obtained by iterating over some object, a new assignment to x would not affect the object we're iterating over. In this specific case, iterating over a NumPy array with np.nditer(a, op_flags = ['readwrite']), each iteration of the loop sets x to a zero-dimensional array that's a writeable view of a cell of a. x[...] = 2*x writes to the contents of the zero-dimensional array, rather than rebinding the x variable. Since the array is a view of a cell of a, this assignment writes to the corresponding cell of a. This is very similar to the difference between l = [] and l[:] = [] with ordinary lists, where l[:] = [] will clear an existing list and l = [] will replace the list with a new, empty list without modifying the original. Lists don't support views or zero-dimensional lists, though.
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/91870097
type: AnswerComment
score: 0
has text: Let me know whether it worked or any problem happened ;-)
type: Comment
comment on: http://stackoverflow.com/a/52464076

http://stackoverflow.com/a/52192026
score: 0
accepted answer of: http://stackoverflow.com/q/52191813
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52191813
type: Answer
has comment: http://stackoverflow.com/comment/91333897
has body: Okay, two problems. First you are trying to built a recursive algorithm but you still use a for loop. That is confusing, you can do this without the for loop. It is not wrong to use a loop in a recursive algorithm but if you change your data structure you do not need to. Second thing is that your dictionary is wrong. I assume that every key of the dictionary is the staring node and every value is a possible end node. This is how your algorithm currently works. In that case the end node for your start A1 is not given. Therefore you get the None output. The biggest problem is that you use the wrong algorithm. This algorithm finds a way from your start to your end node. But you want to ensure that every node between your start and end node is at least once visited. So you can either change the algorithm (which would be easy) or the data structure (which will lead to a lot of variations).
has comment: http://stackoverflow.com/comment/91334041

http://stackoverflow.com/comment/91264662
type: AnswerComment
has text: @jpp Yes, Cool. I like that too.
comment on: http://stackoverflow.com/a/52157145
type: Comment
score: 0

http://stackoverflow.com/comment/91434590
comment on: http://stackoverflow.com/a/52221980
score: 0
type: AnswerComment
has text: decoded_imgs=decoder.predict_generator(steps=testing _samples/batch_size)
type: Comment

http://stackoverflow.com/q/52226079
tagged with: arrays
has comment: http://stackoverflow.com/comment/91402029
favorite count: 0
has comment: http://stackoverflow.com/comment/91401862
answer count: 3
possible better answer: http://stackoverflow.com/a/52226159
tagged with: python
has body: I want to create a matrix that contains matrix elements. So I did the obvious thing and made this: import numpy as np A = np.array([1,2,3,1],[3,1,5,1]) B = np.array([1,6,8,9],[9,2,7,1]) E = np.array([A, B],[B, A]) But the compiler returns: TypeError: data type not understood What can I do to create such a matrix, because I have really huge matrices and I dont have the time to explicitly write everyone down ? * Edit 1: * Additional problem that occurred: Instead of getting a 14x14 matrix, I am getting a multidimensional (2,2,7,7) matrix. Where in the simplified version that was my original question , everything is sound. Any ideas why this occurs now? In this case I have the Amat 7x7, Bmat 7x7 , Emat 14x14, Smat 14x14 Edit 2 Ok I solved the problem using the np.block() as it was stated in the comments below. Thank you very much.
score: 2
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52226252
has answer: http://stackoverflow.com/a/52226159
has comment: http://stackoverflow.com/comment/91401960
upvote count: 3
downvote count: 1
has title: Python3 , Numpy -- Matrix of Matrix elements
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52226252
tagged with: numpy
has answer: http://stackoverflow.com/a/52226158

http://stackoverflow.com/a/52233375
upvote count: 3
score: 3
has body: Look at the code. It has 2 nested loops: The outer loop iterates over the positions val. The inner loop finds the index of the value that should be at the index val, i.e., max_pos. It takes a lot of time just to find the index. Instead, I will compute the index of each value and store it in a dict. index_of = {value: index for index, value in enumerate(arr)} (note that because all values in arr are distinct, there should be no duplicated keys) And also prepare a sorted version of the array: that way it's easier to find the maximum value instead of having to loop over the array. sorted_arr = sorted(arr) Then do the rest similar to the original code: for each index visited, use sorted_arr to get the max, use index_of to get its current index, if it's out-of-place then swap. Remember to update the index_of dict while swapping too. The algorithm takes O(n) operations (including dict indexing/modifying), plus sorting cost of n elements (which is about O(n log n)). Note: If the array arr only contains integers in a small range, it may be faster to make index_of an array instead of a dict.
answers question: http://stackoverflow.com/q/52232880
has comment: http://stackoverflow.com/comment/91415681
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52232880

http://stackoverflow.com/a/52182315
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/52181613
upvote count: 3
type: Answer
has body: Use: from google.cloud import bigquery

http://stackoverflow.com/a/52162307
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/52151185
downvote count: 0
has body: And what about instead of creating the tables array (with the names of the tables) you use... from google.cloud import bigquery client = bigquery.Client() dataset_ref = client.dataset('my_dataset') tables = list(client.list_tables(dataset_ref)) # API request(s), now you have the list of tables in this dataset queried_tables=[] for table in tables: print(table.table_id) if table.table_id.startswith("your_favourite_prefix"): #will perform the action only if the table has the desired prefix queried_tables.append(table.table_id) print(queried_tables) #the list of the desired tables names, now you can use your script to delete them all
has comment: http://stackoverflow.com/comment/91274282
has comment: http://stackoverflow.com/comment/91275168
score: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52151185

http://stackoverflow.com/q/52122242
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/91196585
has comment: http://stackoverflow.com/comment/91196741
tagged with: django
type: Question
linked to: http://stackoverflow.com/q/37059866
has comment: http://stackoverflow.com/comment/91196652
has comment: http://stackoverflow.com/comment/91196404
tagged with: amazon-s3
tagged with: django-models
has body: My question is not a duplicate of this question it is not related Basically I got the following model where some uploaded documents will be public and some others private. To decide when the doc is private or not, when creating the instance, I set the field is_public=True/False, then I will be able to choose the right direction within the AWS S3 bucket. So I want to be able to change the storage to PrivateMediaStorage() when is_public=False from my_project.storage_backends import PrivateMediaStorage class Document(models.Model): file = models.FileField(upload_to="uploaded_documents/%d-%m-%Y") # file = models.FileField(upload_to="uploaded_documents/%d-%m-%Y", # storage=PrivateMediaStorage()) uploaded_by = models.ForeignKey(UserProfile,blank=True,null=True) nb_download = models.IntegerField(default=0) is_public = models.BooleanField(default=False) Here is the storage class in case it's important. from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class PrivateMediaStorage(S3Boto3Storage): location = settings.AWS_PRIVATE_MEDIA_LOCATION default_acl = 'private' file_overwrite = False custom_domain = False
has comment: http://stackoverflow.com/comment/91196804
linked to: http://stackoverflow.com/q/5135556
has comment: http://stackoverflow.com/comment/123653135
downvote count: 0
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/91196950
favorite count: 0
has title: How can I dynamically change the storage of Django FileField()?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91196713
tagged with: python
duplicate of: http://stackoverflow.com/q/5135556
score: 2

http://stackoverflow.com/comment/91337344
type: QuestionComment
comment on: http://stackoverflow.com/q/52193545
has text: @LevZakharov Hi Lev! I'm trying to build an automated test case that tries to rely more on image recognition than on selenium. I see many techniques available with OpenCv and I was wondering if there was a simple way to get those sections.
score: 0
type: Comment

http://stackoverflow.com/comment/91445322
type: QuestionComment
comment on: http://stackoverflow.com/q/52248614
has text: Yes , that is correct.
score: 0
type: Comment

http://stackoverflow.com/q/52124284
score: 1
accepted answer: http://stackoverflow.com/a/52124293
type: Question
has answer: http://stackoverflow.com/a/52124293
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
has body: I am writing a line where I ask the user to input their school ID, which requires both letters and numbers. How can I do this? When I input a number as my answer when asked, my program works. If I type a letter with the number I get the error. Here is my code thus far using Python 3.6 IDLE: def main(): #Introduction print ("Welcome to my program!\n") #Variables with starting values waiting for user input studentid = "" gpa = 0.0 classnumber = "" #Prompt for studentID studentid = eval(input("Please enter your student ID: ")) #Prompt for GPA gpa = eval(input("Please enter your GPA: ")) #Prompt for classnumber classnumber = eval(input("Please enter your class information:")) #display the users information #StudentID: C100556789 #GPA: 4.0 #Class: COP1000 print ("\nStudent ID:\t", studentid) print ("GPA:\t", gpa) print ("Class information:\t", classnumber) And here is my error: Type "copyright", "credits" or "license()" for more information. &gt;&gt;&gt; RESTART: C:\Users\Rene Delgado\Documents\School\Fall 2018\School Code\Student Program.py &gt;&gt;&gt; main() Welcome to my program! Please enter your student ID: C100556789 Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; main() File "C:\Users\Rene Delgado\Documents\School\Fall 2018\School Code\Student Program.py", line 18, in main studentid = eval(input("Please enter your student ID: ")) File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'C100556789' is not defined
type: AnsweredQuestion
has title: How to write an input asking the user to type using both letters and numbers?
downvote count: 0

google-cloud-platform
tags question: http://stackoverflow.com/q/52249978
tags question: http://stackoverflow.com/q/52196856
tags question: http://stackoverflow.com/q/52188858
tags question: http://stackoverflow.com/q/52174695
tags question: http://stackoverflow.com/q/52206575
tags question: http://stackoverflow.com/q/52158771
tags question: http://stackoverflow.com/q/52204739
tags question: http://stackoverflow.com/q/52119750
tags question: http://stackoverflow.com/q/52191307
tags question: http://stackoverflow.com/q/52206251
tags question: http://stackoverflow.com/q/52226691
tags question: http://stackoverflow.com/q/52231300
tags question: http://stackoverflow.com/q/52187418
tags question: http://stackoverflow.com/q/52123319
type: Tag
tags question: http://stackoverflow.com/q/52241556
tags question: http://stackoverflow.com/q/52186851
tags question: http://stackoverflow.com/q/52131077
tags question: http://stackoverflow.com/q/52169523
tags question: http://stackoverflow.com/q/52261904
tags question: http://stackoverflow.com/q/52239034
tags question: http://stackoverflow.com/q/52161087
tags question: http://stackoverflow.com/q/52151548
tag name: google-cloud-platform
tags question: http://stackoverflow.com/q/52264727
tags question: http://stackoverflow.com/q/52174600
tags question: http://stackoverflow.com/q/52206453
tags question: http://stackoverflow.com/q/52265879
tags question: http://stackoverflow.com/q/52224900
tags question: http://stackoverflow.com/q/52208585
tags question: http://stackoverflow.com/q/52151185
tags question: http://stackoverflow.com/q/52231632
tags question: http://stackoverflow.com/q/52214790
tags question: http://stackoverflow.com/q/52265477
tags question: http://stackoverflow.com/q/52225407
tags question: http://stackoverflow.com/q/52168559
tags question: http://stackoverflow.com/q/52246350

http://stackoverflow.com/q/52212203
tagged with: class
tagged with: python-2.7
score: 0
linked to: http://stackoverflow.com/q/1132941
answer count: 1
duplicate of: http://stackoverflow.com/q/1132941
favorite count: 0
has body: I created a class to store some variables and dictionary. Each object will have its own dictionary. However when I created a Class in certain way, it resulted in dictionary getting shared across all objects created. When I tweaked the init, I was able to achieve what I wanted. I want to know why dictionary got shared across different objects and when and I would that be useful. Snippet 1: (Where dictionary gets populated and shared across all object instances) class A(object): def __init__(self, x, y={}): self.x = x self.y = y def set_y(self,key,value): self.y[key] = value Snippet 2:(Where dictionary value is unique and not shared between member instances) class A(object): def __init__(self,x): self.x = x self.y = {} def set_y(self,key,value): self.y[key] = value Test Driver: l = "abcdefghijklmnopqrsqtuwxyz" letter_list = [] node = None for count, letter in enumerate(l,1): if node: letter_list.append(node) node = A(letter) node.set_y(letter,count) I would like to know why dictionary got updated for all instances in first case and not for the second case
tagged with: python
has answer: http://stackoverflow.com/a/52212329
type: AnsweredQuestion
tagged with: oop
upvote count: 1
downvote count: 1
type: Question
has title: Member variable getting shared across multiple objects- python
accepted answer: http://stackoverflow.com/a/52212329

http://stackoverflow.com/comment/91302888
type: Comment
has text: Yup. When I run the code in my IDE (Pycharm) it works, the UI shows up, and the image inside the UI. It’s only when I try to run the code as a .py file through python that the UI won’t load.
type: AnswerComment
comment on: http://stackoverflow.com/a/52176050
score: 0

http://stackoverflow.com/a/52265143
has comment: http://stackoverflow.com/comment/91478975
score: 1
answers question: http://stackoverflow.com/q/52264619
has comment: http://stackoverflow.com/comment/91479444
accepted answer of: http://stackoverflow.com/q/52264619
has comment: http://stackoverflow.com/comment/91480530
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91484725
has body: The following is more concise and linear wrt to the number of combinations: from itertools import product def optimalUtilization(n, l1, l2): # all (index1, index2, sum) triplets where sum is at most n res = [(a[0], b[0], a[1]+b[1]) for a, b in product(l1, l2) if a[1]+b[1] &lt;= n] m = max(res, key=lambda x: x[2])[2] # max sum &lt;= n return [x[:2] for x in res if x[2] == m] &gt;&gt;&gt; optimalUtilization(20, [[1,8],[2,7],[3,14]], [[1,5],[2,10],[3,14]]) [(3, 1)] Whether it is more readable or more Pythonic, is certainly debatable :) Update: No more sorting and grouping needed.
type: Answer
has comment: http://stackoverflow.com/comment/91478898
upvote count: 1

http://stackoverflow.com/comment/91508965
type: QuestionComment
comment on: http://stackoverflow.com/q/52269397
has text: I have a solution, just did this for another question, will be back soon with proper solution you are requesting!
score: 0
type: Comment

http://stackoverflow.com/comment/91491169
type: QuestionComment
type: Comment
has text: @HenryWoody I got my answer from Ykh . thank you . No I wanted to return dllink conditionally depending on whether or not the requesting user has already purchased the Course .
score: 0
comment on: http://stackoverflow.com/q/52249056

http://stackoverflow.com/comment/91330492
comment on: http://stackoverflow.com/q/52134512
score: 0
type: Comment
has text: Thank @UVM but this is a different question. I already know the cost of `len()`. The cost of which I had already mentioned as O(1) constant time.
type: QuestionComment

http://stackoverflow.com/q/52194186
downvote count: 0
type: UnansweredQuestion
score: 1
type: Question
linked to: http://stackoverflow.com/q/2459979
favorite count: 0
tagged with: django
upvote count: 1
tagged with: python
answer count: 1
has body: I currently have a django management command to import CSV files, which is based on this answer. The main business is done by the following line in a loop: created = Customer.objects.get_or_create(account_no = int(row[0]), name = row[1]) However, because I have a number of different models to run this on, I wish to put the above code inside a function, and pass the attributes and row keys in from a dictionary; so I'd defnine something like: csv_columns = { 0: 'account_no', 1: 'name' } However I don't know how to run the get_or_create function based on this. I'm sure this should be simple.
has title: Django objects.get_or_create(): passing arguments from dictionary or list
has answer: http://stackoverflow.com/a/52194349

http://stackoverflow.com/q/52249114
has comment: http://stackoverflow.com/comment/91447125
type: Question
has comment: http://stackoverflow.com/comment/91446781
has comment: http://stackoverflow.com/comment/91446797
has comment: http://stackoverflow.com/comment/91447074
downvote count: 0
has answer: http://stackoverflow.com/a/52258587
tagged with: linux
tagged with: imagemagick
answer count: 2
has body: So I used to run imagemagick direct in a bash script like this: /usr/local/bin/convert image.jpg -resize 1000x1000\! -depth 2 result.jpg SO I decided to convert my script to python using wand! from wand.image import Image ... with Image(file=f) as img: img.transform(resize='1000x1000!') img.depth = 2 img.save(filename='result_py.jpg') f.close() ... I've noticed that if I remove the "-depth 2" from the bash script, the result image will be exactly like the result from python, so what am I missing in the python program? Why does do the depth option in python is not working?
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52249475
tagged with: python
score: 2
tagged with: wand
has title: Imagemagick wand use of depth is not working like command line
tagged with: color-depth

http://stackoverflow.com/q/52138336
tagged with: python
tagged with: restructuredtext
upvote count: 9
tagged with: read-the-docs
has answer: http://stackoverflow.com/a/52141199
has title: Reference to an image from different locations
score: 9
type: Question
downvote count: 0
answer count: 1
favorite count: 0
has body: I am using Python Sphinx (via ReadTheDocs). I have a repository which contains a few sub-modules, and I'm trying to create a unified documentation, but still keep the the docs assets in each module separately. My folder hierarchy is: MyProject docs index.rst module_1_link.rst _static &lt;more irrelevant assets...&gt; module_1 docs README.rst _static myimage.png The index.rst file looks like this: .. toctree:: :caption: Module1 module_1_link The file module_1_link.rst just contains a link to the README file of module 1: .. include:: ../module1/docs/README.rst And the README.rst of module 1 references the image: .. image:: _static/myimage.jpg When I look at the README file of module 1 (inside GitHub) - myimage.png is shown perfectly. But, when I run the documentation via Sphinx I get: WARNING: image file not readable: _static/myimage.jpg I can't find a way to reference the same image from both the README file and the index file rendered by Sphinx and see it in both places.
tagged with: python-sphinx
type: UnansweredQuestion

http://stackoverflow.com/comment/139940410
type: Comment
has text: also `globals()["__vsc_ipynb_file__"]` would provide the full path.
score: 1
comment on: http://stackoverflow.com/a/75683730
type: AnswerComment

http://stackoverflow.com/comment/91447395
comment on: http://stackoverflow.com/q/52249551
has text: You probably just want something like `if dfs(word, gen+i): return True`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91426776
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52238963
has text: @sof No. Why would you need recursive calls?
score: 0

http://stackoverflow.com/a/52118692
downvote count: 0
has body: Don't use a line chart here, use a bar chart, as there is no linear correlation between any of your items. This will solve your labeling problem at the same time: df.groupby('Item').sum().plot(kind='bar') plt.tight_layout() plt.show()
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91191104
upvote count: 2
answers question: http://stackoverflow.com/q/52118445
accepted answer of: http://stackoverflow.com/q/52118445
type: AcceptedAnswer

http://stackoverflow.com/a/52122127
downvote count: 0
has body: When you create buttons, you need to keep images, otherwise, they are destroyed by the garbage collector. I don't have your images, but with my it works def callback(): print("click!") class Window(Frame): # Define settings upon initialization. Here you can specify def __init__(self, master=None): # parameters that you want to send through the Frame class. Frame.__init__(self, master) # reference to the master widget, which is the tk window self.master = master # with that, we want to then run init_window, which doesn't yet exist self.init_window() # Creation of init_window def init_window(self): self.master.title("ABC Automation Platform") p1 = IdsPage(self) self.grid() # creating a menu instance menu = Menu(self) self.master.config(menu=menu) # create the file object) file = Menu(menu, tearoff=False) file.add_command(label="Exit", command=client_exit) file.add_command(label="Download All", command=download_all) file.add_command(label="Rename All", command=rename_all) menu.add_cascade(label="File", menu=file) edit = Menu(menu, tearoff=False) help = Menu(menu, tearoff=False) help.add_command(label="Help") edit.add_command(label="Undo") menu.add_cascade(label="Edit", menu=edit) menu.add_cascade(label="Help", menu=help) btn_paths = "Resources/Buttons/" self.img_ids = PhotoImage(file=btn_paths + "btn_btn_1.png") self.img_sox = PhotoImage(file=btn_paths + "btn_btn_1.png") self.img_sps = PhotoImage(file=btn_paths + "btn_btn_1.png") self.img_dev = PhotoImage(file=btn_paths + "btn_btn_1.png") self.b_ids = Button(self, height=150, width=150, image=self.img_ids, command=callback) self.b_ids.grid(row=1, column=1, padx=(70, 50), pady=10) self.b_sox = Button(self, height=150, width=150, image=self.img_sox, command=callback) self.b_sox.grid(row=1, column=2, pady=10) self.b_sps = Button(self, height=150, width=150, image=self.img_sps, command=callback) self.b_sps.grid(row=2, column=1, padx=(70, 50), pady=5) self.b_dev = Button(self, height=150, width=150, image=self.img_dev, comm…
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52121950
answers question: http://stackoverflow.com/q/52121950
type: Answer
score: 2

http://stackoverflow.com/comment/91353113
type: Comment
type: QuestionComment
has text: @Martineau Alright, I'll see what I can scrounge around elsewhere. I thought I asked it appropriately, but I was in a rush yesterday so that is definitely my fault for not clearly (100%) providing that question. However, with my example (from the other project), it should've filled in some of the holes.
comment on: http://stackoverflow.com/q/52189260
score: 0

http://stackoverflow.com/q/52263060
type: AnsweredQuestion
score: 4
linked to: http://stackoverflow.com/q/6811183
has comment: http://stackoverflow.com/comment/91474771
downvote count: 1
type: Question
upvote count: 5
tagged with: pandas
has title: rolling function in python ignoring nans
answer count: 1
has body: https://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.rolling_quantile.html I cant not see how to best ignore NaNs in the rolling percentile function. Would anyone know? seriestest = pd.Series([1, 5, 7, 2, 4, 6, 9, 3, 8, 10]) and insert nans seriestest2 = pd.Series([1, 5, np.NaN, 2, 4, np.nan, 9, 3, 8, 10]) Now, on the first series, I get expected output, using: seriestest.rolling(window = 3).quantile(.5) But, I wish to do the same and ignore NaNs on the test2 series. seriestest2.rolling(window = 3).quantile(.5) Gives: 0 NaN 1 NaN 2 NaN 3 NaN 4 NaN 5 NaN 6 NaN 7 NaN 8 8.0 9 8.0 dtype: float64 But I think it gives something like this if we can parse a skipna=True, which doesn't work for me: 0 NaN 1 NaN 2 5.0 3 2.0 4 4.0 5 4.0 6 4.0 7 3.0 8 8.0 9 8.0 dtype: float64
has comment: http://stackoverflow.com/comment/91474455
has answer: http://stackoverflow.com/a/52263342
favorite count: 0
has comment: http://stackoverflow.com/comment/91476413
accepted answer: http://stackoverflow.com/a/52263342
has comment: http://stackoverflow.com/comment/91473984
tagged with: python
has comment: http://stackoverflow.com/comment/91474226

http://stackoverflow.com/q/52114168
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52116992
has comment: http://stackoverflow.com/comment/91180530
has body: I want to extract the Host name and Ip from following url, but it returns nothing. import requests from bs4 import BeautifulSoup url = "https://mxtoolbox.com/SuperTool.aspx?action=mx%3abuildersinmysore.com&amp;run=toolpage" response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') divs = soup.find_all('div', {'class':'tool-result-body'}) #table = soup.find_all('table', {'class': 'table table-striped table-bordered table-condensed tool-result-table'}) print(divs)
tagged with: python
accepted answer: http://stackoverflow.com/a/52116992
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91178777
has comment: http://stackoverflow.com/comment/91178852
has comment: http://stackoverflow.com/comment/91179156
has title: unable to extract data from div section
tagged with: web-scraping
type: Question
has comment: http://stackoverflow.com/comment/91180183
has comment: http://stackoverflow.com/comment/91179091

http://stackoverflow.com/a/52147891
accepted answer of: http://stackoverflow.com/q/52147762
type: AcceptedAnswer
score: 0
has body: Split the string into a list at the '],[' then test for square brackets in each part, if one is found print offending part + the 2 square brackets. string =str('[[12.12345678,12.12345678],[12.12[12.12345678,12.12345678], [12.12345678,12.12345678]]') string = string[1:-1] string = string.split(",") x = 0 fl = 0 for i in string : b = (string[x]) c = 0 detect = 0 for i in range(len(b)): d = (b[c]) if d=='[': detect += 1 c += 1 if detect == 2: if fl == 0: print(string[x]+']') else: print('['+string[x]) x += 1 if fl == 0: fl = 1 else: fl = 0
answers question: http://stackoverflow.com/q/52147762
type: Answer

http://stackoverflow.com/q/52235013
tagged with: python
type: AnsweredQuestion
has body: I don't understand how to install modules to Jupyter Notebook. I tried importing different frameworks but nothing can be imported even though I have everything installed in my system. I'm using pip. Or maybe there's a way to point Jupyter to a certain virtualenv?
accepted answer: http://stackoverflow.com/a/52235107
has answer: http://stackoverflow.com/a/54285531
type: Question
has answer: http://stackoverflow.com/a/52241036
has answer: http://stackoverflow.com/a/65189725
downvote count: 0
answer count: 6
possible better answer: http://stackoverflow.com/a/52235154
favorite count: 0
has answer: http://stackoverflow.com/a/52235154
has answer: http://stackoverflow.com/a/59066984
upvote count: 6
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/52235107
score: 6
has title: ModuleNotFoundError: No module named 'pandas' (jupyter notebook)

http://stackoverflow.com/comment/91423117
score: 2
comment on: http://stackoverflow.com/q/52237275
has text: Maybe you should consider using more than one line of code. Pls provide at least one example of how your output looks like and what you desire instead.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91386440
type: QuestionComment
comment on: http://stackoverflow.com/q/52218876
has text: Thank you for your inputs @Serdalis , ive been searching for solutions but i didnt have the chance to resolve this issue. Is it possible that i have updated my version of openssl thats why it suddenly dont work?
score: 0
type: Comment

http://stackoverflow.com/comment/91255670
type: QuestionComment
comment on: http://stackoverflow.com/q/52148757
score: 0
has text: Sorry AKX, have cleaned it up a bit and added some imports. Thank you for the heads up
type: Comment

http://stackoverflow.com/comment/91223065
type: Comment
comment on: http://stackoverflow.com/a/52134636
has text: I checked the RAM allocation, apparently I'm the less fortunate one :(. Thanks for your answer though.
type: AnswerComment
score: 2

http://stackoverflow.com/comment/91278252
has text: thanks, dears, solved @DanielRoseman
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52160983

http://stackoverflow.com/comment/91386211
type: QuestionComment
has text: Ok, but you need to show us your code for the reverse conversion, and ask a specific question so we can help you make that code work correctly. Otherwise, this question's likely to be closed as too broad.
score: 0
comment on: http://stackoverflow.com/q/52218687
type: Comment

http://stackoverflow.com/q/52191695
has title: Rotate transformation on matplotlib axis in subplot
accepted answer: http://stackoverflow.com/a/52205722
tagged with: plot
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91334519
tagged with: matplotlib
linked to: http://stackoverflow.com/q/22540449
type: Question
tagged with: graph
answer count: 1
has comment: http://stackoverflow.com/comment/91333550
has comment: http://stackoverflow.com/comment/91333674
has body: I am trying to create a four-panel figure where the bottom-left panel contains a scatter plot, and the other three panels contain histograms. The top-left will be a standard histogram across the x-dimension of the scatter, the bottom-right will be a 90° rotated histogram for the y-dimension. Both of these are easy to do in matplotlib. I am running into problems with the third histogram, which is to be a 45° rotated plot in the top-right of the figure giving the distribution of the differences between the x and y points. I have made such figures before by manually rotating and rescaling the axes in Illustrator, but it seems like matplotlib should be able to produce figures that are already rotated using the transformation methods on the subplot axes. I thought something like the following might work: import matplotlib.pyplot as plt from matplotlib.transforms import Affine2D fig, ax = plt.subplots(nrows=2, ncols=2, squeeze=True, sharex=False, sharey=False, figsize=(8,8)) ax[0,1].text(0.5,0.5,'I should be rotated',ha='center',va='center') t = ax[0,1].get_transform() ax[0,1].set_transform(t.transform(Affine2D().rotate_deg(45))) plt.show() Here I am attempting to get the transform from the axis, modify it, and then replace it back into the axis object. This code has no effect however. Any help would be greatly appreciated. Edited based on suggestion from ImportanceOfBeingErnest in comments: I have taken a look at the Floating Axes demo, and now have this: from matplotlib.transforms import Affine2D import mpl_toolkits.axisartist.floating_axes as floating_axes import matplotlib.pyplot as plt def setup_axes(fig, rect, rotation, axisScale): tr = Affine2D().scale(axisScale[0], axisScale[1]).rotate_deg(rotation) grid_helper = floating_axes.GridHelperCurveLinear(tr, extremes=(-0.5, 3.5, 0, 4)) ax = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax) aux_ax = ax.get_aux_axes(tr) return ax, aux_ax fig = plt.figure(1, figsize=(8, 8)) axes = [] axi…
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/52205722
has comment: http://stackoverflow.com/comment/91336296

http://stackoverflow.com/comment/91481838
type: QuestionComment
has text: a piece of code would be helpful.
comment on: http://stackoverflow.com/q/52266980
score: 0
type: Comment

http://stackoverflow.com/q/52225908
has comment: http://stackoverflow.com/comment/91402039
has comment: http://stackoverflow.com/comment/91401240
tagged with: performance
has comment: http://stackoverflow.com/comment/91401372
has comment: http://stackoverflow.com/comment/91403772
tagged with: pandas
has comment: http://stackoverflow.com/comment/91401779
answer count: 1
has comment: http://stackoverflow.com/comment/91401399
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91404001
favorite count: 0
has comment: http://stackoverflow.com/comment/91406317
has comment: http://stackoverflow.com/comment/91463218
has comment: http://stackoverflow.com/comment/91401720
tagged with: python
has title: For loop pandas and numpy: Performance
has comment: http://stackoverflow.com/comment/91403988
type: UnansweredQuestion
has body: I have coded the following for loop. The main idea is that in each occurrence of 'D' in the column 'A_D', it looks for all the possible cases where some specific conditions should happen. When all the conditions are verified, a value is added to a list. a = [] for i in df.index: if df['A_D'][i] == 'D': if df['TROUND_ID'][i] == ' ': vb = df[(df['O_D'] == df['O_D'][i]) &amp; (df['A_D'] == 'A' ) &amp; (df['Terminal'] == df['Terminal'][i]) &amp; (df['Operator'] == df['Operator'][i])] number = df['number_ac'][i] try: ## if all the conditions above are verified a value is added to a list x = df.START[i] - pd.Timedelta(int(number), unit='m') value = vb.loc[(vb.START-x).abs().idxmin()].FlightID except: ## if are not verified, several strings are added to the list value = 'No_link_found' else: value = 'Has_link' else: value = 'IsArrival' a.append(value) My main problem is that df has millions of rows, therefore this for loop is way too time consuming. Is there any vectorized solution where I do not need to use a for loop?
upvote count: 1
tagged with: loops
has comment: http://stackoverflow.com/comment/91401558
has answer: http://stackoverflow.com/a/52228231
type: Question
tagged with: numpy

django
tags question: http://stackoverflow.com/q/52161791
tags question: http://stackoverflow.com/q/52251907
tags question: http://stackoverflow.com/q/52221594
tags question: http://stackoverflow.com/q/52225437
tags question: http://stackoverflow.com/q/52113566
tags question: http://stackoverflow.com/q/52252852
tags question: http://stackoverflow.com/q/52144900
tags question: http://stackoverflow.com/q/52168083
tags question: http://stackoverflow.com/q/52180610
tags question: http://stackoverflow.com/q/52193263
tags question: http://stackoverflow.com/q/52208582
tags question: http://stackoverflow.com/q/52129572
tags question: http://stackoverflow.com/q/52266377
tags question: http://stackoverflow.com/q/52239137
tags question: http://stackoverflow.com/q/52163488
tags question: http://stackoverflow.com/q/52167771
tags question: http://stackoverflow.com/q/52125819
tags question: http://stackoverflow.com/q/52188784
tags question: http://stackoverflow.com/q/52189623
tags question: http://stackoverflow.com/q/52178129
tags question: http://stackoverflow.com/q/52245386
tags question: http://stackoverflow.com/q/52242954
tags question: http://stackoverflow.com/q/52115252
tags question: http://stackoverflow.com/q/52248562
tags question: http://stackoverflow.com/q/52112496
tags question: http://stackoverflow.com/q/52166041
tags question: http://stackoverflow.com/q/52197640
tags question: http://stackoverflow.com/q/52181389
tags question: http://stackoverflow.com/q/52139953
tags question: http://stackoverflow.com/q/52189100
tags question: http://stackoverflow.com/q/52211716
tags question: http://stackoverflow.com/q/52244151
tags question: http://stackoverflow.com/q/52250895
tags question: http://stackoverflow.com/q/52180216
tags question: http://stackoverflow.com/q/52162711
tags question: http://stackoverflow.com/q/52127601
tags question: http://stackoverflow.com/q/52172366
tags question: http://stackoverflow.com/q/52215941
tags question: http://stackoverflow.com/q/52152343
tags question: http://stackoverflow.com/q/52136525
tags question: http://stackoverflow.com/q/52195349
tags question: http://stackoverflow.com/q/52117935
tags question: http://stackoverflow.com/q/52123097
tags question: http://stackoverflow.com/q/52159365
tags question: http://stackoverflow.com/q/52178020
tags question: http://stackoverflow.com/q/52160912
tags question: http://stackoverflow.com/q/52256428
tags question: http://stackoverflow.com/q/52188185
tags question: http://stackoverflow.com/q/52268509
tags question: http://stackoverflow.com/q/52141129
tags question: http://stackoverflow.com/q/52127072
type: Tag
tags question: http://stackoverflow.com/q/52257555
tags question: http://stackoverflow.com/q/52128328
tags question: http://stackoverflow.com/q/52148131
tags question: http://stackoverflow.com/q/52246961
tags question: http://stackoverflow.com/q/52239590
tags question: http://stackoverflow.com/q/52162646
tags question: http://stackoverflow.com/q/52139956
tags question: http://stackoverflow.com/q/52179629
tags question: http://stackoverflow.com/q/52162674
tags question: http://stackoverflow.com/q/52170104
tags question: http://stackoverflow.com/q/52211142
tags question: http://stackoverflow.com/q/52172077
tags question: http://stackoverflow.com/q/52152355
tags question: http://stackoverflow.com/q/52128379
tags question: http://stackoverflow.com/q/52243669
tags question: http://stackoverflow.com/q/52155601
tags question: http://stackoverflow.com/q/52166468
tags question: http://stackoverflow.com/q/52155758
tags question: http://stackoverflow.com/q/52169760
tags question: http://stackoverflow.com/q/52247181
tags question: http://stackoverflow.com/q/52243362
tags question: http://stackoverflow.com/q/52240758
tags question: http://stackoverflow.com/q/52259027
tags question: http://stackoverflow.com/q/52155187
tags question: http://stackoverflow.com/q/52244271
tags question: http://stackoverflow.com/q/52121073
tags question: http://stackoverflow.com/q/52126753
tags question: http://stackoverflow.com/q/52155023

http://stackoverflow.com/comment/91298239
comment on: http://stackoverflow.com/q/52172532
has text: @PeterWood, very good idea. `fileinput` will be a more "natural" solution of the problem.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91200942
type: Comment
has text: If the values are large enough, ie. `661426176`. Those are getting converted to `6.61426e+08`. Otherwise, it's just perfect! :)
comment on: http://stackoverflow.com/a/52122687
type: AnswerComment
score: 0

http://stackoverflow.com/a/52191405
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91333175
has comment: http://stackoverflow.com/comment/91332990
accepted answer of: http://stackoverflow.com/q/52191290
has comment: http://stackoverflow.com/comment/91333437
has comment: http://stackoverflow.com/comment/91334438
has comment: http://stackoverflow.com/comment/91333863
has comment: http://stackoverflow.com/comment/91332687
type: Answer
has comment: http://stackoverflow.com/comment/91333041
has comment: http://stackoverflow.com/comment/91333939
has comment: http://stackoverflow.com/comment/91333053
upvote count: 2
has comment: http://stackoverflow.com/comment/91333695
downvote count: 1
has body: You are so close to being correct. You just have to call find_elements (notice the S) which creates a list of the children Your print statement is also wrong ids = [] resultSet = browser.find_element_by_xpath('//*[@id="mainContent"]/div[1]/div/div[5]/ul') ids = resultSet.find_elements_by_tag_name('li') for id in ids: print(id.get_attribute('id'))
score: 1
has comment: http://stackoverflow.com/comment/91333221
has comment: http://stackoverflow.com/comment/91333502
has comment: http://stackoverflow.com/comment/91333394
answers question: http://stackoverflow.com/q/52191290
has comment: http://stackoverflow.com/comment/91332872

http://stackoverflow.com/comment/91302854
type: Comment
comment on: http://stackoverflow.com/a/52176050
has text: Have you check the image is existed or not. Since if I changed the image path to sth not existing, the prompt closed immediately.
score: 0
type: AnswerComment

http://stackoverflow.com/a/68165692
score: 2
downvote count: 0
has body: Building on m.borhan's answer, since in their code some contiguous bold and italic portions failed to output as single item: from docx import * document = Document('path_to_your_files') bolds=[] italics=[] last_bold = &quot;&quot; #last bold part last_italic = &quot;&quot; #last italic part for para in document.paragraphs: for run in para.runs: if run.italic : last_italic = last_italic + run.text elif run.bold : last_bold = last_bold + run.text else: italics.append(last_italic) bolds.append(last_bold) last_italic = &quot;&quot; last_bold = &quot;&quot; italics = [i for i in italics if i] bolds = [i for i in bolds if i] boltalic_Dict={'bold_phrases':bolds, 'italic_phrases':italics}
upvote count: 2
answers question: http://stackoverflow.com/q/52125333
type: Answer

http://stackoverflow.com/comment/91304639
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/52177162
has text: ok, there may be a lot of cases. If some nodes share with one same value, your solution will get wrong answer because you use the value as the key of node.

http://stackoverflow.com/a/52173625
answers question: http://stackoverflow.com/q/52155339
upvote count: 1
has body: You cannot access form data in your template the way you are trying to. If you are using javascript to get data from the form then. IF you don't specify an ID for your form elements, WTForm will render them using the variable name as the id attribute as well as the name attribute pf the HTML input. You can use that to select that input by id using javascript/jquery Your jquery code should look like this. &lt;script&gt; $(document).ready(function(){ $('#btn1').click(function(){ $('.para1').toggle(); var boltPreloadInput = $('#bolt_preload'); alert(boldPreloadInput.val()); }); }); &lt;/script&gt; When you use WTForms, your form elements render to HTML inputs on page load. Once the page is loaded, you cannot access form data on the client side like you are trying. The only way to interact with the form on click events without first sending the data to the server is by using javascript.
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/91212434
type: QuestionComment
score: 2
has text: @ChrisA you can do that in `pd.read_csv` you don't need a second df to do this. just do `pd.read_csv('/docs/Credit_card.csv', encoding='ISO-8859-1', usecols=[0,1,2,3,4,5])`. Basically what I am saying is to use the column's positional value rather than string value to import the data.
comment on: http://stackoverflow.com/q/52130812
type: Comment

http://stackoverflow.com/comment/91182875
has text: How to get values for just 'A' like df['A'] ?
comment on: http://stackoverflow.com/a/52116036
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52223358
has body: I am trying to plot a chart in Altair using the below code. tot_matches_played = alt.Chart(mpt).mark_bar().encode( alt.X('Team',axis=alt.Axis(title='Teams Played in IPL'), sort=alt.EncodingSortField(field='Number_of_matches_played:Q', op='count', order='ascending')), alt.Y('Number_of_matches_played:Q' ), tooltip=['sum(Number_of_matches_played)'] ) But since the tooltip name is weird, I would like to rename it on the chart using "as", something like below. tot_matches_played = alt.Chart(mpt).mark_bar().encode( alt.X('Team',axis=alt.Axis(title='Teams Played in IPL'), sort=alt.EncodingSortField(field='Number_of_matches_played:Q', op='count', order='ascending')), alt.Y('Number_of_matches_played:Q' ), tooltip=['sum(Number_of_matches_played)' as total_matches] ) How to rename a tooltip so that it would appear in a more readable way to users looking at the chart.
answer count: 2
has answer: http://stackoverflow.com/a/52223959
type: UnansweredQuestion
has title: Rename tooltip in altair
has answer: http://stackoverflow.com/a/55426039
score: 8
downvote count: 0
tagged with: tooltip
tagged with: altair
favorite count: 0
upvote count: 8
type: Question
tagged with: python

http://stackoverflow.com/a/52169353
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91289517
has body: This is happening because you're modifying mutable objects that both lists contain references to. Modifying the list you sliced won't change the slice, but modifying a mutable object in that list will also be visible from the other list, because both lists contain the same object. list_ = [[1, 2, 3], [4, 5, 6]] slice_ = list_[:] list_[0] = [7, 8, 9] print(slice_) # [[1, 2, 3], [4, 5, 6]] list_[1].append(0) print(slice_[1]) # [4, 5, 6, 0] print(list_[1] is slice_[1]) # The two lists both contain the same list object # True
downvote count: 0
answers question: http://stackoverflow.com/q/52169101

http://stackoverflow.com/a/71199052
has body: The following is based on user's rocksportrocker excellent answer. I am a Python beginner! Below, please find my first version of using user rocksportrocker's recommendation. import pandas as pd print("Info: Loading starting.") # https://stackoverflow.com/questions/52209290 temp = []; myCounter = 1; myChunksize = 10000; # https://stackoverflow.com/questions/24251219/ for myChunk in pd.read_csv('YourFileName.csv', chunksize = myChunksize, low_memory = False): print('# of rows processed: ', myCounter*myChunksize) myCounter = myCounter + 1; temp.append(myChunk) print("Info: Loading complete.") # https://stackoverflow.com/questions/33642951 df = pd.concat(temp, ignore_index = True) df.head()
type: Answer
answers question: http://stackoverflow.com/q/52209290
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/91178343
comment on: http://stackoverflow.com/a/52113193
score: 1
type: AnswerComment
has text: I did these and have found no evidence that the output of findAll or find_all contains a none value that can be targeted. =( Can you post a sample code that targets and proves the existence of the none value in the output of findAll?
type: Comment

http://stackoverflow.com/a/52171756
answers question: http://stackoverflow.com/q/52171593
has comment: http://stackoverflow.com/comment/91294382
has comment: http://stackoverflow.com/comment/135096365
score: 29
has comment: http://stackoverflow.com/comment/91294393
has comment: http://stackoverflow.com/comment/91294635
has comment: http://stackoverflow.com/comment/137160159
downvote count: 4
upvote count: 33
has body: Ideally, you are encouraged to have a requirements.txt file which contains all the packages required for installation via pip. You can create this file by doing: pip freeze &gt; requirements.txt You can convert a Pipfile and Pipfile.lock into a requirements.txt. pipenv lock -r &gt; requirements.txt After that, you can install all your modules in your python virtual environment by doing the following: pip install -r requirements.txt Hopefully, I anwered your question.
has comment: http://stackoverflow.com/comment/91294579
type: Answer

http://stackoverflow.com/comment/91481292
type: QuestionComment
comment on: http://stackoverflow.com/q/52266674
score: 2
has text: There are two basic approaches to using Tkinter in an OOP manner - either you derive your classes from Tkinter widgets (typically `Frame`, `Toplevel`, or `Tk` itself), or you define ordinary Python classes that merely reference widgets. You have chosen the second approach - in which case your `AUTOPRIMER` instance is utterly unsuitable as the parent of any widget, because it's not a widget itself. You need to pass an actual widget to `BlastAPI.__init__()`, and use that as the parent of its widgets.
type: Comment

http://stackoverflow.com/comment/91455415
has text: and there was me thinking I needed help :p
type: Comment
comment on: http://stackoverflow.com/a/52253716
score: 1
type: AnswerComment

http://stackoverflow.com/comment/138716129
comment on: http://stackoverflow.com/q/52229539
type: Comment
type: QuestionComment
has text: the documentation for django commands is really bad (as is much of django documentation, unfortunately)
score: 0

http://stackoverflow.com/q/52188616
tagged with: python
type: AnsweredQuestion
tagged with: object-type
has title: Python dtype('O') . Processing object data type. Converting to string/integer
linked to: http://stackoverflow.com/q/20109391
score: 1
has answer: http://stackoverflow.com/a/52188931
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52188931
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/52188835
has answer: http://stackoverflow.com/a/52188835
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
has body: I have the table from ImDB with actors. From this table I want to drop all rows where imdb_actors.birthYear is missing or is less than 1950 and also drope those where imdb_actors.deathYear has some value. Idea is to get a dataset with actors who are alive and not retired. imdb_actors.birthYear.dtype Out:dtype('O') And I can't convert to string, this doesn't help: imdb_actors['birthYear'] = imdb_actors['birthYear'].astype('|S'). It just ruins all years. That's why I can't execute: imdb_actors[imdb_actors.birthYear &gt;= 1955] When I try imdb_actors.birthYear.astype(str).astype(int) I get the message: ValueError: invalid literal for int() with base 10: '\\N' What will be the way to drop missing and apply >= 1950 condition?

http://stackoverflow.com/comment/91297987
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52173272
type: QuestionComment
has text: Not a downvoter, but this question lacks effort, please post what you have tried even if it doesn't work. Also this question is kinda broad as it stands, and it feels like a "give me the codes" type of question which is generally not well received. My suggestion to improve this question, is to post the code you have tried, and explain what's wrong with it in a [MCVE] form

http://stackoverflow.com/a/52229817
answers question: http://stackoverflow.com/q/52229706
type: AcceptedAnswer
downvote count: 0
has body: You need only a minor change: modify the list in place using a slice assignment, rather than creating a new list. You then don't need to return it (in fact, the Python convention is to not do so). def lowercase(strings): """takes a list of strings and replaces each with lowercase version""" strings[:] = (x.lower() for x in strings)
has comment: http://stackoverflow.com/comment/91409828
type: Answer
has comment: http://stackoverflow.com/comment/91409368
has comment: http://stackoverflow.com/comment/91409787
score: 7
has comment: http://stackoverflow.com/comment/91409404
upvote count: 7
has comment: http://stackoverflow.com/comment/91409322
accepted answer of: http://stackoverflow.com/q/52229706

http://stackoverflow.com/comment/91268453
type: Comment
type: QuestionComment
has text: Sounds like you're forgetting that each process can only have a copy, not an actual reference to the instance.
score: 0
comment on: http://stackoverflow.com/q/52135667

http://stackoverflow.com/q/52130441
answer count: 1
downvote count: 1
tagged with: numpy
duplicate of: http://stackoverflow.com/q/16970982
tagged with: arrays
has body: I want to iterate over an array of arrays and skip to the next array if I've already read the same array. The following code works, but I'm searching a more 'pythonic' style solution. from sklearn import datasets import numpy as np iris = datasets.load_iris() X = iris.data[:, :2] read = [] for x in X: temp = True for r in read: if np.array_equal(x, r): temp = False if temp: read.append(x) # do some stuff Type and content of X: &gt;&gt;&gt; type(X) &lt;class 'numpy.ndarray'&gt; &gt;&gt;&gt; X array([[5.1, 3.5], [4.9, 3. ], [4.9, 3. ] [4.7, 3.2], [4.6, 3.1], [5. , 3.6], ... [5.9, 3. ]]) For example, when I read [4.9, 3. ] the first time I do some stuff. When I read [4.9, 3. ] again I skip to the next array.
has title: How to remove duplicated array in array of arrays in a pythonic way?
type: AnsweredQuestion
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/91211631
has answer: http://stackoverflow.com/a/52130509
tagged with: python
accepted answer: http://stackoverflow.com/a/52130509
score: 0
has comment: http://stackoverflow.com/comment/91211292
linked to: http://stackoverflow.com/q/16970982
upvote count: 1

http://stackoverflow.com/comment/91468975
type: AnswerComment
comment on: http://stackoverflow.com/a/52260693
has text: `//var` is only well-defined to be a remote filesystem reference on Windows, *but* `//foo` is allowed to be given local/special handling on UNIX too (see last sentence of the spec at http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap04.html#tag_04_11). It *isn't* given that handling on most out-of-the-box UNIX systems, but filesystems like AFS where it's special do exist.
score: 0
type: Comment

http://stackoverflow.com/a/52157599
has body: Unless your label has an image, the width and height represents a number of average sized characters based on the font used by the Label. A width of 700 and a height of 1 will likely result in something 6000-7000 pixels wide, and 15-20 pixels tall. If you're trying to create a border, I recommend using a frame since its width and height parameters are in pixels.
answers question: http://stackoverflow.com/q/52157372
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/q/52188415
has comment: http://stackoverflow.com/comment/91327739
has body: I have %64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%62%65%6e%2e%61%6e%67%65%72%40%6b%6e%6f%62%62%65%2e%63%6f%6d%22%20%72%65%6c%3d%22%6e%6f%69%6e%64%65%78%2c%20%6e%6f%66%6f%6c%6c%6f%77%22%3e%62%65%6e%2e%61%6e%67%65%72%40%6b%6e%6f%62%62%65%2e%63%6f%6d%3c%2f%61%3e%27%29%3b It's from a JavaScript tag that I scraped. Unfortunately, none of the solutions in Javascript unescape() vs. Python urllib.unquote() seem to work in Python 3.
tagged with: decode
accepted answer: http://stackoverflow.com/a/52188465
has comment: http://stackoverflow.com/comment/91326832
has title: Decode %xx in Python 3.6
linked to: http://stackoverflow.com/q/23158822
type: AnsweredQuestion
score: 2
downvote count: 0
favorite count: 0
duplicate of: http://stackoverflow.com/q/11768070
tagged with: python-3.x
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/91326948
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/52188465

http://stackoverflow.com/comment/91510377
has text: Windows 10, Miniconda3, using the bash shell console provided as part of git client for Windows, conda is installed along with the rest of Miniconda under /c/home/miniconda3 (or C:/home/miniconda3)
comment on: http://stackoverflow.com/q/52263338
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91449515
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52250398
has text: Yes I did. I simply used the code you provided. Are you not getting the same problem?
type: AnswerComment

http://stackoverflow.com/comment/91394489
has text: @codeape I just fetch and append it to list, nothing else, and it takes up to 2,5GB of RAM
type: Comment
comment on: http://stackoverflow.com/q/52220794
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91409818
score: 0
type: Comment
type: QuestionComment
has text: I noticed that when I added a 'return' the error doesn't appear. However, it only returns one file. I have three files that I'm trying to read/write/display.
comment on: http://stackoverflow.com/q/52228651

http://stackoverflow.com/comment/91190802
comment on: http://stackoverflow.com/q/52116158
score: 0
type: Comment
type: QuestionComment
has text: Where is `session` defined and how? From using names such as `response` and that other question of yours with identical code it seems you're in a Flask request context. Are you sure you close the session between requests? The scenario that you let the transaction "leak" from request to request, until it commits somewhere seems likely. Also, proper locking (SELECT ... FOR UPDATE, etc.) is the answer to booking use cases, not read uncommitted, if I understood you correctly.

http://stackoverflow.com/q/52177820
type: UnansweredQuestion
has title: How does `from __future__ import braces` work?
tagged with: python
has comment: http://stackoverflow.com/comment/91306391
duplicate of: http://stackoverflow.com/q/45801522
answer count: 0
type: Question
linked to: http://stackoverflow.com/q/7075082
score: 0
has body: There's a well-known joke in Python regarding braces. But - how does it work? When I search the source file, I can't find anything about braces: $ python2.7 python2.7 Python 2.7.10 (default, Feb 7 2017, 00:08:15) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from __future__ import braces File "&lt;stdin&gt;", line 1 SyntaxError: not a chance &gt;&gt;&gt; import __future__ &gt;&gt;&gt; __future__.__file__ '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/__future__.pyc' &gt;&gt;&gt; zsh: suspended python2.7 $ grep 'braces' /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/__future__.py [no response]
linked to: http://stackoverflow.com/q/101268
has comment: http://stackoverflow.com/comment/91305827
has comment: http://stackoverflow.com/comment/91315273
has comment: http://stackoverflow.com/comment/91305678
linked to: http://stackoverflow.com/q/45801522

http://stackoverflow.com/q/52175375
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52231151
tagged with: multithreading
score: 5
tagged with: python
upvote count: 5
tagged with: multiprocessing
type: Question
has body: I am trying to answer the question of how much overhead there is in creating a thread vs a process in python. I modified code from a similar question which basically runs a function with two threads and then runs the same function with two processes and reports the time. import time, sys NUM_RANGE = 100000000 from multiprocessing import Process import threading def timefunc(f): t = time.time() f() return time.time() - t def multiprocess(): class MultiProcess(Process): def __init__(self): Process.__init__(self) def run(self): # Alter string + test processing speed for i in xrange(NUM_RANGE): a = 20 * 20 for _ in xrange(300): MultiProcess().start() def multithreading(): class MultiThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): # Alter string + test processing speed for i in xrange(NUM_RANGE): a = 20 * 20 for _ in xrange(300): MultiThread().start() print "process run time" + str(timefunc(multiprocess)) print "thread run time" + str(timefunc(multithreading)) Then I got 7.9s for multiprocessing and 7.9s for multithreading The main question I'm trying to answer is if it is appropriate to use multithreading or multiprocessing for thousands of network requests on Linux specifically. Seems like according to this code they are the same in terms of startup time but perhaps processes are much heavier in memory usage?
has comment: http://stackoverflow.com/comment/91334043
downvote count: 0
has title: Overhead in creating a thread vs process on Linux
has answer: http://stackoverflow.com/a/52175631
favorite count: 0
tagged with: linux
answer count: 3
has answer: http://stackoverflow.com/a/52175617
has comment: http://stackoverflow.com/comment/91301581

http://stackoverflow.com/a/52170578
has comment: http://stackoverflow.com/comment/91291990
upvote count: 1
answers question: http://stackoverflow.com/q/52170490
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You are not returning the inputt from the function. Try: import datetime from time import gmtime, strftime from tkinter import * root = Tk() root.geometry("500x800") text1 = Label(root, text="Menu", font='Verdana, 15') text1.pack() coststr = StringVar() cost = 0 coststr.set(f'£ {cost}') menu = ["Burger", "Chips", "Milkshake"] textln = Label(root, text="\n") textln.pack() day = datetime.date.today() def choiceburger(): global cost global coststr cost += 1.99 cost = round(cost, 2) coststr.set(f'£ {cost}') txt.insert(END, 'Burger £1.99\n',) def choicechips(): global cost global coststr cost += 1.49 cost = round(cost, 2) coststr.set(f'£ {cost}') txt.insert(END, 'Chips £1.49\n',) def choicemilkshake(): global cost global coststr cost += 0.99 cost = round(cost, 2) coststr.set(f'£ {cost}') txt.insert(END, 'Milkshake £0.99\n',) def pay(): global cost global coststr txt.insert(END, "Total Charges: ") txt.insert(END, coststr.get()) from tkinter import messagebox msgbox = messagebox.askokcancel("", "Are You Sure You Want To Buy These Items?") if msgbox == True: printrec() txt.delete('1.0', END) cost = 0 cost = round(cost, 2) coststr.set(f'£ {cost}') txtboxmsg() else: quit() burgerbutton = Button(root, text=" Burger £1.99 ", command=choiceburger) burgerbutton.pack() chipsbutton = Button(root, text=" Chips £1.49 ", command=choicechips) chipsbutton.pack() milksbutton = Button(root, text=" Milkshake £0.99 ", command=choicemilkshake) milksbutton.pack() textln = Label(root, text="\n") textln.pack() textln = Label(root, text="\n") textln.pack() textln = Label(root, text="\n") textln.pack() txt = Text(root) txt.pack() def txtboxmsg(): txt.insert(END, strftime("%H:%M:%S ")) txt.insert(END, day) txt.insert(END, " Jake's Fast Food\n") txtboxmsg() def gettxt(): inputt=txt.get("1.0",END) print(inputt) return inputt def printrec(): f = open(r"receipts.txt", "a") f.write("\n{}\n".format(gettxt())) f.close() costlabel = Label(root, textvariable=coststr, font='Verdana, 20') costlabel.pack() te…
accepted answer of: http://stackoverflow.com/q/52170490

boolean
tags question: http://stackoverflow.com/q/52194145
tags question: http://stackoverflow.com/q/52197459
tags question: http://stackoverflow.com/q/52157978
tags question: http://stackoverflow.com/q/52114666
tags question: http://stackoverflow.com/q/52173161
tags question: http://stackoverflow.com/q/52209825
tags question: http://stackoverflow.com/q/52176570
tag name: boolean
tags question: http://stackoverflow.com/q/52173793
tags question: http://stackoverflow.com/q/52262516
type: Tag

http://stackoverflow.com/q/52220023
has comment: http://stackoverflow.com/comment/91391675
accepted answer: http://stackoverflow.com/a/52220950
tagged with: pandas
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91388846
tagged with: python
has title: find duplicates and mark as variant
score: -1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52220950
downvote count: 2
upvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91389014
has body: I'm trying to create a data frame where I add duplicates as variants in a column.To further illustrate my question: I have a pandas dataframe like this: Case ButtonAsInteger 0 1 130 1 1 133 2 1 42 3 2 165 4 2 158 5 2 157 6 3 158 7 3 159 8 3 157 9 4 130 10 4 133 11 4 43 ... ... ... I have converted it into this form: grouped = activity2.groupby(['Case']) values = grouped['ButtonAsInteger'].agg('sum') id_df = grouped['ButtonAsInteger'].apply(lambda x: pd.Series(x.values)).unstack(level=-1 0 1 2 3 4 5 6 7 8 9 Case 1 130.0 133.0 42.0 52.0 47.0 47.0 32.0 94.0 NaN NaN 2 165.0 158.0 157.0 141.0 142.0 142.0 142.0 142.0 142.0 147.0 3 158.0 159.0 157.0 147.0 166.0 170.0 169.0 130.0 133.0 133.0 4 130.0 133.0 42.0 52.0 47.0 47.0 32.0 94.0 NaN NaN And now I want to find duplicates and mark each duplicate as a variant. So in this example, Case 1 and 4 should get variant 1. Like this: Variants 0 1 2 3 4 5 6 7 8 9 Case 1 1 130.0 133.0 42.0 52.0 47.0 47.0 32.0 94.0 NaN NaN 2 2 165.0 158.0 157.0 141.0 142.0 142.0 142.0 142.0 142.0 147.0 3 3 158.0 159.0 157.0 147.0 166.0 170.0 169.0 130.0 133.0 133.0 4 1 130.0 133.0 42.0 52.0 47.0 47.0 32.0 94.0 NaN NaN I have already tried this method https://stackoverflow.com/a/44999009. But it doesn't work on my data frame. Unfortunately I don't know why. It will probably be possible to apply a double for loop. So for each line look if there is a duplicate in the record. Whether this is efficient on a large record, I don't know. I have also added my procedure with grouping, because perhaps there is a possibility to already work with duplicates at this point?
tagged with: duplicates
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91389111
linked to: http://stackoverflow.com/q/44998223
has comment: http://stackoverflow.com/comment/91395780

http://stackoverflow.com/q/52224900
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91401472
has answer: http://stackoverflow.com/a/55794172
has comment: http://stackoverflow.com/comment/91405468
type: Question
score: 3
has comment: http://stackoverflow.com/comment/91425520
tagged with: google-cloud-platform
downvote count: 0
answer count: 1
tagged with: python-docx
has comment: http://stackoverflow.com/comment/91400466
has body: I work with python-docx and docx in my PC, but when I've cloned the project to Google Cloud, the problems arose. Both docx and python-docx are installed there: igorsavinkin555@cloudshell:~/corrections-msword (coral-heuristic-5610)$ pip install docx --user Requirement already satisfied: docx in /home/igorsavinkin555/.local/lib/python2.7/site-packages (0.2.4) Requirement already satisfied: lxml in /home/igorsavinkin555/.local/lib/python2.7/site-packages (from docx) (4.2.4) Requirement already satisfied: Pillow&gt;=2.0 in /home/igorsavinkin555/.local/lib/python2.7/site-packages (from docx) (5.2.0) igorsavinkin555@cloudshell:~/corrections-msword (coral-heuristic-215610)$ pip install python-docx --user Requirement already satisfied: python-docx in /home/igorsavinkin555/.local/lib/python2.7/site-packages (0.8.7) Requirement already satisfied: lxml&gt;=2.3.2 in /home/igorsavinkin555/.local/lib/python2.7/site-packages (from python-docx) (4.2.4) igorsavinkin555@cloudshell:~/corrections-msword (coral-heuristic-215610)$ Problem with docx.Document: igorsavinkin555@cloudshell:~/corrections-msword (coral-heuristic-215610)$ dev_appserver.py $PWD ... INFO 2018-09-07 14:31:48,503 api_server.py:275] Starting API server at: http://0.0.0.0:41739 INFO 2018-09-07 14:31:48,518 dispatcher.py:270] Starting module "default" running at: http://0.0.0.0:8080 INFO 2018-09-07 14:31:48,519 admin_server.py:152] Starting admin server at: http://0.0.0.0:8000 INFO 2018-09-07 14:31:50,533 instance.py:294] Instance PID: 727 ERROR 2018-09-07 14:32:00,844 wsgi.py:263] Traceback (most recent call last): File "/google/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/google/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler handler, path, err = LoadObject(self._handler) File "/google/google-cloud-sdk/platform/google_appengine/google/app…
favorite count: 0
linked to: http://stackoverflow.com/q/17688959
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/91454849
tagged with: python
has title: How to install libraries python-docx / docx on Google Cloud Shell?
tagged with: http://stackoverflow.com/tag/docx

http://stackoverflow.com/q/52226341
answer count: 0
has comment: http://stackoverflow.com/comment/95711003
has title: Visualization of force-driven large graph: python and graphviz
type: Question
has body: I am working on community detection algorithms, and I am currently trying to visualize the results of Louvain algorithm (https://arxiv.org/abs/0803.0476) on a graph of 70K nodes and 8M edges. I plotted a smaller graph before (20K nodes, 650K edges) with igraph by taking inspiration from How to plot Community-based graph using igraph for python, and it took almost 30 minutes. Plotting 70K nodes and 8M edges takes 8 hours. To plot the current graph, due to performance, I moved to sfdp (e.g., sfdp foo.dot -Goutputorder="edgesfirst" -Goverlap=false -Tpdf -O). However, I am not able to achieve a good layout to highlight distinct communities by distantiating them. I tried to tune both K at graph level, and len and/or weight at edge level (by setting high values for intra-communities edges, e.g., 1000; and low values for inter-community edges, e.g., 1). sfdp seems to ignore weights. Still, as an extension of fdp, it should not. Examples on a small graph igraph + fruchterman_reingold layout sfdp Am I missing something? How can I highlight community differences as done in the above link?
linked to: http://stackoverflow.com/q/43541376
tagged with: graphviz
linked to: http://stackoverflow.com/q/40443030
score: 0
has comment: http://stackoverflow.com/comment/91536351
type: UnansweredQuestion
tagged with: python
tagged with: graph-visualization
tagged with: igraph

http://stackoverflow.com/a/52214983
upvote count: 3
type: Answer
downvote count: 0
has body: def get_e(lim): return 2 + 1/r(1, lim) def r(v1, lim): if v1 == lim: return v1 + v1/(v1+1) else: return v1 + v1/(r(v1+1, lim))
has comment: http://stackoverflow.com/comment/91379070
score: 3
accepted answer of: http://stackoverflow.com/q/52214698
answers question: http://stackoverflow.com/q/52214698
type: AcceptedAnswer

http://stackoverflow.com/q/52261625
has comment: http://stackoverflow.com/comment/91470910
favorite count: 0
upvote count: 0
type: UnansweredQuestion
has body: I am using the following logging module in python2.7 import logging LOG = logging.getLogger(__name__) where I am able to do LOG.warn("Namespace {0} is not compliant.").format(namespace) but not LOG.info("Namespace {0} is not compliant.").format(namespace) However this works: LOG.info("Namespace %s is hipaa compliant.", namespace) I am wondering why only LOG.info doesn't work.
tagged with: python
has comment: http://stackoverflow.com/comment/91471569
has comment: http://stackoverflow.com/comment/91471083
has comment: http://stackoverflow.com/comment/91471204
has comment: http://stackoverflow.com/comment/91471700
score: -1
has title: LOG.info does not have option to format string
has answer: http://stackoverflow.com/a/52262012
type: Question
answer count: 1
tagged with: python-2.7
downvote count: 1

http://stackoverflow.com/a/52138595
has body: if no_of_people == 1: return 50 else : return no_of_people*(50)+human_pyramid(no_of_people-2) the condition no_of_people == 1 will become True only if the value originally passed is odd. As a solution you may add one more base case for when no_of_people == 0 if no_of_people == 1: return 50 elif no_of_people == 0: return 0 else : return no_of_people*(50)+human_pyramid(no_of_people-2)
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52138518
answers question: http://stackoverflow.com/q/52138518
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/q/52184885
has answer: http://stackoverflow.com/a/52185069
tagged with: numpy
answer count: 2
has title: Using Numpy instead of loops
downvote count: 0
favorite count: 0
has body: I have the following dummy data: import numpy as numpy x = np.linspace(1, 10, 10) y = np.linspace(1, 10, 10) x[::-1].sort() y[::-1].sort() tot_value = np.sum(y) n_values = np.array([1, 2, 3]) final = np.sum((x[:, np.newaxis]**(1/n_values))*(y[:, np.newaxis]/tot_value))**n_values final2 = [np.sum((x[:, np.newaxis]**(1/i))*(y[:, np.newaxis]/tot_value))**i for i in n_values] My problem is that I want to use Numpy (final) to emulate the loop seen in final2 due to speed when getting larger arrays ans stuff. But the output is not the same, and I have been trying different stuff, but I just can't seem to figure out how to do it, and if it is even possible ? The output of final is: [275.3622303 16.59404201 16.59404201] Where it should be as in final2: [6.7290539608469775, 7.0, 7.0] Maybe I'm going blind on this, but I just haven't been able to see how to do it.
accepted answer: http://stackoverflow.com/a/52185069
has answer: http://stackoverflow.com/a/52185056
has comment: http://stackoverflow.com/comment/91319621
tagged with: python
tagged with: vectorization
score: 2
possible better answer: http://stackoverflow.com/a/52185056
type: AnsweredQuestion
upvote count: 2
type: Question

http://stackoverflow.com/comment/91266449
has text: Wait, I think I made a mistake in my program. Perhaps https://www.youtube.com/watch?v=IW28o11vJfE helps.
comment on: http://stackoverflow.com/q/52158095
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/91406230
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52228299
has text: Nice work. Also note that `self.draw(canvas)` is useless here and in fact causes errors on my end. Also you should use `#` instead of `//` in python for comments.

http://stackoverflow.com/comment/91329401
comment on: http://stackoverflow.com/a/52189631
type: AnswerComment
has text: You can, for example, use multiple try/except blocks to handle different problems
type: Comment
score: 0

http://stackoverflow.com/comment/118429336
type: Comment
has text: And remember that if you are running RPi OS Lite, you must first install `pip3`.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52232464

http://stackoverflow.com/comment/91342376
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52126143
type: Comment
has text: @cgdannie it should be sufficient to decode from base64, and then decode the resulting bytes from utf-8. If this doesn't work, open a new question with details and I can take a look.

trace
tag name: trace
tags question: http://stackoverflow.com/q/52238507
type: Tag

http://stackoverflow.com/comment/91313345
type: Comment
type: QuestionComment
has text: I just run pip list, keras packages are installed @Asif Mohamed
comment on: http://stackoverflow.com/q/52174530
score: 0

http://stackoverflow.com/q/52189433
tagged with: numpy
tagged with: arrays
tagged with: threshold
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52189577
has comment: http://stackoverflow.com/comment/91328815
has title: Find the first index for which an array goes below a certain threshold (and stay below for some time)
tagged with: python
has comment: http://stackoverflow.com/comment/91328917
type: AnsweredQuestion
tagged with: windowing
has comment: http://stackoverflow.com/comment/91328863
upvote count: 3
type: Question
has body: Let A be a 1D numpy array, a threshold t, and a window length K. How to find the minimal index j, such that A[j:j+K] &lt; t? (i.e. the first time A stays below the threshold on a full window of width K). I've tried (unfinished) things with a loop, but it seemed far from optimal, and I thought maybe there's a clever "numpy way" to do it. Sidenote: the fact we want to test if we're below the threshold during a certain window length instead of ponctual value, is useful to avoid on/off/on/off/on/off artefacts near the threshold (see also Hysteresis: "hysteresis is intentionally added to an electronic circuit to prevent unwanted rapid switching [...] compensate for contact bounce in switches, or noise in an electrical signal.").
score: 3
has answer: http://stackoverflow.com/a/52189577

http://stackoverflow.com/a/52209179
has body: does Cython count? cdef extern from "ctype.h": int isspace(int x) def cfunc(fd): cdef bytes buf cdef int tot = 0, prev = 0, cur cdef char c while True: buf = fd.read(8192) if not buf: return tot for c in buf: cur = isspace(c) if cur and not prev: tot += 1 prev = cur The timings on my computer are: OP's example takes 6.5s George's takes 5.3s This Cython code takes 0.65s A similar C version takes 0.73s (not sure why longer than Cython) compiled with gcc -mtune=native -march=native -Wall -O3
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91386125
answers question: http://stackoverflow.com/q/52207136
type: Answer
has comment: http://stackoverflow.com/comment/91380529
has comment: http://stackoverflow.com/comment/91379079
has comment: http://stackoverflow.com/comment/91380963
accepted answer of: http://stackoverflow.com/q/52207136

http://stackoverflow.com/q/52224239
has comment: http://stackoverflow.com/comment/91398590
type: Question
has comment: http://stackoverflow.com/comment/91401865
tagged with: python
has comment: http://stackoverflow.com/comment/91401001
has comment: http://stackoverflow.com/comment/91401833
has title: Exchange of variables between C and Python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91400868
has comment: http://stackoverflow.com/comment/91460850
upvote count: 1
has body: I've read a lot about it lately but can't get any further with a problem. It is about the exchange of variables from C scripts to Python 3.x. To the C script: I am working on the evaluation of IEC61850-9-2 Sampled Values (SV) and use the libiec61850 C library (https://github.com/mz-automation/libiec61850), which interprets the protocols. SV sends 80 samples per period (sine), which means that every 0.25 milliseconds a new sample arrives which needs to be processed. Therefore my script has to be fast. Currently I use the following C script, which evaluates the protocols and prints the samples. I hope it is understandable and my comments are sufficient: #include "hal_thread.h" #include &lt;signal.h&gt; #include &lt;stdio.h&gt; #include "sv_subscriber.h" #include &lt;unistd.h&gt; static bool running = true; int sample_rate = 80; double sample[2]= { 0.0 }; void sigint_handler(int signalId) { running = 0; } /* Callback handler for received SV messages */ static void svUpdateListener (SVSubscriber subscriber, void* parameter, SVSubscriber_ASDU asdu) { double val1, val2, val3 = 0; /* read the INT32 Voltage Values on Byte Number 32 , 40 and 48*/ val1 = (double)SVSubscriber_ASDU_getINT32(asdu, 32)/100; val2 = (double)SVSubscriber_ASDU_getINT32(asdu, 40)/100; val3 = (double)SVSubscriber_ASDU_getINT32(asdu, 48)/100; sample[0] = val1; sample[1] = val2; sample[2] = val2; printf("[%f , %f , %f ]\n", val1, val2, val3); } int main(){ /* Creating a SV Receiver and setting Interface to Eth0 */ SVReceiver receiver = SVReceiver_create(); SVReceiver_setInterfaceId(receiver, "eth0"); /* Creating a SV Subscriber, which listens to SV Messages with APPID 4000h */ SVSubscriber subscriber = SVSubscriber_create(NULL, 0x4000); /* Install a callback handler for the subscriber */ SVSubscriber_setListener(subscriber, svUpdateListener, NULL); /* Connect the subscriber to the receiver */ SVReceiver_addSubscriber(receiver, subscriber); /* Start listening to SV messages - starts a new receiver backgro…
has comment: http://stackoverflow.com/comment/91461127
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/91397767
has comment: http://stackoverflow.com/comment/91413748
has comment: http://stackoverflow.com/comment/91460794
linked to: http://stackoverflow.com/q/20363395
downvote count: 0
answer count: 0
score: 1
favorite count: 0

http://stackoverflow.com/a/52129071
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/52128972
has body: The key which was pressed is stored in the key member and not in the type member of the event object: Change type to key, when you check for the key which was pressed: e.g. if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT : glTranslatef(-1.0,0,0.0) if event.key == pygame.K_RIGHT : glTranslatef(1.0,0,0.0) if event.key == pygame.K_UP : glTranslatef(0.0,0,-1.0) if event.key == pygame.K_DOWN : glTranslatef(0.0,0,1.0)
type: Answer
score: 2

http://stackoverflow.com/comment/91420262
type: Comment
comment on: http://stackoverflow.com/a/52234970
score: 0
type: AnswerComment
has text: ahhhh oky i get what you're saying .. you're right ... i'm very new to logging.

http://stackoverflow.com/comment/91312279
type: Comment
type: QuestionComment
has text: @BlackThunder I want to catch all exceptions not only ConnectionError
score: 0
comment on: http://stackoverflow.com/q/52181161

http://stackoverflow.com/a/52222058
answers question: http://stackoverflow.com/q/52221761
has body: You cannot select ndarray for y if you need those two column values in a single plot you can use: plt.plot(table['0']) plt.plot(table['2']) If column names are intergers then: plt.plot(table[0]) plt.plot(table[2])
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91394160
accepted answer of: http://stackoverflow.com/q/52221761
type: Answer

http://stackoverflow.com/a/52174487
answers question: http://stackoverflow.com/q/52174460
type: Answer
score: 7
upvote count: 7
has body: To get a list of sets with each set containing the comma-separated words from the given line: names_list = [set(line.strip().split(', ')) for line in raw_text.splitlines()]
downvote count: 0

http://stackoverflow.com/comment/91481832
type: Comment
comment on: http://stackoverflow.com/a/52266954
score: 0
type: AnswerComment
has text: No they were not, but everytime dist = 0, the player respawned in a random location Actually no I think I understood the difference. I was using the colliderect function, so dist never actually reached 0, hence why the game didn't crash

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

http://stackoverflow.com/comment/91220416
type: QuestionComment
comment on: http://stackoverflow.com/q/52133002
has text: Your fetchall is returning 231 million rows, seems like a bad idea. You can set the fetch size to something more sane. Also, does MySQL connector have a context handler?
score: 0
type: Comment

http://stackoverflow.com/a/52123829
type: Answer
upvote count: 2
has body: If you are certain your board is a square, the diagonal elements will be where the row number and column number are the same. You can access each row by row = board[rowNum], and from there row[colNum] will give you a single element. If rowNum == colNum you're on a diagonal. You can squish the two together like I have done below (board[i][i]). Note: If your board is a list (mutable object) calling it in a function like this will change the contents of the variable that was passed into boardObject even without returning "boardObject" so heads up on that one. def replace_diag(boardObject, replacement): for i in range(len(boardObject)): boardObject[i][i] = replacement
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52123692

http://stackoverflow.com/q/52261121
answer count: 1
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52261165
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has title: .map removes values in my column that are not specified in the mapping
type: Question
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52261165
has body: I have a variety of values in one of my columns in my pandas dataframe. Those include LIMITED LIABILITY CORP, CORPORATION, LIMITED LIABILITY PARTNER, Limited Liability Corporation All I am trying to do is rename some of the values that are equivalent but are called differently. So here I want to rename Limited Liability Corporation as LIMITED LIABILITY CORP and same thing with the Partnership. This is the code I have written using map: Leads_updated['Business_Type'] = Leads_updated['Business_Type'].map({'Limited Liability Corporation': 'LIMITED LIABILITY CORP', 'Limited Liability Partnership':'LIMITED LIABILITY PARTNER'}) Now, it does properly change the values that I wanted to change, however, there are other values that I did not change in my code such as "Corporation" that are now gone from my pandas dataframe column. Why is that and how can I fix it? Thank you!

http://stackoverflow.com/comment/91409275
type: Comment
comment on: http://stackoverflow.com/q/52229785
score: 1
type: QuestionComment
has text: What does the `soup` object contain?

http://stackoverflow.com/q/52119879
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91191045
tagged with: python-2.7
answer count: 2
has body: I am fairly new to python. I am wondering how would you extract 'FRI-AA-02' from this string in a dictionary. { "layers": {}, "definitionExpression": "(UPPER(Auto_Trash_Route) = UPPER('FRI-AA-02'))" } More examples: { "id": "1", "layers": {}" "definitionExpression": "(UPPER(Auto_Yard_Route) = UPPER('FRI-AY-01'))" } { "id": "4", "layers": {}" "definitionExpression": "(UPPER(Auto_Yard_Route) = UPPER('THU-AY-23'))" }
has answer: http://stackoverflow.com/a/52120122
tagged with: string
has comment: http://stackoverflow.com/comment/91191172
favorite count: 0
has comment: http://stackoverflow.com/comment/91190926
has comment: http://stackoverflow.com/comment/91191110
has comment: http://stackoverflow.com/comment/91191212
has title: String manipulation: How isolate a word in a dictionary
tagged with: python
possible better answer: http://stackoverflow.com/a/52120065
tagged with: dictionary
has answer: http://stackoverflow.com/a/52120065
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52120122
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/91191015

http://stackoverflow.com/comment/91321072
comment on: http://stackoverflow.com/a/52185637
type: AnswerComment
score: 0
type: Comment
has text: Thank you I will give this a shot.

http://stackoverflow.com/comment/91364387
has text: @GiacomoAlzetta and CristiFati: Thank you for your comments. I've spent an hour on this but sill failed. Please see the update in the question. Thanks again!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52204971

http://stackoverflow.com/comment/91314535
type: QuestionComment
has text: Instead of computing a quaternion and converting it *back* to Euler angles, you should realize that `dx, dy` already correspond to changes in the Euler angles; specifically pitch and yaw respectively, but *not* roll - which is the cause of this unwanted rotation.
comment on: http://stackoverflow.com/q/52171916
score: 1
type: Comment

http://stackoverflow.com/a/52194944
answers question: http://stackoverflow.com/q/52194927
score: 0
has body: The answer is still in itertools. The function called product does the trick; it takes two arguments: first is the iterable which has the usable elements, second is the amount of times the iterable can repeat itself. itertools.product([4,8,15],repeat=3) would return the permutations you want in your example. The reason permutations or combinations don't work for you is because they don't allow items to repeat themselves; product calculates the cartesian product, which allows for repetition of items.
type: Answer
has comment: http://stackoverflow.com/comment/91339533
has comment: http://stackoverflow.com/comment/91339509

http://stackoverflow.com/comment/91442535
type: QuestionComment
has text: 2018 8 6 16:15 -84.05111884 9.9389431 1195.302 2018 8 6 16:20 -84.05111884 9.9389431 1195.302 thats the first few lines. the 2018 is copied on each line
comment on: http://stackoverflow.com/q/52247221
score: 0
type: Comment

http://stackoverflow.com/q/52136655
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91222965
tagged with: python
has body: I am using python 3.x. I am getting an error while running this code: from chatterbot.trainers import ListTrainer # method to train the chatbot from chatterbot import ChatBot # import the chatbot bot = ChatBot('Test') conv = open('chats.txt', 'r').readlines() bot.set_trainer(ListTrainer) # set the trainer bot.train(conv) # train the bot while True: request = input('You: ') response = bot.get_response(request) print('Bot: ', response) Error: module = self._system_import(name, *args, **kwargs) ModuleNotFoundError: No module named 'chatterbot.trainers'; 'chatterbot' is not a package How to fix this error?
score: 0
tagged with: chatterbot
has title: Chatterbot - No module named 'chatterbot.trainers' - python 3.x
type: Question
has comment: http://stackoverflow.com/comment/91224144
tagged with: chatbot
tagged with: python-3.x
answer count: 0

http://stackoverflow.com/q/52139309
has answer: http://stackoverflow.com/a/52369194
score: 2
has title: Connect python to Sybase IQ
has answer: http://stackoverflow.com/a/75317526
type: Question
upvote count: 2
answer count: 2
downvote count: 0
tagged with: sap-iq
has body: First of all thank you for your help. I was trying to retrieve some data from a sybase IQ database using python, but I can not make it. I've tried with the following code( from https://github.com/sqlanywhere/sqlanydb): import sqlanydb conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo' ) curs = conn.cursor() curs.execute("select 'Hello, world!'") print( "SQL Anywhere says: %s" % curs.fetchone() ) curs.close() conn.close() Unfotunately it gives me the following error: InterfaceError: ('Could not load dbcapi. Tried: None,dbcapi.dll,libdbcapi_r.so,libdbcapi_r.dylib', 0) Does anyone know how to fix it? Thanks in advance Jessica
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91408122
type: QuestionComment
comment on: http://stackoverflow.com/q/52229233
score: 0
type: Comment
has text: Any particular reason you're asking this? If you think you need objects to "persist in the background", the context is going to be very important for determining what you should actually do.

http://stackoverflow.com/a/52189868
has comment: http://stackoverflow.com/comment/91329565
has comment: http://stackoverflow.com/comment/91329670
downvote count: 0
has comment: http://stackoverflow.com/comment/91329734
has comment: http://stackoverflow.com/comment/91329515
has comment: http://stackoverflow.com/comment/91329591
has comment: http://stackoverflow.com/comment/91329532
answers question: http://stackoverflow.com/q/52167595
type: Answer
has comment: http://stackoverflow.com/comment/91329497
score: 2
upvote count: 2
has body: Since Python is a dynamic language, it is not possible for PyCharm to check whether this is valid or not using static inferrence. Consider the following: globals = lambda: {} globals().update({'variable': 'val'}) print(variable) # NameError: name 'variable' is not defined Now that you overshadowed globals, this is not valid code anymore and PyCharm has no way to know. The above being possible is a downside of dynamic languages: you cannot know if a program is valid before running it.
has comment: http://stackoverflow.com/comment/91329793

http://stackoverflow.com/a/52219376
accepted answer of: http://stackoverflow.com/q/52219340
answers question: http://stackoverflow.com/q/52219340
has body: This line is the culprit: entrynumbers = entrynumbers.append(data) list.append mutates the list it is called on, but returns None. So do not reassign, just do: entrynumbers.append(data) For Q1, Python list is not parametrized like collection types in other languages. Even if you add an intial TimeStamp object, you will still be able to add objects of any other type later on.
score: 5
type: AcceptedAnswer
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/91387152
downvote count: 0

http://stackoverflow.com/a/52121111
accepted answer of: http://stackoverflow.com/q/52120798
downvote count: 0
answers question: http://stackoverflow.com/q/52120798
type: Answer
has comment: http://stackoverflow.com/comment/91193693
has body: I would like it to wait till the search results load What you are looking for is a WebDriverWait (aka an "Explicit Wait"). You want to choose a specific element that signifies the results are loaded and wait for that. Suppose you are waiting for the presence of an element that can be located with the id of mySearchResults. The code would look like this. from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # create driver and execute search here # now wait for the presence of the `mySearchResults` element. # if it is not found within 10 secs, a `TimeOutException` is raised. WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "mySearchResults")))
score: 4
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/a/52268109
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52267929
type: Answer
upvote count: 1
has body: To use a pytest fixture, you must list it as an argument to your function: def test_http_client(event_loop, http_client): AsyncHTTPClient is not callable; it has a fetch method: resp = event_loop.run_until_complete(http_client.fetch(url)) What's happening in your code is that you're calling the fixture instead of letting pytest initialize it, and passing url as its tornado_server argument. Also consider using pytest-asyncio or pytest-tornado, which lets you use await instead of run_until_complete (this is the usual method of using pytest with tornado or asyncio): @pytest.mark.asyncio async def test_http_client(http_client): url = 'http://httpbin.org/get' resp = await http_client.fetch(url) assert resp.code == 200
score: 1
accepted answer of: http://stackoverflow.com/q/52267929
downvote count: 0

http://stackoverflow.com/a/58900251
type: Answer
answers question: http://stackoverflow.com/q/52127722
score: 0
has body: For me, the issue was using: random.seed = &lt;SOME INT&gt; along with any form of multiprocessing.

http://stackoverflow.com/q/52236463
has body: I have a 40 record df with roughly 100 columns. example: df id email phone first_name ...... 1 a@a.com 123 adam 2 b@b.com 456 bob Is there any way I can take a sample of each column and have python develop sample data based on the types of data in the columns? So the code auto generates fake id, email, and phone numbers. ideally, I can set the number of fake records I needed created, for example 2million rows are needed and I can appended the word fake into one of the columns like first_name. new df id email phone first_name ...... 1 a@a.com 123 adam 2 b@b.com 456 bob 3 c@c.com 789 fake_carly 4 c@c.com 789 fake_david
answer count: 1
score: 0
tagged with: pandas
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91424580
has comment: http://stackoverflow.com/comment/91423770
has comment: http://stackoverflow.com/comment/91423269
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52240504
has comment: http://stackoverflow.com/comment/91423218
accepted answer: http://stackoverflow.com/a/52240504
has title: How to create dummy records based on sample from dataframe?

http://stackoverflow.com/comment/91285440
comment on: http://stackoverflow.com/a/52167569
has text: This will probably do the trick, but will also sort on subsequent elements when there are duplicate values in the first column. If it is important to preserve the original order in the event of duplicate dates, then add `key=lambda row: row[0]`, or import operator and do `key=operator.itemgetter(0)`. This will sort *only* on the first column.
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91445008
comment on: http://stackoverflow.com/q/52237681
score: 0
has text: Right now I trying to use firefox. yes, the website works manually.@ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52243100
score: 0
has comment: http://stackoverflow.com/comment/94455187
has comment: http://stackoverflow.com/comment/94453141
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52242843
type: Answer
accepted answer of: http://stackoverflow.com/q/52242843
has comment: http://stackoverflow.com/comment/94468990
has body: Asuming you use the variable sudoku_numbers to store your array of numbers, then in the template you can use something like this: &lt;table&gt; {% for row in sudoku_numbers %} &lt;tr&gt; {% for col in row %} &lt;td&gt;{{ col }}&lt;/td&gt; {% endfor %} &lt;/tr&gt; {% endfor %} &lt;/table&gt;

http://stackoverflow.com/comment/91412170
score: 7
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52231326
has text: JS isn't minified to obfuscate it. It's minified to improve rendering times because of payload size.

http://stackoverflow.com/comment/115831011
comment on: http://stackoverflow.com/q/52269056
score: 0
has text: So, did you ever solve this?
type: Comment
type: QuestionComment

aws-lambda
tags question: http://stackoverflow.com/q/52121334
type: Tag
tags question: http://stackoverflow.com/q/52126169
tags question: http://stackoverflow.com/q/52248614
tags question: http://stackoverflow.com/q/52123401
tags question: http://stackoverflow.com/q/52253605
tags question: http://stackoverflow.com/q/52168279
tags question: http://stackoverflow.com/q/52205712
tags question: http://stackoverflow.com/q/52116896
tag name: aws-lambda
tags question: http://stackoverflow.com/q/52198569
tags question: http://stackoverflow.com/q/52268328
tags question: http://stackoverflow.com/q/52178711
tags question: http://stackoverflow.com/q/52198632
tags question: http://stackoverflow.com/q/52128075
tags question: http://stackoverflow.com/q/52129442
tags question: http://stackoverflow.com/q/52126116

user-interface
tags question: http://stackoverflow.com/q/52268699
tags question: http://stackoverflow.com/q/52199258
tags question: http://stackoverflow.com/q/52130203
tags question: http://stackoverflow.com/q/52128928
tags question: http://stackoverflow.com/q/52145586
tags question: http://stackoverflow.com/q/52234917
type: Tag
tags question: http://stackoverflow.com/q/52183500
tags question: http://stackoverflow.com/q/52210391
tags question: http://stackoverflow.com/q/52266674
tags question: http://stackoverflow.com/q/52159749
tags question: http://stackoverflow.com/q/52187616
tags question: http://stackoverflow.com/q/52140339
tags question: http://stackoverflow.com/q/52190498
tags question: http://stackoverflow.com/q/52184558
tags question: http://stackoverflow.com/q/52263142
tags question: http://stackoverflow.com/q/52177947
tags question: http://stackoverflow.com/q/52188071
tags question: http://stackoverflow.com/q/52211220
tag name: user-interface
tags question: http://stackoverflow.com/q/52174384
tags question: http://stackoverflow.com/q/52119287

http://stackoverflow.com/comment/91482551
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52266968
type: Comment
has text: you could provide a [mcve], why do not you check the background color and set a font color according to that case?

http://stackoverflow.com/a/52128053
has comment: http://stackoverflow.com/comment/91207091
upvote count: 2
answers question: http://stackoverflow.com/q/52127980
type: Answer
score: 2
downvote count: 0
has body: Your get_queryset() method returns None. Because instead of passing search in query string your are passing page=2. So, your search your variable is None. If the condition fails get_queryset() returning None. Put your return queryset.filter(title='no result found') outside the condition. def get_queryset(self): queryset = super().get_queryset() search = self.request.GET.get('search') if search: books_with_title = queryset.filter(title__icontains=search) if len(books_with_title) &gt; 0: return books_with_title books_with_author = queryset.filter(authors__name=search) if len(books_with_author) &gt; 0: return books_with_author books_with_publisher = queryset.filter(publisher__name=search) if len(books_with_publisher) &gt; 0: return books_with_publisher return queryset.filter(title='no result found')

http://stackoverflow.com/comment/91408990
comment on: http://stackoverflow.com/q/52229579
score: 0
type: Comment
type: QuestionComment
has text: Basically this is just not supported in json. How will you tell the difference between bytearrays and strings when loading data?

http://stackoverflow.com/a/52365010
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52226062
type: Answer
score: 1
upvote count: 1
has body: I have used the update_item to update each datapoint- After the inital update created as shown in question using the put_item, i have used the update_item to update the attributes. I have used for loop to pass the individual datapoints - ulist = datapoint1 table.update_item( Key={'name':'TableN'}, UpdateExpression= 'SET #datapoints = list_append(#datapoints,:val1)', ExpressionAttributeNames={'#datapoints': 'datapoints'}, ExpressionAttributeValues={':val1':ulist} )
answers question: http://stackoverflow.com/q/52226062

django-sites
type: Tag
tag name: django-sites
tags question: http://stackoverflow.com/q/52240758

http://stackoverflow.com/comment/91409685
type: Comment
has text: @JasonJones As for already having the wrapper objects and not calling the constructors, that part is trivial. If you don't understand how to set or modify the instance attribute `_fake_bases` on an existing object, you really shouldn't be coming anywhere near this kind of code.
comment on: http://stackoverflow.com/a/52229799
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91389641
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52220398
has text: If you say "after reading 2GB", do you mean that you have read 2GB of image files (size on disk) or that you prgram is using 2GB of memory at that point? Because if you have compressed images, they might get much larger when imported into memory
score: 1

http://stackoverflow.com/a/52123757
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52114689
has body: ok, this posts helped me out: Can&#39;t get rid of blank rows in csv output. Make these changes in setting.py file. FEED_EXPORTERS = { 'csv': 'your_project_name.exporters.FixLineCsvItemExporter', } Add paste the exporters.py file inside the spider folder where there is __init__ file. and bam, the output file doesnot contain blank rows.
downvote count: 0

http://stackoverflow.com/comment/91457205
has text: do you mean each date?
score: 0
comment on: http://stackoverflow.com/q/52254886
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91294943
type: QuestionComment
has text: I want to drop duplicated value.I tried using df2 = df1[~(df1['p_x'] == df1['p_y'])] But this does not work as the sorting/ order of column p_x and p_y are different.
comment on: http://stackoverflow.com/q/52171957
score: 0
type: Comment

http://stackoverflow.com/a/52242545
type: Answer
upvote count: 67
has comment: http://stackoverflow.com/comment/117731158
has comment: http://stackoverflow.com/comment/119104048
score: 67
has body: please look carefully at the indentation of your __init__ function: your forward is part of __init__ not part of your module.
downvote count: 0
answers question: http://stackoverflow.com/q/52241680

http://stackoverflow.com/q/52216489
has comment: http://stackoverflow.com/comment/91390833
has comment: http://stackoverflow.com/comment/91381674
has comment: http://stackoverflow.com/comment/91393563
has answer: http://stackoverflow.com/a/52217016
linked to: http://stackoverflow.com/q/39385971
tagged with: python
downvote count: 6
has comment: http://stackoverflow.com/comment/91381784
type: AnsweredQuestion
has body: Am taking a number from user &amp; I have to check whether given number is divisible by 3 or not. Does any know the best way then plz suggest. If my input is 26 then also it's showing Divisible #Using bitwise operator print('Entered number is divisible by 3 or not: ') intNumber = int( input('Enter number: ') ) if( intNumber &gt; 0 ): if( 3 &amp; (intNumber-1) ): print('Divisible') else: print('Not Divisible') else: print('Not is less than zero')
tagged with: bitwise-operators
type: Question
has comment: http://stackoverflow.com/comment/91382072
has comment: http://stackoverflow.com/comment/91381903
possible better answer: http://stackoverflow.com/a/52216761
has comment: http://stackoverflow.com/comment/91396002
linked to: http://stackoverflow.com/q/4432208
answer count: 2
accepted answer: http://stackoverflow.com/a/52217016
upvote count: 0
has comment: http://stackoverflow.com/comment/91382507
has answer: http://stackoverflow.com/a/52216761
score: -6
has title: How to know number is divisible by 3 or any odd number using bitwise operator in python
favorite count: 0
has comment: http://stackoverflow.com/comment/91381891

http://stackoverflow.com/q/52128526
has comment: http://stackoverflow.com/comment/91207526
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/52128555
has title: Python Caesar Cipher style program: Why does python give me TypeError of unsupported operand type(s)?
type: Question
has comment: http://stackoverflow.com/comment/91207524
score: -2
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91207554
accepted answer: http://stackoverflow.com/a/52128555
downvote count: 2
tagged with: python
has body: I am working on a project and am on my final stage of my project, but stuck on this error: Secret message: hello shift: 4 Traceback (most recent call last): File "program.py", line 5, in &lt;module&gt; next_code = code + str(move) TypeError: unsupported operand type(s) for +: 'int' and 'str' I have tried alternate solutions to this, but the plus sign is really bothering me. I am not too good at this stuff since i am a beginner, so i need some help, and i would also like to know how to make it that only uppercase characters are switched, and not the symbols. Here is my code: ask = input("Secret message: ") move = input("shift: ") for i in ask: code = ord(i) next_code = code + str(move) next_character = chr(next_code) print(next_character) Why am i getting this and what is my problem? Thanks in advance!

http://stackoverflow.com/a/52160101
score: 2
answers question: http://stackoverflow.com/q/52159977
type: AcceptedAnswer
downvote count: 0
has body: Can anyone point out what's wrong here? When you call it with add(1) then a is 1 (so not callable) and it will return 1. Next step: You'll have 1(2) but because 1 is not a callable this fails. Furthermore, how to resolve it? You cannot, because you would need to know when to end the recursion, but you only know if you need to go a level deeper after you completed the current step completely. So unfortunately your chosen approach will not work and you have to look for a different approach. That's where your link to the question about function chaining comes in.
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52159977

http://stackoverflow.com/comment/91232482
has text: But you have written "In the remote machine, there is no such user as "gimmi"". If there's no such user why do you have it in your connect string? You need to specify some valid user, perhaps "postgres", that exists on the remote machine DB
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52140789
type: Comment

http://stackoverflow.com/q/52195622
has comment: http://stackoverflow.com/comment/91344017
has title: how to find the outline of union rectangles
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52196273
has comment: http://stackoverflow.com/comment/91340896
has comment: http://stackoverflow.com/comment/91346557
favorite count: 0
has comment: http://stackoverflow.com/comment/91340938
has comment: http://stackoverflow.com/comment/91341132
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52196270
has comment: http://stackoverflow.com/comment/91341442
has body: I have coordinates of each rectangles and want to find the outlines of union rectangles. So what I did is that just drew and colored all rectangles with the coordinates. And found the contour of all rectangles. But I want to know that if there are some kind of algorithms doing the same thing only with coordinates information. So that I don't need to draw and color the whole rectangles. (there are more than 4000 rectangles so it is computationally expensive)
upvote count: 1
has comment: http://stackoverflow.com/comment/91343807
downvote count: 1
type: Question
tagged with: opencv

http://stackoverflow.com/comment/91419710
score: 0
has text: The **ImageMagick** command is not related to Python or Anaconda. It is just run from Terminal, or shell (or CMD.EXE on Windows).
comment on: http://stackoverflow.com/q/52234634
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52158126
has body: jwt.decode(..) expects the key value to be the actual secret in a text string, no encoding. It appears that your token was encoded with a routine that expected the secret was base64 encoded. It was just lucky that your secret, 'thingsboardDefaultSigningKey' happens to decode properly as base64. Change your call to: jwt.decode( token, b64decode('thingsboardDefaultSigningKey'), algorithms=['HS512'], options=jwt_options ) It will then decode without the exception.
type: Answer
score: 14
upvote count: 14
answers question: http://stackoverflow.com/q/52157576
accepted answer of: http://stackoverflow.com/q/52157576
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91470643
type: QuestionComment
has text: Please fix your formatting.
score: 4
comment on: http://stackoverflow.com/q/52261480
type: Comment

http://stackoverflow.com/q/52115655
has comment: http://stackoverflow.com/comment/91181993
has body: I'm trying to install python-snappy in Amazon Linux EC2 instance but I keep getting the below error, Any idea how to fix this issue: sudo python3.6 -m pip install python-snappy Collecting python-snappy Using cached https://files.pythonhosted.org/packages/89/fe/a81a219c183c7e578b6f82d9c2425df045548877be6559358e8560c1e9fd/python-snappy-0.5.3.tar.gz Installing collected packages: python-snappy Running setup.py install for python-snappy ... error Complete output from command /usr/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-e07ios_o/python-snappy/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-k7rd94ik/install-record.txt --single-version-externally-managed --compile: /usr/lib64/python3.6/distutils/dist.py:261: UserWarning: Unknown distribution option: 'cffi_modules' warnings.warn(msg) running install running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/snappy copying snappy/snappy_cffi.py -&gt; build/lib.linux-x86_64-3.6/snappy copying snappy/snappy_formats.py -&gt; build/lib.linux-x86_64-3.6/snappy copying snappy/snappy.py -&gt; build/lib.linux-x86_64-3.6/snappy copying snappy/__init__.py -&gt; build/lib.linux-x86_64-3.6/snappy copying snappy/snappy_cffi_builder.py -&gt; build/lib.linux-x86_64-3.6/snappy copying snappy/__main__.py -&gt; build/lib.linux-x86_64-3.6/snappy copying snappy/hadoop_snappy.py -&gt; build/lib.linux-x86_64-3.6/snappy running build_ext building 'snappy._snappy' extension creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/snappy gcc -pthread -Wno-unused-result -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/include/python3.6m -c snappy/snappym…
answer count: 0
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/91182034
tagged with: snappy
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Issue installing python-snappy
linked to: http://stackoverflow.com/q/11912878
score: 3

http://stackoverflow.com/comment/91515464
has text: Could you add example data into your question as text instead of images? We can't copy-paste from screenshots :P
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52267321
score: 0

http://stackoverflow.com/comment/91196972
comment on: http://stackoverflow.com/a/52122749
type: Comment
type: AnswerComment
has text: thanks it worked but i still get an error in my python program saying; `File "C:\Users\Sharjeel Jan\Desktop\Projects\Data Analysis\Data Analysis Project.py", line 6, in <module> import matplotlib.pylot as plt ModuleNotFoundError: No module named 'matplotlib.pylot'` what for be the reason for this error?
score: 0

http://stackoverflow.com/q/52175543
tagged with: z3py
type: Question
downvote count: 0
answer count: 1
favorite count: 0
has body: I'm encoding a scheduling problem with the Z3 solver using the z3py API. It works pretty well apart from the fact that the runtimes of the solver differs in time (sometimes by factor 10/100) in each run. What I often do if the solver takes too long, I just kill the query and restart it. It seems to me that the solver (for each run) takes a somehow different path to find a solution, which results in different run times. So my question is, whether I can force a solver to take the same(similar) path every time for the same set of constraints (problem)? After doing some research I stumbled upon the concept of setting a random seed manually. Would that help me? Is there any more info how to do that with the python api? best Jenny
tagged with: python
has title: Different run times for the same constraint set using Z3Py
type: UnansweredQuestion
upvote count: 1
tagged with: z3
has answer: http://stackoverflow.com/a/52176075
score: 1

http://stackoverflow.com/comment/91211767
type: AnswerComment
comment on: http://stackoverflow.com/a/52130579
score: 0
type: Comment
has text: although this isn't really what I'm trying to do lol. a list of factors isn't quite what's needed for totient function business...

http://stackoverflow.com/q/52154729
has comment: http://stackoverflow.com/comment/91265056
duplicate of: http://stackoverflow.com/q/26216875
type: UnansweredQuestion
tagged with: python
tagged with: parameter-passing
tagged with: subcommand
has comment: http://stackoverflow.com/comment/91260032
linked to: http://stackoverflow.com/q/27529610
answer count: 0
has body: For my toy project mpu I want to have the following commands: # Creates a Python project based on a template $ mpu init # Checks a Python project for style $ mpu stylecheck So let's say I have a command run_init() and a command run_stylecheck() and an argparse.ArgumentParser object called parser: def run_init(): print('init is executed') def run_stylecheck(): print('stylecheck is executed') def get_parser(parser=None): """Get parser for packaging part.""" from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter if parser is None: parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) subparsers = parser.add_subparsers(dest='subparser_name') pkg_init_parser = subparsers.add_parser('init') return parser get_parser().parse_args() How can I add those two commands to it? Restrictions Please no solutions that suggest to parse sys.argv manually and also not click. The first is not an option as it is too hard to extend, the second one is not an option as I specifically don't want to use external dependencies - although click is awesome. https://stackoverflow.com/a/27529806/562769 I think is also not an option as this will be a lot of different commands and the submodule providing the parser object will not be calling that object.
has title: Can I add a ArgumentParser to parse a subcommand?
has comment: http://stackoverflow.com/comment/91262517
type: Question
has comment: http://stackoverflow.com/comment/91263113
has comment: http://stackoverflow.com/comment/91259919
score: 0
tagged with: argparse
linked to: http://stackoverflow.com/q/26216875

http://stackoverflow.com/comment/91479450
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52265289
has text: @tado that question is a little ambiguous, depending on what you mean by "bounded to class". Maybe read up a little on Python scoping rules. If the question is not clear by then, you might have the tools to formulate it better.
type: AnswerComment

http://stackoverflow.com/a/52151731
type: AcceptedAnswer
downvote count: 0
has body: As I mentioned here, the use of Websockets in App Engine Flexible will be available soon, but, for Standard, it will need, at least, a year more. My post linked is related to .NET, but it's the same: no language available for either Flexible or Standard has access to websockets yet.
answers question: http://stackoverflow.com/q/52151602
accepted answer of: http://stackoverflow.com/q/52151602
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/comment/115300274
comment on: http://stackoverflow.com/a/52189465
type: Comment
score: 0
type: AnswerComment
has text: do we have to manually create the `myTempTable`?

http://stackoverflow.com/a/52191804
downvote count: 0
answers question: http://stackoverflow.com/q/52191396
score: 1
has body: I had to do a similar conversion but the other way, from python to java. I think that the buffer has bytes of data so the slices are access specific bytes and setting to variables. Sorry, I would have just commented but can't because don't have 50 reputation yet.
upvote count: 1
type: Answer

http://stackoverflow.com/a/52256768
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52256489
score: 7
upvote count: 7
has body: In django-1.8 some deprecated elements have been removed [Django-doc]: django.middleware.doc.XViewMiddleware will be removed. Use django.contrib.admindocs.middleware.XViewMiddleware instead. So in your MIDDLEWARE_CLASSES, you should replace it with: # settings.py MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.admindocs.middleware.XViewMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', ) In later versions MIDDLEWARE_CLASSES is renamed to MIDDLEWARE. If you upgrade the Django version, I advise you to check the deprecation page and make changes accordingly. Usually an item is marked deprecated two versions before it is removed. So it was marked deprecated in django-1.6.
answers question: http://stackoverflow.com/q/52256489
type: AcceptedAnswer

http://stackoverflow.com/comment/91263170
has text: Can you print the value of `bot.get_channel("channel id")`? Is it what you expect?
comment on: http://stackoverflow.com/q/52156410
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52161735
has comment: http://stackoverflow.com/comment/91438217
favorite count: 0
possible better answer: http://stackoverflow.com/a/56885654
has comment: http://stackoverflow.com/comment/91385061
tagged with: python
tagged with: logging
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91274877
has comment: http://stackoverflow.com/comment/91275424
upvote count: 3
has title: logging.warn() add stacktrace
has body: There are several logging.warn('....') calls in the legacy code base I am working on today. I want to understand the log output better. Up to now logging.warn() does emit one line. But this single line is not enough to understand the context. I would like to see the stacktrace of the interpreter. Since there are a lot of logging.warn('....') lines in my code, I would like to leave them like they are and only modify the configuration of the logging. How can I add the interpreter stacktrace to every warn() or error() call automatically? I know that logging.exception("message") shows the stacktrace, but I would like to leave the logging.warn() lines untouched.
has answer: http://stackoverflow.com/a/52222218
has comment: http://stackoverflow.com/comment/91438233
has comment: http://stackoverflow.com/comment/91438260
has comment: http://stackoverflow.com/comment/91275086
linked to: http://stackoverflow.com/q/45562594
has comment: http://stackoverflow.com/comment/91385424
type: Question
score: 3
has comment: http://stackoverflow.com/comment/91443526
has comment: http://stackoverflow.com/comment/91274525
tagged with: python-2.7
has answer: http://stackoverflow.com/a/56885654
answer count: 3
accepted answer: http://stackoverflow.com/a/52222218
has answer: http://stackoverflow.com/a/52265301
downvote count: 0

http://stackoverflow.com/a/52130816
accepted answer of: http://stackoverflow.com/q/52130574
has body: You need to associate the buttons with the functions you want to be executed when you press them. I use lambda to pass the specific name to the function call. Also; its more readable to use enumerate when you want a loop index. from tkinter import * main = Tk() prename = ["John", "Jack"] surname = ["Tompson", "Daniels"] def get_prename(n): # Callback function for prename buttons print(n) def get_surname(n): # Callback function for surname buttons print(n) for x, pn in enumerate(prename): pre = Button(main, text=pn, command=lambda pn=pn: get_prename(pn)) pre.grid(row=x, column=0) for y, sn in enumerate(surname): sur = Button(main, text=sn, command=lambda sn=sn: get_surname(sn)) sur.grid(row=y, column=1)
has comment: http://stackoverflow.com/comment/91212097
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91212131
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91212273
has comment: http://stackoverflow.com/comment/91212141
answers question: http://stackoverflow.com/q/52130574
has comment: http://stackoverflow.com/comment/91212210

http://stackoverflow.com/q/52158573
type: Question
has title: Sorting values and grepping the best score (highest number)
downvote count: 0
has answer: http://stackoverflow.com/a/52158872
answer count: 3
has body: I have just started learning Python and I need some help, tips or solution if anybody is willing to help. I have a file that looks like this: 2 C00000002 score: -48.649 nathvy = 49 nconfs = 3878 3 C00000001 score: -44.988 nathvy = 41 nconfs = 1988 4 C00000002 score: -42.674 nathvy = 49 nconfs = 6740 5 C00000002 score: -42.453 nathvy = 49 nconfs = 4553 6 C00000002 score: -41.829 nathvy = 49 nconfs = 7559 7 C00000002 score: -41.156 nathvy = 49 nconfs = 2251 8 C00000002 score: -39.520 nathvy = 49 nconfs = 3129 9 C00000004 score: -38.928 nathvy = 24 nconfs = 150 10 C00000002 score: -38.454 nathvy = 49 nconfs = 9473 11 C00000004 score: -37.704 nathvy = 24 nconfs = 156 12 C00000001 score: -37.558 nathvy = 41 nconfs = 51 My second column are some IDs that are not sorted here, some of them are repeating, such as (C00000001) for example. All of them have a different number assigned followed by score: (number most often starts with -). What I would like to do is: 1) read second column (non sorted IDs) and to always pick the first one that appears. So in case of C00000001 it would pick the on with score : -44.988. 2) now when I have unique values presented, I would like to sort them based on the number after score:, meaning the most negative number to be on the first position while the most positive one to be on the last position.
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/52158924
favorite count: 0
has answer: http://stackoverflow.com/a/52158966
has comment: http://stackoverflow.com/comment/91267334
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52158872
has answer: http://stackoverflow.com/a/52158924
has comment: http://stackoverflow.com/comment/91267226

http://stackoverflow.com/a/52312677
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52258446
has body: Here is the list from Microsoft which contains the values of each constant: https://learn.microsoft.com/en-us/office/vba/api/powerpoint.ppsaveasfiletype
downvote count: 0
type: Answer

http://stackoverflow.com/a/52230092
has body: to print a dict, you can format method. 1. iterate list of pets 2. pass dict to format method, 3. Note: make sure that you include name: pet_name in the dict. for pet in pets: print("Name: {name} Type: {type} Owner: {owner}".format(**pet))
answers question: http://stackoverflow.com/q/52230016
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/113281285
type: AnswerComment
comment on: http://stackoverflow.com/a/52191801
type: Comment
has text: @jitesh2796, see my answer to retain the height to width ratio.
score: 0

http://stackoverflow.com/comment/110303148
type: Comment
has text: Thank you. I was even considering to change the IDE due to this. Now I know, it was due to the overlapping plugins!!
comment on: http://stackoverflow.com/a/54528525
score: 0
type: AnswerComment

http://stackoverflow.com/a/52215481
downvote count: 0
has body: set has a dedicated method to find the intersection. Then you can iterate over the intersection and print each element. def print_common_members(a, b): """ Given two sets, print the intersection, or "No common elements". """ inter = a.intersection(b) if inter: # empty sets are Falsy, non empty sets are Truthy for elt in inter: print(elt) else: print("No common elements") a = {1, 2, 3} b = {2, 3, 4} c = {7, 8, 9} print_common_members(a, b) print() print_common_members(a, c) output: 2 3 No common elements
has comment: http://stackoverflow.com/comment/91379955
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91380084
answers question: http://stackoverflow.com/q/52215409

http://stackoverflow.com/a/52116036
accepted answer of: http://stackoverflow.com/q/52115732
has comment: http://stackoverflow.com/comment/91183046
answers question: http://stackoverflow.com/q/52115732
has comment: http://stackoverflow.com/comment/91182875
has comment: http://stackoverflow.com/comment/91182971
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91182888
has comment: http://stackoverflow.com/comment/91182923
has body: Use: idx = [3,5,9] idx_names = ['A','B','C'] d = dict(enumerate(idx_names)) #get boolean mask for create cumulative sum and filter out idx rows mask = df.index.isin(idx) df['g'] = mask.cumsum() #map by dictioanry df['g'] = df['g'].map(d) #create MultiIndex and change order of levels df = df[~mask].set_index('g', append=True).swaplevel(0,1) print (df) m n o g A 0 2 22 42 1 3 23 43 2 4 24 44 B 4 6 26 46 C 6 8 28 48 7 9 29 49 8 10 30 50
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91461360
has text: @jpp thank you for this, is it possible to take this further by splitting the 'ppt_negative' into two sets, one with '0' ppt, and the other containing values '>0' ppt? Basically, I am not interested in days when nothing happens...
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52256958

http://stackoverflow.com/comment/91283957
type: QuestionComment
has text: After doing feature detection using canny , can I do normalized-cut on that ? Can you give some examples @dhanushka
comment on: http://stackoverflow.com/q/52153979
score: 0
type: Comment

http://stackoverflow.com/a/52266495
has body: IIUC, You can try using swaplevel followed by sort_index: df.set_index('symbol', append=True).swaplevel().sort_index(level=[0,1],ascending=[False,True]) high low symbol Date spy 2017-07-17 245.910004 245.330002 2017-07-18 245.720001 244.669998 2018-08-16 285.040009 283.359985 2018-08-17 285.559998 283.369995 nflx 2018-08-16 331.170013 321.209991 2018-08-17 324.369995 312.959991
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52266462
answers question: http://stackoverflow.com/q/52266462
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/91243721
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52146661
score: 0
has text: My comment still stands. Sometimes the separator is `,`, sometimes it's `, `. I don't know if this was an error in your question or something that requires handling.

http://stackoverflow.com/q/52240065
has body: I need to check that the same port isn't used in two sub-dictionaries. my_dict: first: redis: port: 1234 second: redis: port: 1235 third: redis: port: 1234 In a task I can use the following: - debug: msg: '' This returns: ['1234', '1235', '1234'] What I need, is some way to filter only the duplicates. So I get: ['1234', '1234'] Returned. Basically, I need to check that the ports aren't duplicated, and if they are apply a fail task that checks, and shows which items are causing the conflict. Any ideas?
answer count: 2
tagged with: python
tagged with: jinja2
has title: FIND duplicates in Ansible Dictionary
tagged with: ansible
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52240364
has answer: http://stackoverflow.com/a/52244101
has comment: http://stackoverflow.com/comment/91428948
has comment: http://stackoverflow.com/comment/91428882
type: Question
score: 0

http://stackoverflow.com/q/52138904
tagged with: django
tagged with: python
tagged with: http
type: Question
has answer: http://stackoverflow.com/a/52143574
score: 0
answer count: 1
has title: Django send progress back to client before request has ended
type: UnansweredQuestion
tagged with: sockets
has body: I am working on an application in Django where there is a feature which lets the user share a download link to a public file. The server downloads the file and processes the information within. This can be a time taking task therefore I want to send periodic feedbacks to the user before operations has completed. For instances, I would like to inform the user that file has downloaded successfully or if some information was missing from one of the record e.t.c. I was thinking that after the client app has sent the upload request, I could get client app to periodically ask the server about the status. But I don't know how can I track the progress a different request.How can I implement this?

http://stackoverflow.com/a/52207544
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52207345
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52207345
has body: I would do something similar to the answer you linked but I would define it within the class itself. from functools import wraps def _emergency_disconnect(the_func): @wraps(the_func) def wrapper(*args, **kwargs): output = None try: output = the_func(*args, **kwargs) except: #args[0] will always be self args[0].client.disconnect() if output != None: return output return wrapper Then you can decorate your functions with it @_emergency_disconnect def myFunction(myArg): pass This will cause self.client.disconnect() to be called whenever a method call results in an error.

ctypes
tags question: http://stackoverflow.com/q/52139846
tags question: http://stackoverflow.com/q/52139683
tag name: ctypes
type: Tag
tags question: http://stackoverflow.com/q/52204971
tags question: http://stackoverflow.com/q/52202403
tags question: http://stackoverflow.com/q/52179325
tags question: http://stackoverflow.com/q/52250332
tags question: http://stackoverflow.com/q/52179621
tags question: http://stackoverflow.com/q/52127217
tags question: http://stackoverflow.com/q/52134482
tags question: http://stackoverflow.com/q/52268294

http://stackoverflow.com/comment/91488767
score: 0
type: Comment
has text: Thank you very much for the enlightenment on the source of my problem. I decided to use averaging for every 7 rows, as described in this link:`https://stackoverflow.com/questions/36810595/calculate-average-of-every-x-rows-in-a-table-and-create-new-table`, instead of using weekofyear.
comment on: http://stackoverflow.com/a/52269671
type: AnswerComment

http://stackoverflow.com/q/52169226
has comment: http://stackoverflow.com/comment/91456624
tagged with: pdb
has comment: http://stackoverflow.com/comment/91433820
upvote count: 5
downvote count: 0
type: UnansweredQuestion
has title: How to make readline work in a python subprocess?
tagged with: serverless-framework
has comment: http://stackoverflow.com/comment/91370088
linked to: http://stackoverflow.com/q/543196
tagged with: python
tagged with: readline
favorite count: 0
has body: I have spent quite something enabling readline support in pdb on MacOS Sierra in a subprocess which I don't understand why it fails, hence the question. Please note that I have proper readline support without adding a .pdbrc file in all my python environemnts, including python2 and 3 installations and also in virtual environments created with pipenv, venv, or pew. All work just fine. The problem arises when I want to drop into a pdb shell in a subprocess. I use a nodejs program along with a plugin which I use to invoke AWS code locally. The first nodejs process starts the second and the second one starts a python process which I have my usual pdb code in it: import pdb; pdb.set_trace() However the pdb shell that I get has no readline support. I tried the following alternatives which didn't work as well: import ipdb; ipdb.set_trace() import rlcompleter, readline readline.parse_and_bind('tab: complete') readline.parse_and_bind('bind ^I rl_complete') I also added .pdbrc file with above content (minus ipdb import) to no avail. I tried also setting PYTHONSTARTUP point to a file with this content: import rlcompleter, readline readline.parse_and_bind('tab: complete') It didn't help too. People had reported that these solutions have worked for them, but they didn't have readline support to start with (which for me it works just fine without these tricks). I also tried patching my nodejs process.env.PATH and process.env.PYTHONPATH and added directories where I have python installation which have readline support to no avail. I appreciate if anybody can explain whether there is a fundamental difference between launching pdb from a sub-sub-...-process and directly from terminal (which in anycase it is a subprocess too). Moreover, I appreciate any suggestion that might help me solve this problem. Update I I noticed that even without pdb I don't get the readline support: import code code.interact(local=locals()) If I run the above code I get a python shell without readline suppo…
has comment: http://stackoverflow.com/comment/91433859
tagged with: subprocess
type: Question
has comment: http://stackoverflow.com/comment/91449153
score: 5
has answer: http://stackoverflow.com/a/52310520
answer count: 1
has comment: http://stackoverflow.com/comment/91567758
has comment: http://stackoverflow.com/comment/91385657
has comment: http://stackoverflow.com/comment/91457176
has comment: http://stackoverflow.com/comment/91433885

http://stackoverflow.com/q/52229523
has comment: http://stackoverflow.com/comment/91408741
tagged with: string
has body: I am creating a function in Python to calculate the length of a string, while letting the user know that Int and float is not a string. The Int section works, however the function does not respect the float and I do not know why. I am using visual Studio Code in Windows 10. Python 3.7.0 [MSC v.1914 64 bit (AMD64)] on win32 def length_string(mystring): try: if type(int(mystring)) == int: return f"Hello, this is not {mystring} a string" elif type(mystring) == float: return f"Hello, this is not {mystring} a string" elif type(str(mystring)) == str: return len(mystring) except: return len(mystring) string_name = input("Please enter your value: ") print(length_string(string_name))` Result String Hello is: 5 Result Int 555 = Hello, this is not 555 a string Result Float 555.0 = 5, but should be the same as the int.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91408728
has comment: http://stackoverflow.com/comment/91408774
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91408621
has title: Python program should not calculate float length, only string
has answer: http://stackoverflow.com/a/52229562
tagged with: string-length
has answer: http://stackoverflow.com/a/52229753
score: 0
tagged with: calculator

http://stackoverflow.com/q/52149525
duplicate of: http://stackoverflow.com/q/30791936
has comment: http://stackoverflow.com/comment/91249486
has comment: http://stackoverflow.com/comment/91249084
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91249499
tagged with: regex
has title: Python regex - zero length matches using re.findall() v/s clean groups in regex101.com
has body: Why do I get zero length matches when using re.findall() and get none of those when evaluating the pattern on regex101: text: Relatie f. dsgfsdg\n Factuur 26427432\n Machtiging 436346y435643yerhg\n IncassantID 4ty43y643erhgerh\n Onderwerp Uw factuur\n Datum 25 mei 2014\n local (jupyter notebook): re.findall('(Factuur)(\s+)(\d+)|(Datum)(\s+)(\d+\s+\w+\s+\d+)', content) [('Factuur', ' ', '2423828', '', '', ''), ('', '', '', 'Datum', ' ', '25 mei 2014')] regex101.com: r"(Factuur)(\s+)(\d+)|(Datum)(\s+)(\d+\s+\w+\s+\d+)"
type: Question
linked to: http://stackoverflow.com/q/30791936
has comment: http://stackoverflow.com/comment/91249471
has comment: http://stackoverflow.com/comment/91249651
has comment: http://stackoverflow.com/comment/91249657
score: 0

http://stackoverflow.com/comment/91221944
comment on: http://stackoverflow.com/a/52136064
has text: this will only fix if they enter func([20,'a',40,60])
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/a/52175896
type: Answer
has body: The following does the job but writes the certificate to file. Is it possible to decode the certificate directly and avoid saving it to a file? import ssl, socket myhostname = 'some_host' myctx = ssl.create_default_context() myctx.check_hostname = False myctx.verify_mode = ssl.CERT_NONE s = myctx.wrap_socket(socket.socket(), server_hostname=myhostname) s.connect((myhostname, 443)) bcert = s.getpeercert(binary_form=True) cert = ssl.DER_cert_to_PEM_cert(bcert) # workaround, ssl._ssl._test_decode_cert method expects a filename f = open('mycert.pem','w') f.write(cert) f.close() cert_dict = ssl._ssl._test_decode_cert('mycert.pem') # expects a filename? subject = dict(x[0] for x in cert_dict['subject']) issued_to = subject['commonName'] issuer = dict(x[0] for x in cert_dict['issuer']) issued_by = issuer['commonName'] print(issued_to) print(issued_by) EDIT more simply, but still writes to file import ssl myhostname = 'some_host' FILE = 'cert.pem' with open(FILE, 'w', encoding='utf8') as fp: fp.write(ssl.get_server_certificate((myhostname, 443))) cert_dict = ssl._ssl._test_decode_cert(FILE)
answers question: http://stackoverflow.com/q/52175088
score: 5
upvote count: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52175088

http://stackoverflow.com/q/52226943
type: UnansweredQuestion
tagged with: python
has body: I am trying to update an already saved form on a system using HTTP requests. Due to the server configuration for the third party app we use, updating by POST requires sending a fully filled out payload every single time. I want to get round this by recovering the form data already present on the server and converting it into a dictionary. Then changing any values I need and reposting to make changes sever side. The application we use sends a POST request when the save button is clicked for a particular form. Here I send a post request with no payload. [This simulates pressing the save button and is also the point where dev tools shows me a the payload I want to capture] post_test = self.session.post(url_to_retrieve_from) I thought that now I should be able to print the output, which should resemble what Google Dev tools Form data captures. print(post_test.text) This just gives me html found on the webpage. If Dev Tools can get this from the server then I should also be able to? Example of Data I am trying to get via requests: Form Data
downvote count: 0
score: 1
tagged with: python-requests
tagged with: http
type: Question
tagged with: automation
upvote count: 1
answer count: 1
has title: Python Requests Programmatically get Dev Tools Form Data pre-formatted as a dictionary
favorite count: 0
has answer: http://stackoverflow.com/a/52227885

http://stackoverflow.com/comment/91208925
has text: I don't need encodings in script file then why should I?
comment on: http://stackoverflow.com/a/52129286
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/52126444
has body: linear/linear_model/bias_weights are your trained model weights. linear/linear_model/bias_weights/part_0/Adagrad comes from you using the AdaGrad optimizer. The special feature of this optimizer is that it keeps a "memory" of past gradients and uses this to rescale the gradients at each training step. See the AdaGrad paper if you want to know more (very mathy). The important part is that linear/linear_model/bias_weights/part_0/Adagrad stores this "memory". It is returned because it is technically a tf.Variable in your program, however it is not an actual variable/weight in your model. Only linear/linear_model/bias_weights is. Of course the same holds for linear/linear_model/pixels/weights.
accepted answer of: http://stackoverflow.com/q/52126000
score: 0
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91204077
answers question: http://stackoverflow.com/q/52126000

http://stackoverflow.com/comment/91258481
has text: @Nummer_42O I actually solved that in a bit different way - u can see that in the code. Easily added break, cuz i didnt need whole table (that was just for me). So it is going to stop in the row where the kw "ADMINS" is.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52150701

http://stackoverflow.com/comment/91419291
score: 0
type: QuestionComment
has text: If you're looking for a way to check if the regex matches the whole string, give the `\A`, `\Z`, `\z`, `^` and `$` anchors a look. https://www.regular-expressions.info/refanchors.html
type: Comment
comment on: http://stackoverflow.com/q/52235073

http://stackoverflow.com/a/52126143
answers question: http://stackoverflow.com/q/52117156
type: Answer
upvote count: 1
has body: You are trying to upload binary files (word, jpg), serialised as JSON, and store them on the server. To handle binary data in JSON, encode the binary data as base64 first, then call JSON.stringify. Like this (untested): function uploadFile(fileContent, fileName) { // Encode the binary data to as base64. const data = { fileContent: btoa(fileContent), fileName: fileName }; axios.post('http://localhost:8080/api/uploadFile', JSON.stringify(data)); } On the server side, you need to deserialise from JSON, decode the base64 and the open a file in binary mode to ensure that what you are writing to disk is the uploaded binary data. Opening the file in text mode requires that the data be encoded before writing to disk, and this encoding step will corrupt binary data. Something like this ought to work: class UploadFileHandler(tornado.web.RequestHandler): def post(self): requestBody = tornado.escape.json_decode(self.request.body) # Decode binary content from base64 binary_data = base64.b64decode(requestBody[fileContent]) # Open file in binary mode with open(requestBody["fileName"], "wb") as f: f.write(binary_data)
has comment: http://stackoverflow.com/comment/91232593
has comment: http://stackoverflow.com/comment/91342376
score: 1
accepted answer of: http://stackoverflow.com/q/52117156
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91289924
has text: I downvoted because it's grossly inefficient and is a terrible example of how to write Python code, not because it failed to reach some Pythonic ideal.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52169666

http://stackoverflow.com/comment/91432115
comment on: http://stackoverflow.com/q/52241792
type: Comment
type: QuestionComment
score: 2
has text: You can't. A column has a single datatype. You can't represent letters as a number, so that datatype can't be numeric.

http://stackoverflow.com/a/52149055
answers question: http://stackoverflow.com/q/52147785
score: 2
downvote count: 0
upvote count: 2
type: Answer
has body: This documents the operator&gt;&gt; overload you're currently using: template&lt;class CharT, class Traits&gt; basic_istream&lt;CharT,Traits&gt;&amp; operator&gt;&gt;(basic_istream&lt;CharT,Traits&gt;&amp; st, CharT* s); which in reality means roughly basic_istream&lt;char&gt;&amp; operator&gt;&gt;(basic_istream&lt;char&gt;&amp; st, char* s); (where you call it with st = cin and s = msg). The documentation says this overload ... extracts successive characters and stores them at successive locations of a character array whose first element is pointed to by s but s (or msg) doesn't point to an array where you can store those characters. It's uninitialized, and storing anything in there without initializing it to point at some valid location is Undefined Behaviour. This overload is not recommended anyway, because you can't use it safely. You don't know in advance how many bytes will be read, which means you can't choose a safe size for the array to store them in. Using the std::string overload instead allows the string class to take care of storing however many bytes are read, because std::string (unlike a plain array) can grow itself as required.

http://stackoverflow.com/comment/91465527
comment on: http://stackoverflow.com/q/52259027
type: QuestionComment
type: Comment
has text: You write the path as *content*, not the content of the file...
score: 1

http://stackoverflow.com/comment/91311567
score: 0
type: Comment
has text: At https://regex101.com/r/VIVCVw/1 you can see that your group 1 is missing the closing parentheses.
type: QuestionComment
comment on: http://stackoverflow.com/q/52180653

http://stackoverflow.com/comment/91205985
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52127546
type: Comment
has text: Yes I run it without any error...I don't know why it's not working

http://stackoverflow.com/a/52338772
accepted answer of: http://stackoverflow.com/q/52154611
has body: I was correct in assuming it was not something I could do with that element type. I found out a unique property in the element that was returned (an id) and did a driver.find_element_by_id on it : unexpanded_span_element = driver.find_element_by_id(tables_to_expand[len(tables_to_expand)-1]['id']) unexpanded_span_element.click()
has comment: http://stackoverflow.com/comment/99527979
type: Answer
has comment: http://stackoverflow.com/comment/99452832
has comment: http://stackoverflow.com/comment/99487731
score: 0
answers question: http://stackoverflow.com/q/52154611
has comment: http://stackoverflow.com/comment/99487434
type: AcceptedAnswer

http://stackoverflow.com/q/52264233
score: 30
has comment: http://stackoverflow.com/comment/91477077
has comment: http://stackoverflow.com/comment/91476397
has answer: http://stackoverflow.com/a/52264392
has comment: http://stackoverflow.com/comment/138939202
tagged with: mypy
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/33945261
has title: Return None from python function annotated with mypy, multiple return types
has comment: http://stackoverflow.com/comment/91476664
linked to: http://stackoverflow.com/q/36797282
type: Question
accepted answer: http://stackoverflow.com/a/52264392
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 30
has body: I come from a Typescript background. I'm bringing static type checking into a python project I'm working on (using mypy). In Typescript, it is valid to return null from a function that is annotated to return something else, i.e. a string: function test(flag: boolean): string { if(flag) { return 'success'; } else { return null; } } It is also valid to annotate your function to have multiple potential return types, i.e. string or boolean: function test(flag: boolean): string | boolean { if(flag) { return 'success'; } else { return false; } } But, in python using mypy, I'm disallowed from returning None from a function that is annotated to return str. def test(flag: bool) -> str: if flag: return 'success' else: return None # [mypy] error:Incompatible return value type (got "None", expected "str") Furthermore, I don't see a way to annotate multiple return types, i.e. str | None. How should I approach something like this using mypy? Functions that return None from the error state are all over my codebase.
tagged with: python
tagged with: python-typing

http://stackoverflow.com/comment/91385124
type: QuestionComment
comment on: http://stackoverflow.com/q/52218288
score: 0
has text: Try `apt-get install libx264-dev`. If not works, build and install from source.
type: Comment

http://stackoverflow.com/a/52135978
has comment: http://stackoverflow.com/comment/91221934
has comment: http://stackoverflow.com/comment/91221846
type: Answer
has comment: http://stackoverflow.com/comment/91221914
accepted answer of: http://stackoverflow.com/q/52135821
answers question: http://stackoverflow.com/q/52135821
type: AcceptedAnswer
score: 0
has body: You are increasing your total line count incrementally with each processed line. Read in the full file into a list, then process the list. While processing the list, increase a counter thats "the current lines nr" and pass it to the output function as well. The len() of your list is the total line count you can set to self.line_count: def start(self): with open(self.usersfile, 'rt') as f: allLines = f.readlines() self.line_count = len(allLines) currLine = 0 for line in allLines: currLine += 1 # do what you need to do, do not increment self.line_count self.check_account(username, currLine) # extend your printmethod to take the # currLine nrand print that instead # of self.count # simplified def check_account(self,username,currLine): print ("{} {}/{}".format(username,currLine,self.line_count) )
has comment: http://stackoverflow.com/comment/91221892

http://stackoverflow.com/q/52157535
has comment: http://stackoverflow.com/comment/91265911
answer count: 2
has title: Is there a Pythonic way to run async task in background similar to using a contextmanager?
has answer: http://stackoverflow.com/a/63419080
has answer: http://stackoverflow.com/a/52161552
tagged with: contextmanager
has comment: http://stackoverflow.com/comment/91265772
tagged with: async-await
has comment: http://stackoverflow.com/comment/91266068
accepted answer: http://stackoverflow.com/a/63419080
possible better answer: http://stackoverflow.com/a/52161552
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91265710
score: 6
favorite count: 0
type: Question
tagged with: python-asyncio
has comment: http://stackoverflow.com/comment/91265879
has comment: http://stackoverflow.com/comment/91265639
tagged with: python
has body: Recently I wanted to run some asynchronous tasks in the background while running other tasks but I didn't think the code was Pythonic enough: task = asyncio.create_task(long_task()) await short_task() await task So I made it more Pythonic: @asynccontextmanager async def run_in_background(coro): task = asyncio.create_task(coro) yield task await task async def main(): async with run_in_background(long_task()): await short_task() Does something like this already exist? If not is this considered more Pythonic or less Pythonic than the existing way?
upvote count: 6

http
tags question: http://stackoverflow.com/q/52117533
tags question: http://stackoverflow.com/q/52212370
tags question: http://stackoverflow.com/q/52113037
tags question: http://stackoverflow.com/q/52184936
tags question: http://stackoverflow.com/q/52226943
tags question: http://stackoverflow.com/q/52174367
tag name: http
tags question: http://stackoverflow.com/q/52239491
tags question: http://stackoverflow.com/q/52156945
tags question: http://stackoverflow.com/q/52267189
type: Tag
tags question: http://stackoverflow.com/q/52209941
tags question: http://stackoverflow.com/q/52139165
tags question: http://stackoverflow.com/q/52257044
tags question: http://stackoverflow.com/q/52138904
tags question: http://stackoverflow.com/q/52248600

http://stackoverflow.com/a/52124109
has comment: http://stackoverflow.com/comment/136264357
type: Answer
downvote count: 0
score: 19
answers question: http://stackoverflow.com/q/52123892
upvote count: 19
has body: This isn't so much a question about the Python is operator, as about what indexing, or unboxing, an element of an array does: In [363]: a = np.array([1, 2, np.nan, 3]) In [364]: a[2] Out[364]: nan In [365]: type(a[2]) Out[365]: numpy.float64 In [366]: a[2] is a[2] Out[366]: False a[2] doesn't simply return nan. It returns a np.float64 object whose values is np.nan. Another a[2] will produce another np.float64 object. Two such objects don't match in the is sense. That's true for any array element, not just nan values. Since == doesn't work for nan, we are stuck with using the np.isnan function. np.nan is a unique float object (in this session), but a[2] is not set to that object. If the array was defined as an object type: In [376]: b = np.array([1, 2, np.nan, 3], object) In [377]: b[2] is np.nan Out[377]: True here the is is True - because b contains pointers to objects that already exist in memory, including the np.nan object. Same would be true for a list constructed like that.
accepted answer of: http://stackoverflow.com/q/52123892
type: AcceptedAnswer

http://stackoverflow.com/q/52262308
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91576520
has comment: http://stackoverflow.com/comment/91575036
has comment: http://stackoverflow.com/comment/91545069
has comment: http://stackoverflow.com/comment/91575548
tagged with: autograd
type: Question
has comment: http://stackoverflow.com/comment/91575323
has answer: http://stackoverflow.com/a/52314171
has comment: http://stackoverflow.com/comment/91555184
has comment: http://stackoverflow.com/comment/91575114
has body: I am trying to replicate this standard example using Autograd package. While I am able to replicate other examples from this repository, this particular example throws an error as follows: /home/avuis/anaconda/lib/python3.6/sitepackages/autograd/numpy/numpy_vjps.py:444: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result. return lambda g: g[idxs] Is this related version incompatibility? If so, any quick ways to fix this? Thanks in advance,
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91575730
has title: Gradient using Autograd package in Python

http://stackoverflow.com/q/52119110
type: Question
has answer: http://stackoverflow.com/a/52119348
score: 0
answer count: 1
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/91189505
tagged with: python
has body: This is the html Facilities for Interactive white board or other audio visual display Holland Blinds to external windows. I just need each li in e variable Here is my code tag = soup.find('div', attrs={'class':'field--name-field-rdp-fc-sf-body'}) ultag = tag.find('ul') for i in ultag: e = i.find('li') print(e)
type: AnsweredQuestion
has title: How to loop li tags under ul tags?
accepted answer: http://stackoverflow.com/a/52119348
has comment: http://stackoverflow.com/comment/91189267

http://stackoverflow.com/q/52235697
has comment: http://stackoverflow.com/comment/91420755
type: Question
tagged with: matplotlib
has title: pandas groupby plot values
answer count: 1
has answer: http://stackoverflow.com/a/52235989
score: 0
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/52235989
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91420690
has body: I have a pandas dataframe that looks like this: **real I SI weights** 0 1 3 0.3 0 2 4 0.2 0 1 3 0.5 0 1 5 0.5 1 2 5 0.3 1 2 4 0.2 1 1 3 0.5 I need to divide it by "real", then I need to do the following: given a value of I, consider each value of SI and add the total weight. At the end, I should have, for each realization, something like that: real = 0: I = 1 SI = 3 weight = 0.8 SI = 5 weight = 0.5 I = 2 SI = 4 weight = 0.2 real = 1: I = 1 SI = 3 weight = 0.5 I = 2 SI = 5 weight = 0.3 SI = 4 weight = 0.2 The idea is then to plot, for each value of I and real, on the x axis the values of SI and on the y axis the relative total weight (normalized to 1). What I tried to do was this: name = ['I', 'SI','weight', 'real'] Location = 'Simulationsdata/prova.csv' df = pd.read_csv(Location, names = name,sep='\t',encoding='latin1') results = df.groupby(['I', 'real', 'SI']).weight.sum() When I print results, I have the table I want, but now I don`t know how to make a plot as I wanted, because I do not know how to get the SI values...

http://stackoverflow.com/q/52195378
answer count: 1
tagged with: docker
tagged with: environment-variables
score: 1
has body: I am setting the GOOGLE_APPLICATION_CREDENTIALS environment variable from within my docker-compose.yml file. This is the structure of my docker-compose.yml file: version: "2" services: server: container_name: server environment: - GOOGLE_APPLICATION_CREDENTIALS=/dir1/dir2/file1.json My JSON file is present in the above directory. From my python code, which is also run as part of Docker container, I am using Google Speech API like this: import io from google.cloud import speech from google.cloud.speech import enums from google.cloud.speech import types #take speech wav file and turn it into text. return text def transcribe_file(speech_file): """Transcribe the given audio file.""" client = speech.SpeechClient() When I execute above it throws error that google.auth.exceptions.DefaultCredentialsError: File /dir1/dir2/file1.json was not found. I am unable to understand why it is not able to find the JSON when it is present in the correct directory.
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52195390
has title: file not found error when setting the environment variable in docker compose yml file
tagged with: docker-compose
type: Question
tagged with: google-cloud-speech
downvote count: 0

http://stackoverflow.com/q/52207198
possible better answer: http://stackoverflow.com/a/52207425
score: 0
answer count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/52207379
has body: In git, I run git shortlog -sn to build a list of authors &amp; their commits in a repo. In some cases, multiple authors are actually the same person but with different case or first name instead of first+last. Example: $ git shortlog -sn 100 John Doe 50 john Using subprocess in my Python script to execute this command, I eventually parse it into a dictionary. As an example, it would be like this: &gt;&gt;&gt; users = {"John Doe": 100, "john": 50} &gt;&gt;&gt; users {'John Doe': 100, 'john': 50} I need to loop through these and run a regex on the keys to compare whether 2 names start with the same first name (regardless of case) and: Combine the keys to show the different author names Sum the commits (value) of each element. So the end result should be: {'John Doe, john': 150} I could probably come up with some crude implementation for this, but it wouldn't be very pythonic. Looking for a clean and simple implementation.
accepted answer: http://stackoverflow.com/a/52207379
has comment: http://stackoverflow.com/comment/91364439
tagged with: python
has answer: http://stackoverflow.com/a/52207425
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91364576
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91363660
has title: In python, how do I merge dictionary elements with similar keys?

http://stackoverflow.com/q/52129054
upvote count: 1
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/52167676
has title: Is callback function in RabbitMQ, pika basic_consume is executed in blocking manner (one by one)?
tagged with: message-queue
answer count: 1
favorite count: 0
has body: I am very new to RabbitMQ so I was checking through tutorial (http://www.rabbitmq.com/tutorials/tutorial-one-python.html) In this tutorial, we use pika connection channel's basic_consume function for consuming messages. As documentation of basic_consume(https://pika.readthedocs.io/en/0.10.0/modules/channel.html) states, it obviously consumes message but my question is, in which manner the callback function is executed? In next part of tutorial (http://www.rabbitmq.com/tutorials/tutorial-two-python.html) we can check that single thread cannot call two callback functions simultaneously (as we run example code, sleeping messages appear one by one per thread.) But this is not guaranteed in any of documentations (as I found.) What I want is exactly like this (for single thread only one callback function is called, message being handled one by one.) but I want to make sure that basic_consume operates this way. I also think this is obvious (because we need multi-thread for handling multiple callback functions simultaneously) but I am still little confused... Thanks!
tagged with: python
tagged with: rabbitmq
has answer: http://stackoverflow.com/a/52167676
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/52136049
type: Answer
has body: If the pages are interconnected with hyperlinks from the page at the root, you can easily spider the site by following internal links. This would require you to load the root page, parse its hyperlinks, load those pages and repeat until no new links are detected. You will need to implement cycle detection to avoid crawling pages you have already crawled. Spiders are not trivial to operate politely; many sites expose metadata through robots.txt files or otherwise to indicate which parts of their site they do not wish to be indexed, and they may operate slowly to avoid consuming excessive server resource. You should respect these norms. However, do note that there is no general purpose way to enumerate all pages if they are not explicitly linked from the site. To do so would require: that the site enables directory listing, so you can identify all files stored on those paths. Most sites do not provide such a service; or cooperation with the operator of the site or the web server to find all pages listed under those paths; or a brute-force search of all possible URLs under those paths, which is an effectively unbounded set. Implementing such a search would not be polite to the operator of the site, is prohibitive in terms of time and effort, and cannot be exhaustive.
score: 1
accepted answer of: http://stackoverflow.com/q/52135929
upvote count: 1
answers question: http://stackoverflow.com/q/52135929
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91266896
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52158389
has text: `word = "something else"` does not create a new variable with the same name as the existing variable. It rebinds the existing variable. Rebinding that variable just doesn't do anything to the list.
type: AnswerComment

http://stackoverflow.com/q/52180055
favorite count: 0
type: UnansweredQuestion
tagged with: pickle
tagged with: python
score: 3
has answer: http://stackoverflow.com/a/52180535
has title: How to load a pickle by pandas not from the file
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/91326555
tagged with: pandas
answer count: 1
downvote count: 0
has body: since previously the code: def read_pickle_packet(self, sf): body = self._read_payload(sf) return pickle.load(body) has an error:ImportError: No module named indexes.base. which was caused by the pandas version inconsistent between server and client. I solve the problem by changing the code like this: def read_pickle_packet(self, sf): body = self._read_payload(sf) filehandler = open("tempFile.pkl", 'w') filehandler.write(body) filehandler.close() return pd.read_pickle("tempFile.pkl") It can solve the problem. But my question is there any more quick way to load the pickle object rather than store it into filesystem and then read it. It cost time and memory.But i could not found some clue by google "pandas read pickle from object". Thank you for any suggestion.

http://stackoverflow.com/a/52253487
upvote count: 2
has body: I believe need to add sales after groupby, if necessary add fill_value=0 to unstack for replace NaNs to 0: df.groupby(['year','sales'])['sales'].mean().unstack(fill_value=0).plot()
has comment: http://stackoverflow.com/comment/91455121
has comment: http://stackoverflow.com/comment/91454651
type: Answer
has comment: http://stackoverflow.com/comment/91454774
has comment: http://stackoverflow.com/comment/91454497
downvote count: 0
has comment: http://stackoverflow.com/comment/91454594
answers question: http://stackoverflow.com/q/52253445
score: 2
has comment: http://stackoverflow.com/comment/91454842
has comment: http://stackoverflow.com/comment/91454518

class
tags question: http://stackoverflow.com/q/52179224
tags question: http://stackoverflow.com/q/52242437
tags question: http://stackoverflow.com/q/52195272
tags question: http://stackoverflow.com/q/52184455
tags question: http://stackoverflow.com/q/52213184
tags question: http://stackoverflow.com/q/52235173
tags question: http://stackoverflow.com/q/52256983
tags question: http://stackoverflow.com/q/52247572
tags question: http://stackoverflow.com/q/52205848
tags question: http://stackoverflow.com/q/52127867
tags question: http://stackoverflow.com/q/52137072
tags question: http://stackoverflow.com/q/52254421
tags question: http://stackoverflow.com/q/52224432
tags question: http://stackoverflow.com/q/52155791
tags question: http://stackoverflow.com/q/52201785
tags question: http://stackoverflow.com/q/52210318
tags question: http://stackoverflow.com/q/52149297
tags question: http://stackoverflow.com/q/52135651
tags question: http://stackoverflow.com/q/52173760
type: Tag
tags question: http://stackoverflow.com/q/52165717
tags question: http://stackoverflow.com/q/52202298
tags question: http://stackoverflow.com/q/52207345
tags question: http://stackoverflow.com/q/52122632
tags question: http://stackoverflow.com/q/52208821
tag name: class
tags question: http://stackoverflow.com/q/52229233
tags question: http://stackoverflow.com/q/52212203
tags question: http://stackoverflow.com/q/52144474
tags question: http://stackoverflow.com/q/52187592
tags question: http://stackoverflow.com/q/52134701
tags question: http://stackoverflow.com/q/52242939
tags question: http://stackoverflow.com/q/52163200
tags question: http://stackoverflow.com/q/52131147
tags question: http://stackoverflow.com/q/52249359
tags question: http://stackoverflow.com/q/52143917
tags question: http://stackoverflow.com/q/52171726

http://stackoverflow.com/q/52230513
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/72733532
has comment: http://stackoverflow.com/comment/91410961
has title: How to remove last comma from print(string, end=“, ”)
type: Question
score: 9
has answer: http://stackoverflow.com/a/69687182
upvote count: 9
has body: my output from a forloop is string = "" for x in something: #some operation string = x += string print(string) 5 66 777 I use the below code to have them on the same line print(string, end=", ") and then I get 5, 66, 777, I want the final result to be 5, 66, 777 How do I change the code print(string, end=", ") so that there is no , at the end The above string is user input generated it can me just 1 or 2,3, 45, 98798, 45 etc So far I have tried print(string[:-1], end=", ") #result = , 6, 77, print((string, end=", ")[:-1]) #SyntaxError: invalid syntax print((string, end=", ").replace(", $", "")) #SyntaxError: invalid syntax print(", ".join([str(x) for x in string])) # way off result 5 6, 6 7, 7, 7 print(string, end=", "[:-1]) #result 5,66,777,(I thought this will work but no change to result) print(*string, sep=', ') #result 5 6, 6 7, 7, 7 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! user input twenty five, four, nine gets 25, 4, 9, #(that stupid comma in the end)
has answer: http://stackoverflow.com/a/73965234
has answer: http://stackoverflow.com/a/77136609
accepted answer: http://stackoverflow.com/a/52230563
has answer: http://stackoverflow.com/a/66446297
has answer: http://stackoverflow.com/a/63534071
downvote count: 0
answer count: 10
has answer: http://stackoverflow.com/a/52230604
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52230597
has answer: http://stackoverflow.com/a/70853520
possible better answer: http://stackoverflow.com/a/52230604
tagged with: python
has answer: http://stackoverflow.com/a/52230563

http://stackoverflow.com/a/56880897
score: 2
answers question: http://stackoverflow.com/q/52191307
downvote count: 0
upvote count: 2
type: Answer
has body: I recommend you to use Google Cloud Build. It lets you syncing your repo and using gsutil you can automatically update your storage i.e gs://acme-sales on each commits to your GitHub repository: steps: - name: gcr.io/cloud-builders/gsutil args: ['cp', '/workspace', 'gs://acme-sales'] You may start on GitHub by connecting your repository i.e. https://github.com/jc/&lt;repo_name&gt; to Google Cloud Build using the link below: https://github.com/apps/google-cloud-build

http://stackoverflow.com/q/52222112
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91392852
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91396432
answer count: 0
score: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91396330
tagged with: function
has body: I would like to be able to basically pass a column into the np.random.normal() function. I have the following; def calc_z(w,S,a1,a2,yt1,yt2): mu = w * S print 'Mu' , mu sigma = mt.sqrt(0.5) z = np.array(np.random.normal(mu,sigma)) u = [a1,a2,z] yt = [yt1,yt2,1] thetaset = np.random.rand(len(u)) m = [i for i in range(len(u))] max_iter = 30 #Calculate E-step for i in range(max_iter): print 'Iteration:', i print 'z:', z print 'thetaset', thetaset devLz = eq6(var,w,S,z,yt,u,thetaset,m) dev2Lz2 = eq9(var,thetaset,u) #Calculate M-Step z = z - (devLz / dev2Lz2) w = lambdaw * z for i in range(len(thetaset)): devLTheta = eq7(yt,u,thetaset,lambdatheta) dev2LTheta2 = eq10(thetaset,u,lambdatheta) thetaset = thetaset - (devLTheta / dev2LTheta2) return float(z) calc_z_udf = udf(calc_z,FloatType()) data.show() data = data.withColumn('z', calc_z(data['w'],data['Org_Depth_Diff_S'],data['proximity_rank_a1'],data['cotravel_count_a2'],data['cotravel_yt1'],data['proximity_yt2'])) But when I pass S in, the np.random.normal function doesn't like being passed a column and gives me the following error; Traceback (most recent call last): File "/home/taylorr2/PySparkLatent3.py", line 125, in &lt;module&gt; data = data.withColumn('z', calc_z(data['w'],data['Org_Depth_Diff_S'],data['proximity_rank_a1'],data['cotravel_count_a2'],data['cotravel_yt1'],data['proximity_yt2'])) File "/home/taylorr2/PySparkLatent3.py", line 90, in calc_z z = np.array(np.random.normal(mu,sigma)) File "mtrand.pyx", line 1282, in mtrand.RandomState.normal (numpy/random/mtrand/mtrand.c:6920) ValueError: setting an array element with a sequence. I am trying to think of a way to get this function to accept this value or do this a different way. Thanks!
has title: Creating a column of random numbers from a distribution with mean and std from other columns using python
has comment: http://stackoverflow.com/comment/91394059
has comment: http://stackoverflow.com/comment/91393809
tagged with: random
has comment: http://stackoverflow.com/comment/91392977
has comment: http://stackoverflow.com/comment/91397061
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91392922

http://stackoverflow.com/comment/91409512
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52229876
type: QuestionComment
has text: decodeURI() says it's malformed but you might be right

http://stackoverflow.com/a/52156681
has comment: http://stackoverflow.com/comment/91375710
has comment: http://stackoverflow.com/comment/91301542
score: 3
has comment: http://stackoverflow.com/comment/91374908
downvote count: 1
upvote count: 4
has comment: http://stackoverflow.com/comment/91369530
has comment: http://stackoverflow.com/comment/91263809
answers question: http://stackoverflow.com/q/52152943
has comment: http://stackoverflow.com/comment/91340339
has body: That error implies that you have another older version of the Oracle client installed somewhere earlier in your PATH. You should do a search for OCI.DLL on your machine (using where.exe or the dir command) and either move or remove any unnecessary copies or adjust PATH as needed. Some older applications stuffed OCI.DLL in C:\Windows\System32 improperly, for example.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91326542
accepted answer of: http://stackoverflow.com/q/52152943
has comment: http://stackoverflow.com/comment/91263782
has comment: http://stackoverflow.com/comment/91263902
has comment: http://stackoverflow.com/comment/91295939
has comment: http://stackoverflow.com/comment/91301358
has comment: http://stackoverflow.com/comment/91263842
type: Answer

http://stackoverflow.com/q/52232068
has comment: http://stackoverflow.com/comment/91413627
has body: Preface: I have an image of a coin. This is any generic image of a coin that I plug into python, and I want to make this coin a grayscale image. The variable P represents the array containing the RGB values for the picture of the coin, and I believe that I can turn RGB to grayscale by changing any RGB values under 128 to 0 while turning any RGB values above 128 to 255. Error: I am trying to use a for loop to turn the values in the array generated by P to 0, 128, and 255. When I do so this way, I encounter the error as: TypeError: '&lt;' not supported between instances of 'tuple' and 'int' ". Code: import numpy as np import matplotlib.pyplot as plt P = plt.imread('coin.jpg') for item in enumerate(P): if item &lt; 128: item = 0 elif item &gt; 128: item = 255
has answer: http://stackoverflow.com/a/52233753
favorite count: 0
has answer: http://stackoverflow.com/a/52233624
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91414641
tagged with: python
linked to: http://stackoverflow.com/q/23339315
score: 2
upvote count: 3
tagged with: image-processing
has comment: http://stackoverflow.com/comment/91414609
downvote count: 1
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52232230
has comment: http://stackoverflow.com/comment/91415802
has title: How to change an image to grayscale represented as a NumPy array
answer count: 3
has comment: http://stackoverflow.com/comment/91415982

http://stackoverflow.com/comment/91286327
comment on: http://stackoverflow.com/a/52155279
score: 0
type: Comment
has text: That shouldn't happen given your input. Perhaps break up the code to see exactly which part is breaking on your real data. `df1 = df.groupby('Country').Value.agg(list)` then apply Series, then Transpose.
type: AnswerComment

http://stackoverflow.com/q/52173403
has title: Using generator items selectively
has comment: http://stackoverflow.com/comment/91298440
type: Question
tagged with: python
tagged with: generator
score: 0
upvote count: 1
linked to: http://stackoverflow.com/q/5509302
downvote count: 1
answer count: 1
has body: Let's say I have some arrays/lists that contains a lot of values, which means that loading several of these into memory would ultimately result in a memory error due to lack of memory. One way to circumvent this is to load these arrays/lists into a generator, and then use them when needed. However, with generators you don't have so much control as with arrays/lists - and that is my problem. Let me explain. As an example I have the following code, which produces a generator with some small lists. So yeah, this is not memory intensive at all, just an example: import numpy as np np.random.seed(10) number_of_lists = range(0, 5) generator_list = (np.random.randint(0, 10, 10) for i in number_of_lists) If I iterate over this list I get the following: for i in generator_list: print(i) &gt;&gt; [9 4 0 1 9 0 1 8 9 0] &gt;&gt; [8 6 4 3 0 4 6 8 1 8] &gt;&gt; [4 1 3 6 5 3 9 6 9 1] &gt;&gt; [9 4 2 6 7 8 8 9 2 0] &gt;&gt; [6 7 8 1 7 1 4 0 8 5] What I would like to do is sum element wise for all the lists (axis = 0). So the above should in turn result in: [36, 22, 17, 17, 28, 16, 28, 31, 29, 14] To do this I could use the following: sum = [0]*10 for i in generator_list: sum += i where 10 is the length of one of the lists. So far so good. I am not sure if there is a better/more optimized way of doing it, but it works. My problem is that I would like to determine which lists in the generator_list I want to use. For example, what if I wanted to sum two of the first [0] list, one of the third, and 2 of the last, i.e.: [9 4 0 1 9 0 1 8 9 0] [9 4 0 1 9 0 1 8 9 0] [4 1 3 6 5 3 9 6 9 1] [6 7 8 1 7 1 4 0 8 5] [6 7 8 1 7 1 4 0 8 5] &gt;&gt; [34, 23, 19, 10, 35, 5, 19, 22, 43, 11] How would I go about doing that ? And before any questions arise why I want to do it this way, the reason is that in my real case, getting the arrays into the generator takes some time. I could then in principle just generate a new generator where I put in the order of lists as seen in the new list, but again, that …
has comment: http://stackoverflow.com/comment/91297831
has comment: http://stackoverflow.com/comment/91298355
has answer: http://stackoverflow.com/a/52173829
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91297797
accepted answer: http://stackoverflow.com/a/52173829
favorite count: 0

http://stackoverflow.com/comment/91191662
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52117120
has text: Thanks, I will check it out. What is the input to this model? The sequence with the words? I mean- does this prepares the one-hot encoding? n_vocab should state the number of words in the data?
type: AnswerComment

http://stackoverflow.com/comment/91220644
comment on: http://stackoverflow.com/q/52134584
score: 0
type: Comment
type: QuestionComment
has text: with due respect this is no way a duplicate.I already solved that problem and come to this point to reverse that result.That's why already gave my code sample to convert wav to spectogram.But mu question is after decomposing that spectogram how do i recompose it.So that's 2 way advance than the issue you mentioned.Btw thanks.

http://stackoverflow.com/comment/91367699
comment on: http://stackoverflow.com/q/52209106
has text: Please check any tutorial that includes non-trivial lists, such as a list of lists. This *is* perfectly legal access to a deeper structure. Think of it as `x = stack[-1]; y = x[1]`, if that helps.
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52248943
has comment: http://stackoverflow.com/comment/91446058
has body: Looks like you can access it with the path property of the request object: https://docs.djangoproject.com/en/2.1/ref/request-response/#django.http.HttpRequest.path
has comment: http://stackoverflow.com/comment/91446167
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52248821
has comment: http://stackoverflow.com/comment/91446429
answers question: http://stackoverflow.com/q/52248821
has comment: http://stackoverflow.com/comment/91446383
type: Answer

http://stackoverflow.com/comment/91430092
type: QuestionComment
comment on: http://stackoverflow.com/q/52240694
has text: `df.apply(pd.to_numeric, errors='coerce')`?
score: 0
type: Comment

http://stackoverflow.com/q/52222002
has answer: http://stackoverflow.com/a/79426815
upvote count: 85
has answer: http://stackoverflow.com/a/64401876
has answer: http://stackoverflow.com/a/52228375
accepted answer: http://stackoverflow.com/a/52228375
favorite count: 0
has body: I am using Jupyter notebook. I'm trying to measure how long will it take to count the Avogadro's number with Python. I found that time.perf_counter() and time.process_time() modules will be useful for this kind of work. So I tried both of them, but the result was totally different. What makes this kind of difference? Here is my code. Using time.perf_counter() import time a = 10 ** 5 def AvogadroCounting(): i = 0 while i &lt;= a: i += 1 AvogadroCounting() t_fract = time.perf_counter() #time to count fraction of avogadro's number in Seconds print(t_fract, 'secs') And my notebook gives 693920.393636181 secs. Using time.process_time() import time a = 10 ** 5 def AvogadroCounting(): i = 0 while i &lt;= a: i += 1 AvogadroCounting() t_fract = time.process_time() #time to count fraction of avogadro's number in Seconds print(t_fract, 'secs') and this gives 2048.768273 secs.
answer count: 3
has title: What is the difference between time.perf_counter() and time.process_time()?
possible better answer: http://stackoverflow.com/a/64401876
tagged with: python
score: 85
downvote count: 0
tagged with: time
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/52248720
type: Answer
upvote count: 1
score: 1
has body: The approach of the answer by abc adding the module path to the system path is fine for local, instant testing, but it's not the full solution, for example when C code needs to be compiled or command line hooks must be set. For a full test you might want to install the package instead. A typical Python has a setup.py and can be packaged into a distribution file (wheel, ...) which can then be installed locally from a local file. The workflow would be: create a package distributable (may include a command like python setup.py bdist_wheel) create a new virtual environment for testing (or de-install any previously installed, non-modified version of the package) installe the package from the locally created distributable (may be as simple as pip install --no-index --find-links=..) run the tests This results in exactly the same situation every future user of the package will find itself in and is a complete test (including the installing process), but it's also a lot of effort, that's why I usually only us the system path method during development, but the full installation way only directly before a release.
downvote count: 0
answers question: http://stackoverflow.com/q/52248505

http://stackoverflow.com/a/52188769
accepted answer of: http://stackoverflow.com/q/52188382
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: One solution is to convert 'Cs' to a Categorical. Then use GroupBy + first: df['Cs'] = df['Cs'].astype('category') res = df.groupby(['Samp', 'Cs']).first().reset_index() res['Age'] = res.groupby('Samp')['Age'].transform('first').astype(int) Result Samp Cs Age 0 A cin 51 1 A ebv 51 2 A gs 51 3 A msi 51 4 B cin 62 5 B ebv 62 6 B gs 62 7 B msi 62 8 C cin 55 9 C ebv 55 10 C gs 55 11 C msi 55 12 D cin 70 13 D ebv 70 14 D gs 70 15 D msi 70 16 E cin 56 17 E ebv 56 18 E gs 56 19 E msi 56
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52188382

http://stackoverflow.com/a/52171123
downvote count: 0
has comment: http://stackoverflow.com/comment/91293140
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52170932
has comment: http://stackoverflow.com/comment/91293318
answers question: http://stackoverflow.com/q/52170932
has body: /tf_files means that the tf_files folder is under your main directory (that's the meaning of /), which is not the case. You should remove all the leading slashes / from your directory arguments, i.e. python scripts/retrain.py --bottleneck_dir=tf_files/bottlenecks --how_many_training_steps=500 --model_dir={$your-working_directory}/inception --output_graph={$your-working_directory}/retrained_graph.pb --output_labels={$your-working_directory}/retrained_labels.txt --image_dir=tf_files/paintings assuming of course that the shell variable your-working_directory has already been defined (if not, replace it with your actual working directory).
type: AcceptedAnswer

windows
tags question: http://stackoverflow.com/q/52213420
tags question: http://stackoverflow.com/q/52187362
tags question: http://stackoverflow.com/q/52144829
tags question: http://stackoverflow.com/q/52149909
tags question: http://stackoverflow.com/q/52236796
tags question: http://stackoverflow.com/q/52225035
tags question: http://stackoverflow.com/q/52250623
tags question: http://stackoverflow.com/q/52268294
tags question: http://stackoverflow.com/q/52243287
tags question: http://stackoverflow.com/q/52205398
tags question: http://stackoverflow.com/q/52129116
tags question: http://stackoverflow.com/q/52253916
tags question: http://stackoverflow.com/q/52138200
tags question: http://stackoverflow.com/q/52213973
tags question: http://stackoverflow.com/q/52252512
type: Tag
tags question: http://stackoverflow.com/q/52128951
tags question: http://stackoverflow.com/q/52133551
tags question: http://stackoverflow.com/q/52220223
tags question: http://stackoverflow.com/q/52250332
tags question: http://stackoverflow.com/q/52226044
tag name: windows
tags question: http://stackoverflow.com/q/52214776
tags question: http://stackoverflow.com/q/52246574
tags question: http://stackoverflow.com/q/52156470
tags question: http://stackoverflow.com/q/52209760
tags question: http://stackoverflow.com/q/52256138
tags question: http://stackoverflow.com/q/52191007

http://stackoverflow.com/comment/91478739
comment on: http://stackoverflow.com/q/52264941
has text: I'm sure there is a way. For all pixel values in row 1 of an image, are they in the same row or column or a pandas df? say pixel coordinates for row1 of image would be [(0,0), (1,0), (2,0) (3,0)]. Would thos be stored in the same row or column of a df? It would help if you could provide us an example of the df as well.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/52160973
has comment: http://stackoverflow.com/comment/91369330
type: AcceptedAnswer
downvote count: 0
has body: A solution that might suffice is to create a wrapper-class. Example: class MyGoogleCloudStorageToBigQueryOperator(BaseOperator): template_fields = ('bucket', 'source_objects', 'schema_object', 'destination_project_dataset_table') @apply_defaults def __init__(self, bucket, destination_project_dataset_table, source_format, source_objects, schema_fields, params, create_disposition, write_disposition, skip_leading_rows, google_cloud_storage_conn_id, bigquery_conn_id, *args, **kwargs): super(InfogroupFilestreamOperator, self).__init__(*args, **kwargs) self.bucket= bucket self.destination_project_dataset_table=destination_project_dataset_table ... def execute(self, context): self.log.info("My name is %s", self.task_id) hook=GoogleCloudStorageToBigQueryOperator( task_id="doesnt_matter", bucket=self.bucket, source_format=self.source_format, ... ) return hook.execute(context) MyGoogleCloudStorageToBigQueryOperator can then be instantiated instead of GoogleCloudStorageToBigQueryOperator in your for-loop.
has comment: http://stackoverflow.com/comment/91365615
answers question: http://stackoverflow.com/q/52144108
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/52144108
upvote count: 1

http://stackoverflow.com/comment/91328654
type: Comment
type: QuestionComment
has text: https://www.tutorialspoint.com/python/python_if_else.htm
comment on: http://stackoverflow.com/q/52189421
score: 0

http://stackoverflow.com/q/52230904
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: Python Pandas. Extract rows with differing number of columns and sub-strings from string columns containing a secondary separator
has body: I have a tab-delimited file like this: 10 5040637 rs2518044;rs536681963 CG TG C 10 34398820 rs150406373 C G 10 35040637 rs532547811 TCCC T Using Python pandas, I would like to: 1) Extract the first 4 columns. 2) In cases where there are strings of the kind "rs2518044;rs536681963" or "rs2518044;rs536681963;rs1111", I want to extract the part before the first ";". I would get something like this: 10 5040637 rs2518044 CG 10 34398820 rs150406373 C 10 35040637 rs532547811 TCCC
has comment: http://stackoverflow.com/comment/91411726
score: 1
accepted answer: http://stackoverflow.com/a/52237579
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/52231103
tagged with: pandas
has answer: http://stackoverflow.com/a/52231103
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52237579

http://stackoverflow.com/comment/91452395
score: 0
type: Comment
type: QuestionComment
has text: What is `print (df.dtypes)` ?
comment on: http://stackoverflow.com/q/52252477

http://stackoverflow.com/comment/91308111
type: AnswerComment
score: 0
type: Comment
has text: it prints content
comment on: http://stackoverflow.com/a/52178631

http://stackoverflow.com/comment/91273988
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52162003
has text: Yes, you have to check when perform redirect and when it isn't required, return the `super...`. I've just edited an answer, please check it.

http://stackoverflow.com/a/52253950
accepted answer of: http://stackoverflow.com/q/52244588
has comment: http://stackoverflow.com/comment/91466872
type: Answer
has comment: http://stackoverflow.com/comment/91456746
has body: Here how you can get all the people that like your photo by xpath: //div[text()='Likes']/..//a[@title] Code below get first 12 liker: likes = browser.find_elements_by_xpath("//div[text()='Likes']/..//a[@title]") for like in likes: user = like.get_attribute("title") To get all likes you have to scroll, for that you can get total likes you have and then scroll until all likes will be loaded. To get total likes you can use //a[contains(.,'likes')]/span xpath and convert it to integer. To scroll use javascript .scrollIntoView() to last like, final code would look like: totalLikes = int(browser.find_element_by_xpath("//a[contains(.,'likes')]/span").text) browser.find_element_by_xpath("//a[contains(.,'likes')]/span").click() while true: likes=browser.find_elements_by_xpath("//div[text()='Likes']/..//a[@title]") likesLen = len(likes) if (likesLen == totalLikes - 1) break browser.execute_script("arguments[0].scrollIntoView()", likes.get(likesLen-1)) for like in likes: user = like.get_attribute("title") How it works: With //div[text()='Likes'] I found unique div with window contains likes. Then to get all likes that is li I go to parent div with /.. selector and then get all a with title attribute. Because all likes not loading immediately you have to scroll down. For that I get total likes amount before click to likes. Than I scroll to last like (a[@title]) to force instagram to load some data until total likes I got not equals to list of likes. When scroll completes I just iterate throw all likes in list I got inside while loop and get titles.
has comment: http://stackoverflow.com/comment/91456430
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/52244588
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91193614
type: AnswerComment
type: Comment
has text: In case of keys made by a single word, as the max length of a key is 1, you only check for each word of the input sentence.
comment on: http://stackoverflow.com/a/52119690
score: 0

http://stackoverflow.com/q/52257044
tagged with: debian
accepted answer: http://stackoverflow.com/a/52257181
has title: python - http.server works on windows but doesnt on debian
has body: So I'm relatively new to python, but I am a quick learner, I think. For communication with one of my programs, I made this simple webserver: from http.server import BaseHTTPRequestHandler, HTTPServer import json import os import time class S(BaseHTTPRequestHandler): class user(): def __init__(self, name, hash): self.name = name; self.hash = hash; def terminate(self): pass; def _set_headers(self, res=200, type="text/html", loc=False): self.send_response(res) if loc: self.send_header('Location', loc) self.send_header('Content-type', 'text/html') self.end_headers() def do_GET(self): self._set_headers(200) self.wfile.write(b" UGame-Server. Incorrect Method.") def do_HEAD(self): self._set_headers() def do_POST(self): if self.headers.get('Content-Length'): data = json.loads(self.rfile.read(int(self.headers.get('Content-Length')))); else: data = {}; datas = json.dumps(data); if self.path == "/": self._set_headers(200, "text/html", "index"); self.path = "/index"; else: self._set_headers(200, "text/html"); path = self.path[1:]; print(path); import index as serverfile; auth=True; if path[:6]=="secure": auth=False; os.chdir("axs"); if "hash" in data: if os.path.exists(data["hash"]+".txt") and time.time()-os.path.getmtime(data["hash"]+".txt")<43200: auth=True; print("Secure access from account "+data["name"]+" verified."); data["user"]=self.user(data["name"],data["hash"]); # del data["name"]; else: if self.client_address[0]=="127.0.0.1": auth=True; data["user"]=self.user("admin","fake"); data["name"]="admin"; os.chdir(".."); if auth: psfr = open("serverdata.posdata.json", "r" ); posdata = json.loads(psfr.read()); psfr.close(); if data["name"] in posdata: data["user"].x = posdata[data["name"]]["x"]; data["user"].y = posdata[data["name"]]["y"]; data["user"].z = posdata[data["name"]]["z"]; data["user"].world = posdata[data["name"]]["world"]; if auth: # try: exec("global response; response = serverfile."+path+"(data);"); # except AttributeError: # exec('global response; response = …
tagged with: python
has comment: http://stackoverflow.com/comment/91461257
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91461383
has comment: http://stackoverflow.com/comment/91461404
tagged with: http
type: Question
has answer: http://stackoverflow.com/a/52257181
has comment: http://stackoverflow.com/comment/91461334
score: 0
answer count: 1

http://stackoverflow.com/comment/91193431
score: 1
type: QuestionComment
has text: What exactly do you mean by "compile an existing Python application"? Turn each of your modules into an extension module, and then write your own CPython-embedding app to replace the top-level script and call into your modules with the C API? That should be doable. I remember them announcing Cython support for Android a few years ago, and a bunch of blog posts springing up with examples. If you just web search `cython android` you'll probably find lots of them.
comment on: http://stackoverflow.com/q/52121069
type: Comment

http://stackoverflow.com/q/52149692
possible better answer: http://stackoverflow.com/a/52150044
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52150028
accepted answer: http://stackoverflow.com/a/52150028
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/52150044
has body: I have written a code that reads from the given dataset and converts the whole txt file into a pandas data-frame (after some pre-processing) The latitudes represent the rows and are present in a list. The longitudes represent the columns and are present in a separate list. Now, I want to create a smaller data frame from the original one I created (so that it is easier to understand and interpret the data) and perform calculations. For that, I created a smaller column of size 18 by skipping over every 10 elements. This worked fine. Lets call this new column as new_column. Now, what I want to do is I want to iterate over every row and for every value of row k and new_column j, add it to a new matrix or a data frame. For eg. if the row 10 and new_column 12 has the value 'x' i want to add this 'x' at the same position but in a new data frame (or matrix). I have written the following code but I don't know how to perform that part which lets me do the above. import matplotlib.pyplot as plt import pandas as pd import numpy as np from scipy import interpolate # open the file for reading dataset = open("Aug-2016-potential-temperature-180x188.txt", "r+") # read the file linewise buffer = dataset.readlines() # pre-process the data to get the columns column = buffer[8] column = column[3 : -1] # get the longitudes as features features = column.split("\t") # convert the features to float data-type longitude = [] for i in features: if "W" in features: longitude.append(-float(i[:-1])) # append -ve sign if "W", drop the "W" symbol else: longitude.append(float(i[:-1])) # append +ve sign if "E", drop the "E" symbol # append the longitude as columns to the dataframe df = pd.DataFrame(columns = longitude) # convert the rows into float data-type latitude = [] for i in buffer[9:]: i = i[:-1] i = i.split("\t") if i[0] != "": if "S" in i[0]: # if the first entry in the row is not null/blank latitude.append(-float(i[0][:-1])) # append it to latitude list; append -ve for for "S" df.loc[-float…
has title: How to create a sub data-frame from a given pandas data-frame?
score: 0
tagged with: pandas
tagged with: python
tagged with: python-3.x

jquery
tags question: http://stackoverflow.com/q/52155339
tags question: http://stackoverflow.com/q/52261182
type: Tag
tags question: http://stackoverflow.com/q/52135673
tags question: http://stackoverflow.com/q/52156945
tag name: jquery
tags question: http://stackoverflow.com/q/52257172
tags question: http://stackoverflow.com/q/52216318
tags question: http://stackoverflow.com/q/52218050
tags question: http://stackoverflow.com/q/52231715

http://stackoverflow.com/comment/91663281
has text: Hi there @MauricioMartinez, I understand the line.split(',') in the code above. I tried an implementation of it. However, I encountered an issue with **`re.split(r',(?![^"]")',content1.iloc[0][0]))`**. I tried using a look ahead to avoid commas in double quotes like the following: **`,"1,4-Benzenediol; Hydroquinol; p-Quinol",`** I works for the following **',"2,6-Diamino-4-hexenoic acid, 9CI",'**, but not the latter. Any help would be much appreciated. I am positive I did not write the look ahead regex correctly, and trying to figure it out.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52250359
type: Comment

http://stackoverflow.com/comment/91468416
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52260206
has text: Thank You! I have thought that there are no APIs for Python.

discord
tags question: http://stackoverflow.com/q/52131921
tags question: http://stackoverflow.com/q/52123779
tags question: http://stackoverflow.com/q/52210855
type: Tag
tags question: http://stackoverflow.com/q/52241051
tags question: http://stackoverflow.com/q/52125432
tags question: http://stackoverflow.com/q/52169896
tags question: http://stackoverflow.com/q/52194212
tags question: http://stackoverflow.com/q/52206819
tags question: http://stackoverflow.com/q/52257398
tags question: http://stackoverflow.com/q/52252695
tags question: http://stackoverflow.com/q/52142539
tags question: http://stackoverflow.com/q/52193942
tags question: http://stackoverflow.com/q/52132913
tags question: http://stackoverflow.com/q/52215217
tags question: http://stackoverflow.com/q/52225311
tag name: discord
tags question: http://stackoverflow.com/q/52156924
tags question: http://stackoverflow.com/q/52139809
tags question: http://stackoverflow.com/q/52133714
tags question: http://stackoverflow.com/q/52198372
tags question: http://stackoverflow.com/q/52247301
tags question: http://stackoverflow.com/q/52156410
tags question: http://stackoverflow.com/q/52236001
tags question: http://stackoverflow.com/q/52214171
tags question: http://stackoverflow.com/q/52176124
tags question: http://stackoverflow.com/q/52191882

http://stackoverflow.com/comment/91284361
score: 0
type: Comment
has text: but you didnt resolve my initial problem ! I want to obtain [ ' PRODUCTION ' , ' "CATEG " ' ] and this is not the case.
type: AnswerComment
comment on: http://stackoverflow.com/a/52166199

http://stackoverflow.com/q/52141147
has comment: http://stackoverflow.com/comment/91232022
has body: What I think: def sum_square(n): result = 0 if n &gt; 0: i = iter(n) for i in n: result += i * i return result elif n &lt;= 0: raise ValueError("n should be positive") print(sum_square(4)) However, the terminal displays that int object is not iterable. What's wrong with my answer? Could you do the modification based on my thought?
has answer: http://stackoverflow.com/a/52141155
answer count: 1
downvote count: 0
has title: Python function that takes a positive integer n and returns the sum of the squares of all the positive integers smaller than n
favorite count: 0
accepted answer: http://stackoverflow.com/a/52141155
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
type: Question

http://stackoverflow.com/comment/91191552
score: 0
comment on: http://stackoverflow.com/q/52120006
has text: You probably want an empty `cache/__init__.py`, but not having it shouldn't cause this problem (and doesn't for me); it makes `cache` an implicit namespace package instead of a regular package, but you can still import stuff out of it just fine.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52226200
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/52226281
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/52226281
tagged with: python
score: 4
has body: Right now, I have my data in a 2 by 2 numpy array. If I was to use MinMaxScaler fit_transform on the array, it will normalize it column by column, whereas I wish to normalize the entire np array all together. Is there anyway to do that?
upvote count: 4
tagged with: numpy
has title: How to use MinMaxScaler on all columns?
possible better answer: http://stackoverflow.com/a/55308323
has answer: http://stackoverflow.com/a/55308323

http://stackoverflow.com/comment/95259058
score: 1
comment on: http://stackoverflow.com/a/52202153
has text: ok, I am working on using loops. If it works, I will post the solution here. Thanks for your help.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91269116
comment on: http://stackoverflow.com/q/52159531
has text: Nvm. I'm on mobile, so moving slow. Didn't realize wave is built into python.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52247528
upvote count: 1
tagged with: python
tagged with: crystal-reports
has title: Read and convert crystal report .rpt file to .csv or .xlsx in python 3
has answer: http://stackoverflow.com/a/57495133
score: 1
type: Question
answer count: 2
has body: I'm trying to write a small script in Python3 to open and read bunch of crystal reports .rpt files and convert them to .csv or .xlsx files. I checked pandas and python3 official docs, but no luck. I ran file command from my linux machine on one of these files, and it gave me this: Composite Document File V2 Document, Little Endian, Os: Windows, Version 4.10, Code page: 1256, Revision Number: 97 and that lead me to olefile library, and I was able to load the content, but the content is in byte format. It would be highly appreciated if anyone can just help me out on how i might load this byte data (may be decode them first) to pandas and save it to a readable csv or xlsx file. Thank You, Regards
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/57423287

http://stackoverflow.com/q/52221803
possible better answer: http://stackoverflow.com/a/52271459
has answer: http://stackoverflow.com/a/52271459
upvote count: 5
has answer: http://stackoverflow.com/a/52264673
answer count: 2
score: 5
tagged with: puppeteer
downvote count: 0
has body: I'm trying to accept the cookies consent on a pop up window that is generated on this page. I tried to use waitForSelector but none of the selectors that I used seems to be visible to the headless browser. I would like to actually switch to "YES" and then submit the form. I guess it's displayed on window.onload so perhaps this will need to be done in JavaScript? import asyncio import time from pyppeteer import launch from pyppeteer.errors import TimeoutError from urllib.parse import urlparse URLS = [ 'https://www.trustarc.com/' ] start = time.time() async def fetch(url, browser): page = await browser.newPage() try: #await page.setRequestInterception(True) page.on('request', callback) await page.goto(url, {'waitUntil': 'networkidle0'}) await page.screenshot({'path': f'img/{urlparse(url)[1]}.png', 'fullPage': True}) except TimeoutError as e: print(f'Timeout for: {url}') finally: await page.close() async def callback(req): print(f'Request: {req.url}') async def run(): browser = await launch(headless=True, args=['--no-sandbox']) tasks = [] for url in URLS: task = asyncio.ensure_future(fetch(url, browser)) tasks.append(task) ret = await asyncio.gather(*tasks) await browser.close() loop = asyncio.get_event_loop() future = asyncio.ensure_future(run()) loop.run_until_complete(future) print(f'It took {time.time()-start} seconds.')
favorite count: 0
has comment: http://stackoverflow.com/comment/91396946
accepted answer: http://stackoverflow.com/a/52264673
tagged with: python
type: AnsweredQuestion
has title: Python: Pyppeteer clicking on pop up window
tagged with: pyppeteer
has comment: http://stackoverflow.com/comment/91397856
has comment: http://stackoverflow.com/comment/91397426
type: Question

http://stackoverflow.com/q/52205368
favorite count: 0
has comment: http://stackoverflow.com/comment/91360348
has comment: http://stackoverflow.com/comment/91602218
upvote count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/71688884
tagged with: python
downvote count: 0
has answer: http://stackoverflow.com/a/56101018
tagged with: pip
type: Question
has comment: http://stackoverflow.com/comment/91361607
has comment: http://stackoverflow.com/comment/91360266
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/91360384
tagged with: word-cloud
answer count: 2
score: 5
has body: I am using Jupyter Notebook and trying to build a wordcloud. Turns out there are some issues with the pillow package and the internet is full of talks around it. I was geetting the DLL error initially. I tried a lot of different things and not sure which one worked but right now, I am getting the 'cannot import name' error. Some details from Anaconda Prompt- &gt;python -m pip --version pip 18.0 from C:\Users\Kritika.Jalan\Anaconda3\lib\site-packages\pip (python 3.6) &gt;python -m pip install wordcloud Requirement already satisfied: wordcloud in c:\users\kritika.jalan\anaconda3\lib\site-packages (1.5.0) Requirement already satisfied: numpy&gt;=1.6.1 in c:\users\kritika.jalan\anaconda3\lib\site-packages (from wordcloud) (1.15.0) Requirement already satisfied: pillow in c:\users\kritika.jalan\anaconda3\lib\site-packages (from wordcloud) (4.0.0) Requirement already satisfied: olefile in c:\users\kritika.jalan\anaconda3\lib\site-packages (from pillow-&gt;wordcloud) (0.45.1) Details from Jupyter Notebook - from wordcloud import WordCloud ImportError: cannot import name 'WordCloud' import PIL print(PIL.PILLOW_VERSION) 5.0.0 What am I doing wrong here?
has title: Cannot import name 'WordCloud'

http://stackoverflow.com/comment/91235782
comment on: http://stackoverflow.com/a/52142911
type: Comment
has text: Since I'm on Python 3 I accepted this answer, but @ManojJadhav deserves an upvote. I should have specified version in my initial post
score: 1
type: AnswerComment

loops
tags question: http://stackoverflow.com/q/52242142
tags question: http://stackoverflow.com/q/52263451
tags question: http://stackoverflow.com/q/52169506
tags question: http://stackoverflow.com/q/52136961
tags question: http://stackoverflow.com/q/52225908
tags question: http://stackoverflow.com/q/52192868
tags question: http://stackoverflow.com/q/52114889
tags question: http://stackoverflow.com/q/52214006
tags question: http://stackoverflow.com/q/52249780
tags question: http://stackoverflow.com/q/52172760
tags question: http://stackoverflow.com/q/52215236
tags question: http://stackoverflow.com/q/52178792
tags question: http://stackoverflow.com/q/52169497
tags question: http://stackoverflow.com/q/52141928
tags question: http://stackoverflow.com/q/52222085
tags question: http://stackoverflow.com/q/52236217
type: Tag
tags question: http://stackoverflow.com/q/52118391
tags question: http://stackoverflow.com/q/52176882
tags question: http://stackoverflow.com/q/52178329
tags question: http://stackoverflow.com/q/52162441
tags question: http://stackoverflow.com/q/52171056
tags question: http://stackoverflow.com/q/52130222
tags question: http://stackoverflow.com/q/52212898
tags question: http://stackoverflow.com/q/52184338
tags question: http://stackoverflow.com/q/52211342
tags question: http://stackoverflow.com/q/52150197
tags question: http://stackoverflow.com/q/52227295
tags question: http://stackoverflow.com/q/52230334
tags question: http://stackoverflow.com/q/52127689
tags question: http://stackoverflow.com/q/52186361
tags question: http://stackoverflow.com/q/52137230
tags question: http://stackoverflow.com/q/52244934
tags question: http://stackoverflow.com/q/52250530
tag name: loops
tags question: http://stackoverflow.com/q/52239990
tags question: http://stackoverflow.com/q/52260104
tags question: http://stackoverflow.com/q/52266566
tags question: http://stackoverflow.com/q/52187275
tags question: http://stackoverflow.com/q/52187815
tags question: http://stackoverflow.com/q/52134571
tags question: http://stackoverflow.com/q/52196306
tags question: http://stackoverflow.com/q/52145493
tags question: http://stackoverflow.com/q/52252779
tags question: http://stackoverflow.com/q/52213678
tags question: http://stackoverflow.com/q/52189532
tags question: http://stackoverflow.com/q/52126524
tags question: http://stackoverflow.com/q/52112788
tags question: http://stackoverflow.com/q/52151426
tags question: http://stackoverflow.com/q/52175351
tags question: http://stackoverflow.com/q/52123692
tags question: http://stackoverflow.com/q/52239963
tags question: http://stackoverflow.com/q/52209106
tags question: http://stackoverflow.com/q/52188649
tags question: http://stackoverflow.com/q/52160893

http://stackoverflow.com/comment/91409969
type: AnswerComment
comment on: http://stackoverflow.com/a/52230058
score: 0
type: Comment
has text: In your Python code, what do you get when you print `data`?

http://stackoverflow.com/comment/91230738
type: Comment
has text: All I need to scrape is particular for my user, then I need to do the log in first.
score: 0
comment on: http://stackoverflow.com/q/52137238
type: QuestionComment

http://stackoverflow.com/q/52151042
has comment: http://stackoverflow.com/comment/91253816
has body: I use python to insert a date into MySQL. Before I insert the date I changed the date format to: start_datetime_object = datetime.datetime.strptime(str(stDate), '%Y-%m-%d') end_datetime_object = datetime.datetime.strptime(str(enDate), '%Y-%m-%d') d_stDate= start_datetime_object.strftime('%Y-%m-%d') d_enDate= end_datetime_object.strftime('%Y-%m-%d') When I use logging.debug("DATES----&gt;" + d_enDate +'-- '+ d_stDate) I get the result as I should in a %Y-%m-%d format. At the moment I'm stuck with datetime.date(2018, 6, 30) Edit: My query is: cursor1.execute("INSERT INTO "+MYSQL_DB+".events ( `name`, `type`, `startDate`,`endDate`, `location` ) VALUES (%s,%s,%s,%s,%s)",[ str(name), str(types), str(d_stDate),str(d_enDate),str(location)])
has comment: http://stackoverflow.com/comment/91254131
has comment: http://stackoverflow.com/comment/91252261
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91253712
tagged with: python
has comment: http://stackoverflow.com/comment/91253962
has comment: http://stackoverflow.com/comment/91254213
has comment: http://stackoverflow.com/comment/91252316
has comment: http://stackoverflow.com/comment/91252504
answer count: 0
tagged with: mysql
has title: Why my date element is displayed with this format : datetime.date(2018, 6, 30) in MySQL (in terminal)?
type: Question
has comment: http://stackoverflow.com/comment/91254350
has comment: http://stackoverflow.com/comment/91253004
has comment: http://stackoverflow.com/comment/91253691
tagged with: tornado
has comment: http://stackoverflow.com/comment/91252560
score: 0
has comment: http://stackoverflow.com/comment/91253571

udp
tags question: http://stackoverflow.com/q/52196479
tags question: http://stackoverflow.com/q/52237810
tags question: http://stackoverflow.com/q/52133035
tag name: udp
type: Tag

http://stackoverflow.com/a/52219579
has body: It's easier to use format_map In [40]: mydf.apply('We made {totalval} pesos from {account}. Woohoo!'.format_map, axis=1) Out[40]: 0 We made 140 pesos from Jones LLC. Woohoo! 1 We made 215 pesos from Alpha Co. Woohoo! 2 We made 95 pesos from Blue Inc. Woohoo! dtype: object Assign back with In [46]: mydf.assign(fullstring=mydf.apply( 'We made {totalval} pesos from {account}. Woohoo!'.format_map, axis=1)) Out[46]: Cur account bolts nuts totalval \ 0 pesos Jones LLC 200 150 140 1 euros Alpha Co 210 200 215 2 pounds Blue Inc 90 50 95 fullstring 0 We made 140 pesos from Jones LLC. Woohoo! 1 We made 215 pesos from Alpha Co. Woohoo! 2 We made 95 pesos from Blue Inc. Woohoo! For dict you could use to_dict In [48]: mydf.assign(fullstring=mydf.apply( 'We made {totalval} pesos from {account}. Woohoo!'.format_map, axis=1) ).to_dict(orient='r') Out[48]: [{'Cur': 'pesos', 'account': 'Jones LLC', 'bolts': 200, 'nuts': 150, 'totalval': 140, 'fullstring': 'We made 140 pesos from Jones LLC. Woohoo!'}, {'Cur': 'euros', 'account': 'Alpha Co', 'bolts': 210, 'nuts': 200, 'totalval': 215, 'fullstring': 'We made 215 pesos from Alpha Co. Woohoo!'}, {'Cur': 'pounds', 'account': 'Blue Inc', 'bolts': 90, 'nuts': 50, 'totalval': 95, 'fullstring': 'We made 95 pesos from Blue Inc. Woohoo!'}]
downvote count: 0
upvote count: 6
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52219499
has comment: http://stackoverflow.com/comment/91388319
accepted answer of: http://stackoverflow.com/q/52219499
type: Answer
score: 6

http://stackoverflow.com/comment/115263704
has text: Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/65197688

http://stackoverflow.com/q/52204743
has title: Scraping milions of records with requests and lxml takes too long
type: Question
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/52204820
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52204808
has body: I'm writing simple scraper with requests and lxml. Code works fine but scraping milions of records takes more than 10 days. Is it possible to make it faster using these two modules or is it only possible with async framework like scrapy? Here's the full code: import requests from lxml import html profile = 10100 #start from this profile i = 0 while i&lt;1000000: url = ("https://www.example.com/profile/10100") headers = {"user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"} r = requests.get(url, headers=headers) doc = html.fromstring(r.content) mod = doc.xpath("//*[@id = 'achievement104' and @class='achievement ']/text()") name = doc.xpath("/html/body/div[2]/div/div/div[1]/div/div[2]/h1/text()") if len(mod) != 0: #if match print("Moderator!", name) else: print("Not moderator!", name) profile += 1 #go to another profile i += 1 Thanks.
tagged with: web-scraping
tagged with: python-requests
possible better answer: http://stackoverflow.com/a/52204808
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52204820

http://stackoverflow.com/comment/91202785
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52125938
has text: Try `pip3 install pycrypto`. `pip` may belong to Python 2. `pip -V` will show if it's Python 2 or Python 3.

http://stackoverflow.com/q/52218173
has title: Count occurrences in hourly time frame from given start end time
tagged with: pandas
answer count: 1
has body: I have a data set which contains starting/ending time of meetings in different meeting rooms (exported from meeting rooms calendar) for a period of several months. I would like to create heat map which will show utilization per hour in an average day (lets say Monday). I've made a mock-up to show what I want as a result: Wanted mock-up This will be done using Plot.ly following this Heatmap guide. So far I have made dataframe for each day of the week and sort it by room name RoomName Start End Room1 18.5.2018 7:00 18.5.2018 19:00 Room1 6.7.2018 7:00 6.7.2018 19:00 Room1 13.7.2018 7:00 13.7.2018 19:00 Room1 20.7.2018 7:00 20.7.2018 19:00 Room1 27.7.2018 7:00 27.7.2018 19:00 Room1 3.8.2018 7:00 3.8.2018 19:00 Room1 29.6.2018 7:00 29.6.2018 19:00 Room1 22.6.2018 7:00 22.6.2018 19:00 Room2 29.6.2018 9:00 29.6.2018 11:00 Room2 15.6.2018 9:00 15.6.2018 10:30 Room2 17.8.2018 10:00 17.8.2018 11:30 ... ... ... Room8 10.8.2018 7:00 10.8.2018 19:00 Room8 17.8.2018 7:00 17.8.2018 19:00 I am wondering how to process this data to create an average day and hourly intervals in that day which will contain the number of occurrences of certain room being booked. Thanks
tagged with: python
type: AnsweredQuestion
tagged with: plotly
type: Question
has answer: http://stackoverflow.com/a/52219146
accepted answer: http://stackoverflow.com/a/52219146
tagged with: numpy
score: 0

http://stackoverflow.com/q/52266000
downvote count: 0
has body: I'm am trying to figure out the recommended way to use the dataset api together with the estimator api. Everything I have seen online is some variation of this: def train_input_fn(): dataset = tf.data.Dataset.from_tensor_slices((features, labels)) return dataset which can then be passed to the estimator's train function: classifier.train( input_fn=train_input_fn, #... ) but the dataset guide warns that: the above code snippet will embed the features and labels arrays in your TensorFlow graph as tf.constant() operations. This works well for a small dataset, but wastes memory---because the contents of the array will be copied multiple times---and can run into the 2GB limit for the tf.GraphDef protocol buffer. and then describes a method that involves defining placeholders which are then filled with the feed_dict: features_placeholder = tf.placeholder(features.dtype, features.shape) labels_placeholder = tf.placeholder(labels.dtype, labels.shape) dataset = tf.data.Dataset.from_tensor_slices((features_placeholder, labels_placeholder)) sess.run(iterator.initializer, feed_dict={features_placeholder: features, labels_placeholder: labels}) But if you're using the estimator api, you're not manually running the session. So how do you use the dataset api with estimators while avoiding the problems associated with from_tensor_slices()?
tagged with: tensorflow
type: Question
has title: Avoiding tf.data.Dataset.from_tensor_slices with estimator api
score: 5
answer count: 1
favorite count: 0
upvote count: 5
has answer: http://stackoverflow.com/a/52276382
accepted answer: http://stackoverflow.com/a/52276382
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/52230440
score: 2
downvote count: 0
answer count: 1
tagged with: virtualenv
has body: I recently upgraded from Ubuntu 16.04 LTS to 18.04 LTS, using the prompts and GUI windows with the Ubuntu software updater to complete the upgrade. Previous to the upgrade I had multiple virtual environments (virtualenv), each with an extensive set of Python packages installed. When I activate a virtualenv any Python commands or import statements result in ImportError: cannot import name _remove_dead_weakref. For example, pip freeze results in: $ pip freeze Traceback (most recent call last): File "/home/pwright/virtualenvs/btac-web-plots/bin/pip", line 7, in &lt;module&gt; from pip._internal import main File "/home/pwright/virtualenvs/btac-web-plots/local/lib/python2.7/site-packages/pip/_internal/__init__.py", line 5, in &lt;module&gt; import logging File "/usr/lib/python2.7/logging/__init__.py", line 26, in &lt;module&gt; import sys, os, time, cStringIO, traceback, warnings, weakref, collections File "/usr/lib/python2.7/weakref.py", line 14, in &lt;module&gt; from _weakref import ( ImportError: cannot import name _remove_dead_weakref Same error for trying to start an ipython session: $ ipython Traceback (most recent call last): File "/home/pwright/virtualenvs/btac-web-plots/bin/ipython", line 7, in &lt;module&gt; from IPython import start_ipython File "/home/pwright/virtualenvs/btac-web-plots/local/lib/python2.7/site-packages/IPython/__init__.py", line 48, in &lt;module&gt; from .core.application import Application File "/home/pwright/virtualenvs/btac-web-plots/local/lib/python2.7/site-packages/IPython/core/application.py", line 16, in &lt;module&gt; from copy import deepcopy File "/usr/lib/python2.7/copy.py", line 52, in &lt;module&gt; import weakref File "/usr/lib/python2.7/weakref.py", line 14, in &lt;module&gt; from _weakref import ( ImportError: cannot import name _remove_dead_weakref Most of my virtual environments have Python 2.7.12, whereas my system Python is 2.7.15. Has anyone else encountered this? What is this particular error, and what is my best solut…
favorite count: 0
has title: Python virtual environments broken with upgrade to Ubuntu 18.04
upvote count: 2
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52237016
type: Question
tagged with: ubuntu-18.04
has comment: http://stackoverflow.com/comment/91411066
accepted answer: http://stackoverflow.com/a/52237016

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

http://stackoverflow.com/q/52181307
has comment: http://stackoverflow.com/comment/91313443
answer count: 1
type: UnansweredQuestion
has body: Disabling a widget such as ttk.Button: button = ttk.Button(frame, text='Quit', command=self.quit) button.state(('disabled',)) renders it unresponsive to user actions such as clicking. However, disabling ttk.Treeview: tree = ttk.Treeview(frame,column=['one','two']) tree.state(('disabled',)) only serves to change its styling - it is still responsive to user actions such as column resizing, selecting and scrolling. Is there a way to make ttk.Treeview stop responding to user actions like ttk.Button? Neither Google nor the documentation seem to have the answer.
has comment: http://stackoverflow.com/comment/91315114
linked to: http://stackoverflow.com/q/35122530
score: 1
favorite count: 0
has title: Python tkinter.ttk: how to disable Treeview
tagged with: tkinter
type: Question
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/91314575
has answer: http://stackoverflow.com/a/52189449
upvote count: 3

http://stackoverflow.com/q/52265419
tagged with: python
has title: Join dataframes based on partial string-match between columns
has answer: http://stackoverflow.com/a/52265485
favorite count: 0
accepted answer: http://stackoverflow.com/a/52265485
downvote count: 0
has body: I have a dataframe which I want to compare if they are present in another df. after_h.sample(10, random_state=1) movie year ratings 108 Mechanic: Resurrection 2016 4.0 206 Warcraft 2016 4.0 106 Max Steel 2016 3.5 107 Me Before You 2016 4.5 I want to compare if the above movies are present in another df. FILM Votes 0 Avengers: Age of Ultron (2015) 4170 1 Cinderella (2015) 950 2 Ant-Man (2015) 3000 3 Do You Believe? (2015) 350 4 Max Steel (2016) 560 I want something like this as my final output: FILM votes 0 Max Steel 560
type: Question
tagged with: string-matching
type: AnsweredQuestion
tagged with: join
has answer: http://stackoverflow.com/a/57013955
score: 5
possible better answer: http://stackoverflow.com/a/52266140
has comment: http://stackoverflow.com/comment/91482158
has answer: http://stackoverflow.com/a/52266140
upvote count: 5
answer count: 3
tagged with: pandas
tagged with: partial

http://stackoverflow.com/a/52132600
answers question: http://stackoverflow.com/q/52132465
score: 0
type: Answer
has body: you could potentialy loop through the 3 lists and print them with the * sympol in front. for i in data[:3]: print(*i) this would in normal cases remove the brackets and commas of the list and just print it with spaces. I must admit though that i do not under stand how you got your output, so this is just my 2 cents. Hope it helps :)

http://stackoverflow.com/comment/91282631
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52166339
type: Comment
has text: Thank you so much. This works perfectly. I guess the idea is that rather than picking a random solution, we roll a 10-sided dice 100 times for each row?

http://stackoverflow.com/q/52127072
accepted answer: http://stackoverflow.com/a/52135046
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
downvote count: 0
tagged with: django
has body: I work on a simple chat app. I need to query db for an user to get last message of user conversation to other users. Same as main page of whatsapp and telegram. Model: class CHAT(models.Model): sender_uid = models.CharField(max_length=150, db_index=True) receiver_uid = models.CharField(max_length=150, db_index=True) message = models.TextField(verbose_name='Message Text') created = models.IntegerField(default=created_time_epoch) I tried this query: message_list = self.model.objects.filter(Q(sender_uid=user_uid)|Q(receiver_uid=user_uid)).order_by('receiver_uid', 'sender_uid', '-created').distinct('receiver_uid', 'sender_uid') Output: &lt;QuerySet [&lt;CHAT: ted@ted.com Message: hello 4 To: saeed@saeed.com&gt;, &lt;CHAT: marshal@marshal.com Message: hello6 To: saeed@saeed.com&gt;, &lt;CHAT: saeed@saeed.com Message: hello 5 To: ted@ted.com&gt;]&gt; My problem is I get two last message from each conversation (if both user send message to each other), In one of them user is sender and in other one user is receiver. For now I handle it with below code: message_send_list = list(self.model.objects.filter(sender_uid=user_uid).order_by('receiver_uid', '-created').distinct('receiver_uid')) message_receive_list = list(self.model.objects.filter(receiver_uid=user_uid).order_by('sender_uid', '-created').distinct('sender_uid')) temp_list = [] for s_message in message_send_list: r_message = next((item for item in message_receive_list if item.sender_uid == s_message.receiver_uid), None) if r_message is not None: message_receive_list.pop(message_receive_list.index(r_message)) if s_message.created &gt; r_message.created: temp_list.append(s_message) else: temp_list.append(r_message) else: temp_list.append(s_message) temp_list.extend(message_receive_list) Output: [&lt;CHAT: saeed@saeed.com Message: hello 5 To: ted@ted.com&gt;, &lt;CHAT: marshal@marshal.com Message: hello6 To: saeed@saeed.com&gt;] My question is how can I get this result in one query? Problem is user can be sender and rece…
type: Question
has comment: http://stackoverflow.com/comment/91208770
score: 1
tagged with: django-models
has comment: http://stackoverflow.com/comment/91218029
has title: Django ORM multiple distinct and order by
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52135046

http://stackoverflow.com/a/52257913
downvote count: 0
answers question: http://stackoverflow.com/q/52257639
type: Answer
upvote count: 1
has body: This worked for me : with open("test.txt","r+") as f: f.seek(5) #first fseek to the position line=f.readline() #read everything after it f.seek(5) #since file pointer has moved, fseek back to 5 f.write("B") #write the letter f.write(line) #write the remaining part Original : AAAAAAAAAA After : AAAAABAAAAA
score: 1

http://stackoverflow.com/comment/91333674
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52191695
has text: It looks like it would be as easy as just setting a transform to the axes, but it is unfortunately not. The transform chain is a bit more complicated and due to the independent x and y scales cannot simply be rotated. There is a relatively easy method shown in the [Floating Axes Demo](https://matplotlib.org/gallery/axisartist/demo_floating_axes.html), which uses a `mpl_toolkits.axisartist` helper function to achieve this.

http://stackoverflow.com/q/52158549
has title: Python simultaneously filling up a list
tagged with: multiprocessing
accepted answer: http://stackoverflow.com/a/52158652
tagged with: concurrency
score: 2
type: AnsweredQuestion
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/52158652
has body: So I am trying to write multiprocess code that will hopefully fill up a list based on some processes that are running. But it's not modifying the list at all. Now I know I can't access the same element and increment it from multiple threads because it will lead to race conditions. But what I have is code that accesses ONE index from ONE and only one process. So that for example, if I have a list with 4 elements, I run 4 processes, one process for each element. This, however, doesn't work. Even though I read that lists are supposedly thread-safe. I wrote a small program demonstrating my issue: from multiprocessing import Process list = [0,0,0,0] def incrAt(idx): list[idx] += 1 p0 = Process(target = incrAt, args=(0,)) p1 = Process(target = incrAt, args=(1,)) p2 = Process(target = incrAt, args=(2,)) p3 = Process(target = incrAt, args=(3,)) p0.start() p1.start() p2.start() p3.start() # Do stuff while we wait... p0.join() p1.join() p2.join() p3.join() print(list) # should print [1,1,1,1] but prints [0,0,0,0]
upvote count: 2
answer count: 1

http://stackoverflow.com/q/52212633
score: 2
has comment: http://stackoverflow.com/comment/93026143
downvote count: 0
has body: The one place that I am very lost is in determining how to properly supply API credentials to Scrapy Cloud and Scrapinghub in order to send the parsed items to Google Cloud. I currently am storing my scripts on Github and auto-updating it to Scrapy Cloud. This is in order to make for easier updating to my projects, and also to allow others to see my project progressions. The issue then arises of how to properly provide the API credentials in order to verify Scrapy data for Google. I can't publicly display the credentials (VERY bad idea I learned). And I don't believe I can both manually upload a JSON file to Scrapy Cloud and store my project in Github. I could only store my projects on Scrapy, but that limits collaboration on the project. Is there a potential workaround for this? Has anyone been able to resolve this issue? Thanks in advance! Edit: After reading some obscure Google documentation, I was able to resolve the issue with the initial help below. The process looks like this: Create a set of service account credentials in Google Cloud UI Go into Scrapinghub UI and create a setting in the spider for each item in the credentials. Use the "settings.get" function provided by Scrapy to pull those credentials in from your Scrapinghub UI. Build a Credentials object from the OAuth2 module. Use the Credentials object as the credentials for the Pub/Sub PublisherClient. A Github link to how I resolved the issue is here: https://github.com/cmattheson6/bill_votes/blob/master/senate_votes/pipelines.py
favorite count: 0
has title: How can I provide API credentials to Scrapy Cloud without publicly providing the credentials?
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/91374913
tagged with: python
tagged with: scrapy
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52213729
has comment: http://stackoverflow.com/comment/124163984

http://stackoverflow.com/a/52227824
has comment: http://stackoverflow.com/comment/91407776
score: 2
has comment: http://stackoverflow.com/comment/91406861
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52227707
answers question: http://stackoverflow.com/q/52227707
has comment: http://stackoverflow.com/comment/91408711
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91407383
has comment: http://stackoverflow.com/comment/91407154
type: Answer
has comment: http://stackoverflow.com/comment/91408548
has body: You get this error message whenever you use a format string with positional formats specs (like {} or {1}), but pass only keyword arguments. Similarly, you get a KeyError when you use a format string with only keyword format specs (like {v}), but pass only positional arguments: &gt;&gt;&gt; '{}'.format(i=1) IndexError: tuple index out of range &gt;&gt;&gt; '{i}'.format(1) KeyError: 'i' The fix is just to make your specs match your arguments. Either way you like is fine, they just have to be consistent: &gt;&gt;&gt; '{i}'.format(i=1) 1 &gt;&gt;&gt; '{}'.format(1) 1 All that being said, I'm not sure what the point of this is: "shiprow{}".format(i = range(0, 10)) You can fix it either way, but is this really a string you want? &gt;&gt;&gt; "shiprow{i}".format(i = range(0, 10)) 'shiprowrange(0, 10)' &gt;&gt;&gt; "shiprow{}".format(range(0, 10)) 'shiprowrange(0, 10)' If you're curious why you get this error, oversimplifying format a bit, it works like this: def format(self, *args, **kwargs): result = '' index = 0 bits = self.parse_format_stuff() for bit in bits: if bit is a regular string: result += bit elif bit is empty braces: result = args[index] index += 1 elif bit is a number in braces: result += args[number] elif bit is a valid identifier string in braces: result += kwargs[identifier] else: raise a ValueError return result So, when it sees that {} format spec, it looks for args[0]. Since you didn't pass any positional arguments, args is the empty tuple (), so args[0] is an IndexError. Arguably it might be better if format handled those errors and turned them into something nicer—but occasionally it's useful to be able to handle the KeyError programmatically. (Not so often the IndexError, but obviously the two have to work the same way.)

http://stackoverflow.com/q/52249978
linked to: http://stackoverflow.com/q/65148708
has answer: http://stackoverflow.com/a/52250030
tagged with: google-cloud-functions
tagged with: python
has comment: http://stackoverflow.com/comment/115155209
favorite count: 0
has body: I am trying to upload a file to google cloud storage from within a cloud function. I can't import the cloud storage library into my function, though. Can cloud storage be used from within cloud functions in this manner? Cloud Function from google.cloud import storage def upload_blob(bucket_name, blob_text, destination_blob_name): """Uploads a file to the bucket.""" storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_string(blob_text) print('File {} uploaded to {}.'.format( source_file_name, destination_blob_name)) def log_data(request): request_json = request.get_json() BUCKET_NAME = 'my-bucket' BLOB_NAME = 'test-blob' BLOB_STR = '{"blob": "some json"}' upload_blob(BUCKET_NAME, BLOB_STR, BLOB_NAME) return f'Success!' Error Deployment failure: Function load error: Code in file main.py can't be loaded. File "/user_code/main.py", line 1, in &lt;module&gt; from google.cloud import storage ImportError: cannot import name 'storage' from 'google.cloud' (unknown location)
score: 37
has comment: http://stackoverflow.com/comment/91448131
accepted answer: http://stackoverflow.com/a/52250030
type: AnsweredQuestion
upvote count: 37
tagged with: google-cloud-storage
type: Question
tagged with: google-cloud-platform
has title: Write to Google Cloud Storage from Cloud Function (python)
tagged with: serverless
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/91315952
comment on: http://stackoverflow.com/a/52181511
type: AnswerComment
score: 0
type: Comment
has text: @AthotaSrinivas - Are data confidental? If not, is possible send me csv to my email in my profile?

http://stackoverflow.com/a/52135729
upvote count: 4
has comment: http://stackoverflow.com/comment/91227308
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/91221739
has comment: http://stackoverflow.com/comment/91228342
type: Answer
has body: You can use ast.parse to parse the code, create a ast.NodeTransformer subclass to clear all the string nodes (no need to clear comments because comments are automatically ignored by ast.parse already), install the astunparse package to turn the node back to source code, and then count the keywords: import ast import astunparse import keyword import re class clear_strings(ast.NodeTransformer): def visit_Str(self, node): node.s = '' return node n = ast.parse(''' a = 'True' assert False # [[] for _ in range(9)] """if""" ''') clear_strings().visit(n) print(sum(map(keyword.iskeyword, re.findall(r'\w+', astunparse.unparse(n))))) This outputs: 2 (because only assert and False are counted as keywords)
answers question: http://stackoverflow.com/q/52135295
has comment: http://stackoverflow.com/comment/91223418

http://stackoverflow.com/comment/91308433
has text: @Compustretch I cannot reproduce your issues, your sample dataset works fine for me. Could you run `pd.show_versions()` and tell us your `pandas` and `matplotlib` versions?
comment on: http://stackoverflow.com/q/52177938
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52215796
has comment: http://stackoverflow.com/comment/91382660
has comment: http://stackoverflow.com/comment/91381421
has comment: http://stackoverflow.com/comment/91382571
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/52201038
answers question: http://stackoverflow.com/q/52201038
has comment: http://stackoverflow.com/comment/91382009
has comment: http://stackoverflow.com/comment/91382319
downvote count: 0
score: 1
has body: It seems that the sas_token is incorrect in your post,it does not contain %2Fdevices%2F{deviceid}. I don't know how you get the token,but I think you can use Device Explorer tool to generate the SAS token.
type: AcceptedAnswer

http://stackoverflow.com/comment/91432129
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52241562
has text: Nevermind. I've realized the input file was incorrect. Does work indeed.

http://stackoverflow.com/a/52146658
type: AcceptedAnswer
has body: There are 2 problems with your code. The validation function should always return a boolean. From this answer: It's important that the validation command returns either True or False. Anything else will cause the validation to be turned off for the widget. Your test_input function doesn't do that - there's a branch in which it returns None. def test_input(value, action): valid_input = ["7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "0", ".", "/"] if action == "1": if value not in valid_input: return False return True # None is being returned here! This is why the validation is disabled after your program deletes text from the Entry. The fix is simple: return True instead of None. def test_input(value, action): valid_input = ["7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "0", ".", "/"] if action == "1": if value not in valid_input: return False return True # if action != 1, allow it return True The validation function needs to handle multi-character input. You've assumed that the validation function is called for every single character that's entered. This is true when the user types a formula with their keyboard, but not when copy/pasting or setting the entry's text with .insert(...). Your function needs to handle these cases. def test_input(value, action): valid_input = ["7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "0", ".", "/"] if action == "1": return all(char in valid_input for char in value) # if action != 1, allow it return True
has comment: http://stackoverflow.com/comment/91264236
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/52145586
accepted answer of: http://stackoverflow.com/q/52145586
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/91264062

http://stackoverflow.com/comment/91410788
comment on: http://stackoverflow.com/q/52226198
score: 0
type: Comment
type: QuestionComment
has text: The confusion here is possibly between Python classes as in templates for objects, and HTML/CSS classes which are just a type of markup. When doing web stuff in Python, the context and terminology need to stay very clear.

http://stackoverflow.com/q/52179940
has body: new Python user here. I'm writing a piece of encryption software. This particular chunk of code is supposed to interpret a file full of encrypted data and decrypt it, but I keep getting an IndexError. Here's the code: while message_count &lt; message_len: if int(ord(message[message_count])-int(key_list[key_count])) &gt;= 0: key_tempvar = str(chr(ord(message_encrypted[message_count])-int(key_list[key_count]))) message_decrypted = message_decrypted + key_tempvar key_count += 1 if key_count == key_len: key_count = 0 message_count += 1 Here's the error: Traceback (most recent call last): File "E:\Documents\Code\Python\encryption\ASCII_encrypt.py", line 122, in &lt;module&gt; title() File "E:\Documents\Code\Python\encryption\ASCII_encrypt.py", line 69, in title decrypt(message) File "E:\Documents\Code\Python\encryption\ASCII_encrypt.py", line 109, in decrypt key_tempvar = str(chr(ord(message_encrypted[message_count])-int(key_list[key_count]))) IndexError: string index out of range message_count starts at 0 and message_len is equal to the length of the encrypted file. The idea of the code is that each character of message goes through the function individually and then gets added to the string message_decrypted, then that string gets written to a new file. Thanks in advance for your help! :)
has comment: http://stackoverflow.com/comment/91309947
has title: Issue with 'IndexError: string index out of range'
score: 0
has comment: http://stackoverflow.com/comment/91310136
has comment: http://stackoverflow.com/comment/91310012
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91309996
tagged with: encryption
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91310015
type: Question
has comment: http://stackoverflow.com/comment/91309882
tagged with: index-error

http://stackoverflow.com/comment/91335615
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52192868
has text: @GeorgeBou: `0<B and B<50` is equivalent (but slightly slower, as it loads `B` twice) to `0 < B < 50`; no need to split it up.
score: 0

http://stackoverflow.com/q/52171321
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52171704
has body: This is a (clearer) repost of a question I just made, my deidentification was confusing people. Hi, I'm new to graphing in python using matplotlib.pyplot and spent a good amount of time searching on this site and others, and trying to figure this out but I haven't succeeded in accomplishing what I'd like to do. Using the code below, I have generated the following graph, which is a collection of courses and the percent of those enrolled who went on to complete the course: What my code is creating: However, what I would like to generate with python is something like the following (crudely made in MS paint to convey to you all what I would like my code to generate): What I want to create: The right hand side axis labels is the number of people who enrolled in each course, which is the additional information I would like featured. An alternative solution is to have the enrollment numbers featured within the graph, written on/at the end of the bars. But whatever works is fine. import matplotlib.pyplot as plt y = ['Physics','Chemistry','Economics','Philosophy','Computer Science','Sociology','Biology','History','Overall'] x = [0.0,33.333333333333336,50.0,50.0,50.0,54.54545454545455,58.333333333333336,100.0,51.851851851851855] alternativeYlabels = ['54', '1', '3', '12', '12', '2', '11', '12', '1'] plt.barh(y,x) plt.title('Percent Completion Rate of Each Course') plt.show() How can I alter my code to fit my needs? Also, how could I add vertical grid lines in my plot corresponding to each 20% in here as well? Thanks
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/51991204
score: 2
has title: Creating alternative y axis labels for a horizontal bar plot with matplotlib
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/52172004
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/52172004
has answer: http://stackoverflow.com/a/52171704
answer count: 2
downvote count: 0

http://stackoverflow.com/q/52155123
has comment: http://stackoverflow.com/comment/91260793
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91260627
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91260642
has answer: http://stackoverflow.com/a/52155305
has body: I keep getting an empty dictionary #!/usr/local/bin/python3 dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} dictNew = {} def concatDict(dictCon): dictNew = dict.update(dictCon) return dictNew concatDict(dic1) concatDict(dic2) concatDict(dic3) print(dictNew) dictNew is not getting updated from the function calls. Can someone point me in the right direction?
has comment: http://stackoverflow.com/comment/91260444
has comment: http://stackoverflow.com/comment/91260495
downvote count: 1
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/91260399
score: -1
has comment: http://stackoverflow.com/comment/91260413
has comment: http://stackoverflow.com/comment/91260777
answer count: 3
has comment: http://stackoverflow.com/comment/91260551
has title: python3 Function to concat python dictionaries not working
has answer: http://stackoverflow.com/a/52155150
favorite count: 0
has answer: http://stackoverflow.com/a/52155165
linked to: http://stackoverflow.com/q/19158339
has comment: http://stackoverflow.com/comment/91260603

http://stackoverflow.com/comment/91405475
has text: Really glad you gave this answer. It allowed me to go back and rewrite my other view functions that were just as bad if not worse. Thanks again!
comment on: http://stackoverflow.com/a/52214736
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91253887
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52151647
score: 0
has text: @Denziloe Indeed, my bad. We often use 'e' for integers too in math, but in Python we may use the `**` operator to get large integers.

http://stackoverflow.com/a/52161069
upvote count: 3
answers question: http://stackoverflow.com/q/52148690
has comment: http://stackoverflow.com/comment/91300131
has comment: http://stackoverflow.com/comment/91341364
has body: Firstly, if you're just using the pre-trained model for the Stanford CoreNLP dependency parser, you should use the CoreNLPDependencyParser from nltk.parse.corenlp and avoid using the old nltk.parse.stanford interface. See Stanford Parser and NLTK After downloading and running the Java server in terminal, in Python: &gt;&gt;&gt; from nltk.parse.corenlp import CoreNLPDependencyParser &gt;&gt;&gt; dep_parser = CoreNLPDependencyParser(url='http://localhost:9000') &gt;&gt;&gt; sent = "I shot an elephant with a banana .".split() &gt;&gt;&gt; parses = list(dep_parser.parse(sent)) &gt;&gt;&gt; type(parses[0]) &lt;class 'nltk.parse.dependencygraph.DependencyGraph'&gt; Now we see that the parses are of type DependencyGraph from nltk.parse.dependencygraph https://github.com/nltk/nltk/blob/develop/nltk/parse/dependencygraph.py#L36 To convert the DependencyGraph to a nltk.tree.Tree object by simply doing DependencyGraph.tree(): &gt;&gt;&gt; parses[0].tree() Tree('shot', ['I', Tree('elephant', ['an']), Tree('banana', ['with', 'a']), '.']) &gt;&gt;&gt; parses[0].tree().pretty_print() shot _________|____________ | | elephant banana | | | _____|_____ I . an with a To convert it into the bracketed parse format: &gt;&gt;&gt; print(parses[0].tree()) (shot I (elephant an) (banana with a) .) If you're looking for dependency triplets: &gt;&gt;&gt; [(governor, dep, dependent) for governor, dep, dependent in parses[0].triples()] [(('shot', 'VBD'), 'nsubj', ('I', 'PRP')), (('shot', 'VBD'), 'dobj', ('elephant', 'NN')), (('elephant', 'NN'), 'det', ('an', 'DT')), (('shot', 'VBD'), 'nmod', ('banana', 'NN')), (('banana', 'NN'), 'case', ('with', 'IN')), (('banana', 'NN'), 'det', ('a', 'DT')), (('shot', 'VBD'), 'punct', ('.', '.'))] &gt;&gt;&gt; for governor, dep, dependent in parses[0].triples(): ... print(governor, dep, dependent) ... ('shot', 'VBD') nsubj ('I', 'PRP') ('shot', 'VBD') dobj ('elephant', 'NN') ('elephant', 'NN') det ('an', 'DT') ('shot', 'VBD') nmod ('banana', 'NN') ('banana', 'NN'…
has comment: http://stackoverflow.com/comment/91374276
downvote count: 0
has comment: http://stackoverflow.com/comment/91339870
type: Answer
has comment: http://stackoverflow.com/comment/116438521
has comment: http://stackoverflow.com/comment/91341354
has comment: http://stackoverflow.com/comment/91339928
has comment: http://stackoverflow.com/comment/91340661
has comment: http://stackoverflow.com/comment/91340515
score: 3
has comment: http://stackoverflow.com/comment/91297340
has comment: http://stackoverflow.com/comment/91340520

http://stackoverflow.com/comment/91329633
type: QuestionComment
comment on: http://stackoverflow.com/q/52175718
has text: Hello, Thank you for your quick answers! Yes, I initially installed Spyder using anaconda. I tried your command 'conda install package' and I got back the error '"conda" is not recognized as an internal or external command, operable program or batch file.' After looking on some other questions I resolved to uninstall anaconda and reinstall it with the box checked to make a path for anaconda. After doing this I was able to use 'conda install pandas-datareader' and now my code works. Thank you for your help!
score: 0
type: Comment

http://stackoverflow.com/a/52202153
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91380613
has body: You can use: L = ['Online','Own'] pat = '|'.join(r"\b{}\b".format(x) for x in L) df['New_Medium'] = df.pop('Medium').str.findall('('+ pat + ')').str.join(', ') #remove rows with empty values df = df[df['New_Medium'].astype(bool)] from itertools import product df1 = pd.DataFrame([j for i in df.apply(lambda x: x.str.split(',\s*')).values for j in product(*i)], columns=df.columns) print (df1) Date Investment Type New_Medium 0 1/1/2000 Mutual Fund Own 1 1/1/2000 Mutual Fund Online 2 1/1/2000 Stocks Own 3 1/1/2000 Stocks Online 4 1/1/2000 Fixed Deposit Own 5 1/1/2000 Fixed Deposit Online 6 1/1/2000 Real Estate Own 7 1/1/2000 Real Estate Online 8 1/2/2000 Mutual Fund Own 9 1/2/2000 Stocks Own 10 1/2/2000 Real Estate Own 11 1/3/2000 Fixed Deposit Online 12 1/2/2000 Stocks Own 13 1/2/2000 Stocks Online #get all combinations and aggregate join by unique values df = df1.groupby('Investment Type').agg(lambda x: ', '.join(x.unique())).reset_index() print (df) Investment Type Date New_Medium 0 Fixed Deposit 1/1/2000, 1/3/2000 Own, Online 1 Mutual Fund 1/1/2000, 1/2/2000 Own, Online 2 Real Estate 1/1/2000, 1/2/2000 Own, Online 3 Stocks 1/1/2000, 1/2/2000 Own, Online
has comment: http://stackoverflow.com/comment/95258852
accepted answer of: http://stackoverflow.com/q/52199952
has comment: http://stackoverflow.com/comment/95259058
answers question: http://stackoverflow.com/q/52199952
has comment: http://stackoverflow.com/comment/91383107
has comment: http://stackoverflow.com/comment/95258664
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91380878
type: Answer

http://stackoverflow.com/comment/91307708
comment on: http://stackoverflow.com/q/52178689
score: 0
type: Comment
type: QuestionComment
has text: Do you use `enctype="multipart/form-data"` in your ` ` tag in template?

http://stackoverflow.com/comment/91488600
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52270632
has text: Why don't you just try it?

http://stackoverflow.com/comment/91189664
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52118314
type: Comment
has text: What is your batch size currently? If you are getting very good accuracy in sample and poor accuracy out of sample, it may be due to overfitting, in which case you want to decrease your batch size.

http://stackoverflow.com/q/52208598
tagged with: image-segmentation
has comment: http://stackoverflow.com/comment/91369164
has comment: http://stackoverflow.com/comment/91369830
has answer: http://stackoverflow.com/a/52210595
answer count: 1
has comment: http://stackoverflow.com/comment/91369929
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91366695
has comment: http://stackoverflow.com/comment/91368073
tagged with: image-processing
has comment: http://stackoverflow.com/comment/91367481
type: Question
tagged with: labeling
has title: Image not labeling correctly: how to return only one connected component?
has comment: http://stackoverflow.com/comment/91367490
has body: I want to pre-process the image so that only the inner rectangular segment is kept (i.e. remove the surrounding background). But I'm not getting the correct result, which was shown as . for me. The code is quite simple: def labelim(img): #labeling image gray = rgb2gray(img) #translate rgb to gray val = filters.threshold_local(gray,5) mask = gray &gt; val clean_border = segmentation.clear_border(mask) labeled = label(clean_border) signle_labeled = np.where(labeled == 0,labeled, 1)#ensure all assigned label return as 1. return single_labeled def crop_img(img, labeled): cropped_images = [] pad = 20 for region in regionprops(labeled): if region.area &lt; 2000: continue minr,minc,maxr,maxc = region.bbox cropped_images.append(gray[minr-pad:maxr+pad, minc-pad:maxc+pad]) for c, cropped_image in enumerate(cropped_images): cropim = cropped_image return cropim labeled = labelim(img) cropped_image = crop_img(img, labeled) The testing code works for another one of my images, but not working for most of them. Thanks for any help/suggestion.
score: 0

http://stackoverflow.com/comment/91437287
has text: Hi fralau, I'm still learning what appropriate naming conventions are? Is there a good guide? I just try to be as descriptive as possible so that it's easy to read
comment on: http://stackoverflow.com/a/52223222
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91406493
type: AnswerComment
has text: So that worked great for a single folder of CSVs (thank you!!) but when I ran it in a directory with several subfolders it stopped working: Traceback (most recent call last): File "csv_remove_quotes_dir_walk.py", line 14, in <module> with open(fname, 'r') as infile:
type: Comment
comment on: http://stackoverflow.com/a/52228386
score: 0

http://stackoverflow.com/comment/91266504
score: 0
type: Comment
type: QuestionComment
has text: Is there a way, then, to HASH and SALT a password and then get the original form back? Using SHA_256 Encryption?
comment on: http://stackoverflow.com/q/52158102

http://stackoverflow.com/q/52134482
has title: Core dumped while passing double array from C to python using c extension module for python
type: Question
has comment: http://stackoverflow.com/comment/91263716
tagged with: numpy-ndarray
tagged with: ctypes
has body: I am writing a simple c code that will return a double array to python. I compiled the code successfully with out error and can generate .so file to import in python. However when I call the wrapped C function from Python environment I get core dump. I am attaching the c code below so that the error can be reproduced. I would be highly obliged if anyone directs me to point me to understand where am I going wrong which results in core dump error? While debuging I found that the source of the error is in the line pyArr = (PyArrayObject*) PyArray_SimpleNewFromData(2, dims, NPY_DOUBLE, ptr); yet I am unable to fix the issue. I also tried with static double array in line 6 but got same core dump issue. Any help is appreciated. #include &lt;Python.h&gt; #include &lt;numpy/arrayobject.h&gt; #include &lt;numpy/ndarrayobject.h&gt; extern "C" { static PyObject* func_wrap(PyObject* , PyObject* args) { double* ptr; ptr = (double *) malloc(4 * sizeof(double)); *ptr = 1.0; *(ptr+1) = 2.0; *(ptr+2) = 3.0; *(ptr+3) = 4.0; PyArrayObject* pyArr; npy_intp dims[1]; dims[0] = 4; pyArr = (PyArrayObject*)PyArray_SimpleNewFromData(1, dims, NPY_BYTE, ptr); PyArray_ENABLEFLAGS(pyArr, NPY_ARRAY_OWNDATA); /* numpy array takes the ownership afterwards */ return Py_BuildValue("O", pyArr); } static PyMethodDef CppMethods[] = { {"func", func_wrap, METH_VARARGS, "returns numpy 1d array"}, {NULL, NULL, 0, NULL} }; // Define module information static struct PyModuleDef mydemo = { PyModuleDef_HEAD_INIT, "mydemo", "mydemo Module", -1, CppMethods }; // Init function for module PyMODINIT_FUNC PyInit_mydemo(void) { import_array(); return PyModule_Create(&amp;mydemo); } }
downvote count: 0
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/91263021
tagged with: wrapper
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91220885
has comment: http://stackoverflow.com/comment/128382362
tagged with: python
has comment: http://stackoverflow.com/comment/91261188
has comment: http://stackoverflow.com/comment/91261505
score: 3
answer count: 0
upvote count: 3

http://stackoverflow.com/q/52225756
has answer: http://stackoverflow.com/a/52226058
accepted answer: http://stackoverflow.com/a/52226058
favorite count: 0
tagged with: unix-timestamp
has comment: http://stackoverflow.com/comment/91401230
tagged with: python
has title: python date unix 1 day is lost
type: AnsweredQuestion
score: 1
tagged with: date
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/91401632
has body: I have an error in python, when extracting one day. I'm converting to unix and extracting one day, yet the 11th of march - is always missing, no matter how big the dataset. Could anyone tell me what might be the error ? from time import localtime, mktime, strptime, strftime day = str(20180313) one_day = 86400 for i in range(1,5): print(day) previous_day_unix = int( mktime( strptime( day, "%Y%m%d")))-one_day day = strftime("%Y%m%d", localtime(int(previous_day_unix))) print(day)
answer count: 1
downvote count: 1

http://stackoverflow.com/a/52242308
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52241034
answers question: http://stackoverflow.com/q/52241034
type: Answer
has body: ffprobe offers a JSON writer as an output format. Set -of to json
score: 1
upvote count: 1

http://stackoverflow.com/q/52204952
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/52205115
tagged with: python-3.x
has title: Python3 dictionary comprehension with sub-dictionary upacking?
has answer: http://stackoverflow.com/a/52207444
type: Question
possible better answer: http://stackoverflow.com/a/52207182
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91359168
has answer: http://stackoverflow.com/a/52207182
has comment: http://stackoverflow.com/comment/91359212
linked to: http://stackoverflow.com/q/17915117
has comment: http://stackoverflow.com/comment/91358965
has answer: http://stackoverflow.com/a/52205115
linked to: http://stackoverflow.com/q/2802726
tagged with: dictionary-comprehension
tagged with: iterable-unpacking
has comment: http://stackoverflow.com/comment/91359015
score: 0
answer count: 3
has body: Suppose one has a dictionary, root which consists of key:value pairs, where some values are themselves dictionaries. Can one (and if so, how) unpack these sub dictionaries via dictionary comprehension? e.g. {k: v if type(v) is not dict else **v for k, v in root.items()} example: root = {'a': 1, 'b': {'c': 2, 'd': 3}} result = {'a': 1, 'c': 2, 'd': 3}
tagged with: python

http://stackoverflow.com/a/66985165
upvote count: 1
has body: The snipped above works but in sync mode, the asyncio call is the following: from telethon import TelegramClient from telethon.tl.functions.channels import InviteToChannelRequest, CreateChannelRequest, CheckUsernameRequest, UpdateUsernameRequest from telethon.tl.types import InputPeerChannel tm = TelegramClient(username, api_id, api_hash) tm.start(user_phone) async def proc(): created_private_channel = await tm(CreateChannelRequest( "Channel Title", "Channel description", broadcast=True, megagroup=False)) new_channel_id = created_private_channel.created_private_channel.chats[0].id new_channel_access_hash = created_private_channel.chats[0].access_hash check_channelname_result = await tm(CheckUsernameRequest( InputPeerChannel(channel_id=new_channel_id, access_hash=new_channel_access_hash), desired_ch_name)) if check_channelname_result: update_response = await tm(UpdateUsernameRequest( InputPeerChannel(channel_id=new_channel_id, access_hash=new_channel_access_hash), desired_ch_name)) print(f'update_response={update_response}') else: print(f'channelname={desired_ch_name} already taken') tm.loop.run_until_complete(proc())
answers question: http://stackoverflow.com/q/52160946
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/a/54234766
downvote count: 0
score: 6
has body: Are you using PostgreSQL or sqlite3? In your error message, the error come from sqlite3. In django docs the way you can using ArrayField is using postgresql as database.
upvote count: 6
answers question: http://stackoverflow.com/q/52153989
type: Answer

http://stackoverflow.com/comment/91312623
type: QuestionComment
has text: Possible duplicate of [How to add a padding to the data to make it acceptable for AES256 encryption algorithm in pycrypto library](https://stackoverflow.com/questions/2108047/how-to-add-a-padding-to-the-data-to-make-it-acceptable-for-aes256-encryption-alg)
comment on: http://stackoverflow.com/q/52181245
type: Comment
score: 0

http://stackoverflow.com/a/52123888
score: 1
has comment: http://stackoverflow.com/comment/91231685
has comment: http://stackoverflow.com/comment/91232202
has body: Using reindex with repeat df1.reindex(df1.index.repeat(df1.a)).assign(a=1).reset_index(drop=True) Out[1266]: a b 0 1 2 1 1 4 2 1 4 3 1 4 4 1 6 5 1 3 6 1 3 7 1 5
has comment: http://stackoverflow.com/comment/91230873
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91230833
accepted answer of: http://stackoverflow.com/q/52123449
type: Answer
answers question: http://stackoverflow.com/q/52123449
downvote count: 0

http://stackoverflow.com/comment/91359859
type: Comment
comment on: http://stackoverflow.com/a/52163728
type: AnswerComment
score: 0
has text: I just solved to problem. I used tf.where and tf.gather_nd. I would like to thank DomJack for help.

dataframe
tags question: http://stackoverflow.com/q/52253563
tags question: http://stackoverflow.com/q/52139725
tags question: http://stackoverflow.com/q/52266462
tags question: http://stackoverflow.com/q/52174027
tags question: http://stackoverflow.com/q/52163950
tags question: http://stackoverflow.com/q/52259270
tags question: http://stackoverflow.com/q/52174512
tags question: http://stackoverflow.com/q/52127766
tags question: http://stackoverflow.com/q/52134999
tags question: http://stackoverflow.com/q/52219200
tags question: http://stackoverflow.com/q/52233115
tags question: http://stackoverflow.com/q/52229804
tags question: http://stackoverflow.com/q/52206697
tags question: http://stackoverflow.com/q/52231902
tags question: http://stackoverflow.com/q/52232115
tags question: http://stackoverflow.com/q/52228639
tags question: http://stackoverflow.com/q/52120838
tags question: http://stackoverflow.com/q/52196080
tags question: http://stackoverflow.com/q/52209133
tags question: http://stackoverflow.com/q/52247112
tags question: http://stackoverflow.com/q/52190691
tags question: http://stackoverflow.com/q/52232315
tags question: http://stackoverflow.com/q/52254886
tags question: http://stackoverflow.com/q/52133815
tags question: http://stackoverflow.com/q/52129876
tags question: http://stackoverflow.com/q/52160472
tags question: http://stackoverflow.com/q/52227248
tags question: http://stackoverflow.com/q/52113834
tags question: http://stackoverflow.com/q/52208306
tags question: http://stackoverflow.com/q/52195838
tags question: http://stackoverflow.com/q/52146460
tags question: http://stackoverflow.com/q/52149477
tags question: http://stackoverflow.com/q/52153069
tags question: http://stackoverflow.com/q/52245582
tags question: http://stackoverflow.com/q/52123388
tags question: http://stackoverflow.com/q/52249017
tags question: http://stackoverflow.com/q/52180451
tags question: http://stackoverflow.com/q/52117162
tags question: http://stackoverflow.com/q/52154641
tags question: http://stackoverflow.com/q/52156423
tags question: http://stackoverflow.com/q/52241792
tags question: http://stackoverflow.com/q/52232910
tags question: http://stackoverflow.com/q/52164461
tags question: http://stackoverflow.com/q/52193571
tags question: http://stackoverflow.com/q/52251990
tags question: http://stackoverflow.com/q/52118820
tags question: http://stackoverflow.com/q/52223045
tags question: http://stackoverflow.com/q/52196134
tags question: http://stackoverflow.com/q/52204720
tags question: http://stackoverflow.com/q/52266458
tags question: http://stackoverflow.com/q/52224142
tags question: http://stackoverflow.com/q/52117704
tags question: http://stackoverflow.com/q/52233872
tags question: http://stackoverflow.com/q/52234531
tags question: http://stackoverflow.com/q/52143288
tags question: http://stackoverflow.com/q/52213416
tags question: http://stackoverflow.com/q/52128475
tags question: http://stackoverflow.com/q/52182361
tags question: http://stackoverflow.com/q/52147060
tags question: http://stackoverflow.com/q/52238877
tags question: http://stackoverflow.com/q/52210812
tags question: http://stackoverflow.com/q/52242962
tags question: http://stackoverflow.com/q/52166860
tags question: http://stackoverflow.com/q/52222929
tags question: http://stackoverflow.com/q/52231600
tags question: http://stackoverflow.com/q/52194145
tags question: http://stackoverflow.com/q/52175248
tags question: http://stackoverflow.com/q/52138325
tags question: http://stackoverflow.com/q/52125572
tags question: http://stackoverflow.com/q/52163161
tags question: http://stackoverflow.com/q/52232617
tags question: http://stackoverflow.com/q/52116984
tags question: http://stackoverflow.com/q/52268652
tags question: http://stackoverflow.com/q/52141517
tags question: http://stackoverflow.com/q/52152661
tags question: http://stackoverflow.com/q/52113181
tags question: http://stackoverflow.com/q/52234679
tags question: http://stackoverflow.com/q/52247837
tags question: http://stackoverflow.com/q/52124008
tags question: http://stackoverflow.com/q/52262519

http://stackoverflow.com/q/52255824
score: -1
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52256033
has body: I'm trying to run a simple linear fit to 373 data points and yet polyfit seems to fail and I'm not sure why. x = np.reshape(air_sst_new[:,90,180],(373)) y = np.reshape(olr_new[:,90,180],(373)) z = np.polynomial.polynomial.polyfit(x,y,1) plt.figure() plt.plot(x,y, '.') xx = np.linspace(np.min(x),np.max(x)) yy = np.polynomial.polynomial.polyval(xx, z) plt.plot(xx, yy) Plot showing original data and the fit The code written above works when using randomly generated points which is frustrating. example_x = np.random.rand(373,180,360) example_y = np.random.rand(373,180,360) x = np.reshape(example_x[:,90,180], (373)) y = np.reshape(example_y[:,90,180], (373)) z = np.polynomial.polynomial.polyfit(x,y,1) plt.figure() plt.plot(x,y, '.') xx = np.linspace(np.min(x), np.max(x)) yy = np.polynomial.polynomial.polyval(xx, z) plt.plot(xx, yy) Plot showing randomly generated data and correct fit
answer count: 1
accepted answer: http://stackoverflow.com/a/52256033
has comment: http://stackoverflow.com/comment/91458960
favorite count: 0
downvote count: 2
has title: np.polynomial.polynomial.polyfit doesn't seem to fit data in Python
tagged with: curve-fitting
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91470325
type: AnsweredQuestion
tagged with: matplotlib

http://stackoverflow.com/q/52135307
tagged with: matlab
tagged with: interpolation
upvote count: 1
tagged with: scipy
has title: What is the Python interpolate function which is the same as spapi in Matlab
has answer: http://stackoverflow.com/a/52138062
tagged with: spline
type: UnansweredQuestion
has body: In Matlab, I can use the spline interpolation function spapi to generate a spline curve, so that prescribed values of the curves and its first two derivatives can be matched. For example: spapi([0 0 0 0 1 2 2 2 2],[0 1 1 1 2],[2 0 1 2 -1]) this produces the unique cubic spline f on the interval [0..2] with exactly one interior knot, at 1, that satisfies the five conditions f(0)=2, f(1)=0, f'(1)=1, f''(1)=2, f(2)=–1 These include 3-fold matching at 1, i.e., matching there to prescribed values of the function and its first two derivatives. In Python, however, the spline interpolate function scipy.interpolate.splrep(x,y) can not work as x should be monotone increasing. So, how can I get a curve with prescribed values and derivative values? Is there any Python moldue or function? Many thanks!
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
answer count: 1

http://stackoverflow.com/a/52158856
answers question: http://stackoverflow.com/q/52142768
has body: You can use request to get the data from your HTML inputs. First import it from flask from flask import request By default Flask only allows GET requests. You'll need to allow POST methods to your route. @app.route('/placement_debugger', methods=['GET', 'POST') Here is how you can get the data from the HMTL form. (This would go in your get_data() function) if request.form: placement_id = request.form.get('Placement ID')
score: 0
type: Answer

http://stackoverflow.com/q/52153556
type: Question
has body: I have a regression model. I write code of this algorithm : create 10 random splits of training data into training and validation data. Choose the best value of alpha from the following set: {0.1, 1, 3, 10, 33, 100, 333, 1000, 3333, 10000, 33333}. To choose the best alpha hyperparameter value, you have to do the following: • For each value of hyperparameter, perform 10 random splits of training data into training and validation data as said above. • For each value of hyperparameter, use its 10 random splits and find the average training and validation accuracy. • On a graph, plot both the average training accuracy (in red) and average validation accuracy (in blue) w.r.t. each hyperparameter setting. Comment on this graph by identifying regions of overfitting and underfitting. • Print the best value of alpha hyperparameter. 2- Evaluate the prediction performance on test data and report the following: • Total number of non-zero features in the final model. • The confusion matrix • Precision, recall and accuracy for each class. Finally, discuss if there is any sign of underfitting or overfitting with appropriate reasoning I write This code : print('Accuracy of logistic regression classifier on test set: {:.2f}'.format(Newclassifier.score(X_test, y_test))) from sklearn.metrics import classification_report print(classification_report(y_test, y_pred)) My Questions is : 1- why accuracy in each iteration decrease? 2- is My model Overfit or underfit? 3- does My model work right?
score: 0
answer count: 1
favorite count: 0
has title: How to recognize Overfitting and underfitting in Python
tagged with: python
has answer: http://stackoverflow.com/a/52153764
accepted answer: http://stackoverflow.com/a/52153764
type: AnsweredQuestion
tagged with: machine-learning
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/52112496
type: Question
has comment: http://stackoverflow.com/comment/91175821
tagged with: django-models
has comment: http://stackoverflow.com/comment/91175882
has comment: http://stackoverflow.com/comment/91175960
accepted answer: http://stackoverflow.com/a/52113434
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91175904
has comment: http://stackoverflow.com/comment/91177280
tagged with: django
tagged with: python
has title: How to get last object in each hour over last 7 days in Django using DatetimeField column?
type: AnsweredQuestion
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/52113434
has body: I have been doing a task of filtering values from a table called 'Feeds', The row gets inserted every 10 mins into the system. ie. 6 rows every hour I am storing its datetime in a column called timestamp. I want to filter last row of each such hour of past 7 days. Here is my code. class Feeds(models.Model): value = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True)` Please Help to solve this. Thank you.

http://stackoverflow.com/a/52201887
has comment: http://stackoverflow.com/comment/91354050
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52201643
has comment: http://stackoverflow.com/comment/91352739
downvote count: 0
score: 1
has body: Your code already gives the answer. encoder has in its last layer lstm with two dimension (number_batch, number_features) instead of (number_batches, number_timesteps, number_features). This is because you did not set return_sequences = True(this is your intended behaviour). But what you want to do is the same, as what you do with your decoder: You apply the RepeatVector layer to make the input shape 3 dimensional and therefore able to be feeded into a LSTM Layer.

http://stackoverflow.com/q/52176999
has body: I'm trying to save a pdf file which is rendered using HTML to a model field right now, it throws this error. coercing to Unicode: need string or buffer, instance found this is the code def save_to_pdf(template_src, context_dict, pk): import ipdb; ipdb.set_trace() instance = get_object_or_404( Project.objects.filter(pk=pk, is_deleted=False)) template = get_template(template_src) context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result,link_callback=fetch_resources) pdfnew=file(pdf) instance.structural_info.save('structure.pdf',pdfnew) return True structural_info is the file field. What is the correct way to do it?
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/7514964
tagged with: python
has answer: http://stackoverflow.com/a/52178273
type: AnsweredQuestion
upvote count: 3
tagged with: file
tagged with: django
type: Question
score: 3
has title: Saving a rendered pdf file to model field Django
tagged with: django-models
accepted answer: http://stackoverflow.com/a/52178273
has comment: http://stackoverflow.com/comment/134180918
tagged with: http://stackoverflow.com/tag/pdf

http://stackoverflow.com/a/52136962
downvote count: 0
has body: You can make an entrypoint script that performs this before running your app. I'd likely deploy this using a compose file rather than directly in the image so that you don't have a dynamically updating container in production. Here's an example entrypoint script: #!/bin/sh # if a command is not provided, set a default command if [ $# -eq 0 ]; then set -- python app.py fi # update to new requirements on each container start pip --no-cache-dir install --upgrade -r requirements.txt # use exec to replace pid 1 with the command (e.g. python app.py) exec "$@" The Dockerfile would have this added, but I wouldn't change the current command: COPY entrypoint-dev.sh / Then in your development compose file, you can use that entrypoint: version: '3' services: app: image: app:dev entrypoint: - /entrypoint-dev.sh volumes: - .:/opt/code
answers question: http://stackoverflow.com/q/52127979
accepted answer of: http://stackoverflow.com/q/52127979
type: AcceptedAnswer
score: 4
type: Answer
upvote count: 4

http://stackoverflow.com/comment/91468536
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52224172
has text: @Mahesha999 Yes, you right. The point here is the output is the result of mixture of two loggers. You can easily change/tune them to know which logger gives the particular message.
type: Comment

http://stackoverflow.com/comment/91340400
has text: Hi @J.C.Rocamonde, I have tried the `path` way to define my URL and then send a request as `http://127.0.0.1:8000/api?url=https://i.imgur.com/TGJHFe1.jpg` but it returns `404 not found` error.
comment on: http://stackoverflow.com/a/52189270
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/52136385
has comment: http://stackoverflow.com/comment/91222667
has comment: http://stackoverflow.com/comment/91222842
has comment: http://stackoverflow.com/comment/91224053
has comment: http://stackoverflow.com/comment/91224506
has comment: http://stackoverflow.com/comment/91223427
has comment: http://stackoverflow.com/comment/91222554
tagged with: ipc
has comment: http://stackoverflow.com/comment/91222527
downvote count: 0
answer count: 1
has title: IPC using Named Pipes in C++ and Python program hangs
has body: I'm practicing IPC by using named pipes on Unix and trying to write a string in FIFO file using python &amp; reversing it through C++ program. But the program in Python gets hanged &amp; returns no result. Python Code For writing into file: import os path= "/home/myProgram" os.mkfifo(path) fifo=open(path,'w') string=input("Enter String to be reversed:\t ") fifo.write(string) fifo.close() The program hangs and doesn't ask for any input here. I get following error when I break out: Traceback (most recent call last): File "writer.py", line 4, in &lt;module&gt; fifo=open(path,'w') KeyboardInterrupt C++ code for reading from file: #include &lt;fcntl.h&gt; #include &lt;iostream&gt; #include &lt;sys/stat.h&gt; #include &lt;unistd.h&gt; #include &lt;string&gt; #include &lt;string.h&gt; #define MAX_BUF 1024 using namespace std; char* strrev(char *str){ int i = strlen(str)-1,j=0; char ch; while(i&gt;j) { ch = str[i]; str[i]= str[j]; str[j] = ch; i--; j++; } return str; } int main() { int fd; char *myfifo = "/home/myProgram"; char buf[MAX_BUF]; /* open, read, and display the message from the FIFO */ fd = open(myfifo, O_RDONLY); read(fd, buf, MAX_BUF); cout&lt;&lt;"Received:"&lt;&lt; buf&lt;&lt;endl; cout&lt;&lt;"The reversed string is \n"&lt;&lt;strrev(buf)&lt;&lt;endl; close(fd); return 0; } Since, the writer program fails to execute, unable to test the reader code and hence can't mention the result here. Please help.
has comment: http://stackoverflow.com/comment/91223371
favorite count: 0
tagged with: named-pipes
has comment: http://stackoverflow.com/comment/91222581
has comment: http://stackoverflow.com/comment/91222484
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91222548
tagged with: python
has comment: http://stackoverflow.com/comment/91223209
has comment: http://stackoverflow.com/comment/91225363
tagged with: c++
has comment: http://stackoverflow.com/comment/91223289
upvote count: 3
has answer: http://stackoverflow.com/a/52137319
has comment: http://stackoverflow.com/comment/91226279
has comment: http://stackoverflow.com/comment/91223346
type: Question
score: 3
has comment: http://stackoverflow.com/comment/91224111

http://stackoverflow.com/q/52179193
upvote count: 1
tagged with: django
accepted answer: http://stackoverflow.com/a/52179390
has body: I am using try except to handle errors in views.py. In the exception area i want to redirect user to a template if there is an error. While redirecting to the template, i want to pass errors to template and show errors at the beginning of that page. try: car.delete() except ProtectedError, e: return redirect(reverse('car-operations') + '?car_no=' + str(car.car_no), {'errors': e}) The ProtectError occurs when i try to delet the car. But this error is not passed to redirected page. In redicreted page i use below code to show errors. {% if errors %}&lt;div class="alert alert-danger"&gt;{{ errors }}&lt;/div&gt;{% endif %} I see that error occurs. But i couldn't pass it to template. If i use render request, i can pass the error to template but this time i can't call the template with "'?car_no=' + str(car.car_no)"
has title: Passing errors to redirected template in views.py in django
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/91308633
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52179390
tagged with: python
score: 1
tagged with: error-handling

http://stackoverflow.com/q/52167667
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91287065
upvote count: 2
has body: Pretty Self-explanatory. My sprite does not show up and there is just a white box. I am using Ubuntu 18.04.1 LTS and pygame version 1.9.3 I am using the code from Programming the raspberry pi by Simon Monk on page 107 if you are wondering import pygame from pygame.locals import * from sys import exit spoon_x = 300 spoon_y = 300 pygame.init() screen = pygame.display.set_mode((600,400)) pygame.display.set_caption('Raspberry Catching') spoon = pygame.image.load('/home/john/PycharmProjects/pygame/spoon.png').convert() while True: for event in pygame.event.get(): if event.type == QUIT: exit() screen.fill((255,255,255)) spoon_x, ignore = pygame.mouse.get_pos() screen.blit(spoon, (spoon_x, spoon_y)) pygame.display.update() spoon test
has title: White Box in Pygame
type: Question
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52169128
has comment: http://stackoverflow.com/comment/91288053
has comment: http://stackoverflow.com/comment/91286905
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52169128
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/91287372
has comment: http://stackoverflow.com/comment/91287480

http://stackoverflow.com/q/52264941
tagged with: opencv
has body: I have a pandas dataframe containing all values for each pixel in an image. Is there a way to use the x and y coordinate of a pixels location in the image to determine its index value? Xcord = 4 Ycord = 8 PandasIndexVal = Xcord*(NumberofCol)+ Ycord #or something like that. Another way I am trying to think of it as is thatch I have a 2d array (x by y) representing an image and I have another that is a flattened version of the same matrices and I need to find the two index values that line up.
answer count: 0
has title: Pandas determine intersection point from two dataframes of different shape
type: Question
has comment: http://stackoverflow.com/comment/91479285
tagged with: dataframe
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/91478739
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91443312
score: 0
type: QuestionComment
type: Comment
has text: Why doesn't your first example return `ABABACDEDEDFGA`? Also in your last example, how is the tolerance 2 when the string has 4 letters different than A? (B,B,C,D)
comment on: http://stackoverflow.com/q/52220462

http://stackoverflow.com/comment/91373808
score: 0
type: Comment
type: QuestionComment
has text: @thushv89 If this is the case, how can I rebuild a numpy ndarray object that I can pass to Keras? I've tried instantiating a new list and then passing it to `numpy.array` without success.
comment on: http://stackoverflow.com/q/52201744

http://stackoverflow.com/comment/91303304
type: Comment
has text: Not quite? I'd be interested to see cases where it fails. :-)
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52158526

http://stackoverflow.com/a/52146189
downvote count: 0
has comment: http://stackoverflow.com/comment/91242335
has comment: http://stackoverflow.com/comment/91247326
upvote count: 2
has comment: http://stackoverflow.com/comment/91248602
answers question: http://stackoverflow.com/q/52145649
has body: I would use regular expression. This little script searches for words with hyphenated and replaces the hyphenated by nothing. import re def replaceHyphenated(s): matchList = re.findall(r"\w+-\w+",s) # find combination of word-word sOut = s for m in matchList: new = m.replace("-","") sOut = sOut.replace(m,new) return sOut if __name__ == "__main__": s = """After the symposium, the Foundation and the FCF steering team continued their work and created the Func-tional Check Flight Compendium. This compendium contains information that can be used to reduce the risk of functional check flights. The information contained in the guidance document is generic, and may need to be adjusted to apply to your specific aircraft. If there are questions on any of the information in the compendi-um, contact your manufacturer for further guidance.""" print(replaceHyphenated(s)) output would be: After the symposium, the Foundation and the FCF steering team continued their work and created the Functional Check Flight Compendium. This compendium contains information that can be used to reduce the risk of functional check flights. The information contained in the guidance document is generic, and may need to be adjusted to apply to your specific aircraft. If there are questions on any of the information in the compendium, contact your manufacturer for further guidance. If you are not used to RegExp I recommend this site: https://regex101.com/
has comment: http://stackoverflow.com/comment/91242446
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91247677

http://stackoverflow.com/a/52176084
answers question: http://stackoverflow.com/q/52176002
type: Answer
has body: You can take input as string and split it to list For eg. eg="This is python program" print(eg) eg=eg.split() print(eg) This will give output This is python program ['This', 'is', 'python', 'program'] Hope this helps
score: 0

http://stackoverflow.com/a/52212329
answers question: http://stackoverflow.com/q/52212203
has body: The dictionary is updated because of the way you used the default value in the __init__ constructor. In the first case, that empty dict is a single object; it is not a unique constructor for each new object. It gets evaluated when the class is defined, and the same dict object sits there for each new object instantiated. Very simply, the line def __init__(self, x, y={}): is executed once, when the function is defined, during the class definition. In your second case, the initialization self.y = {} is in the body of the function, and so gets executed each time you instantiate a new object. You can see the longer explanation in this canonical posting on the topic.
type: Answer
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52212203

http://stackoverflow.com/comment/91403068
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52226782
type: QuestionComment
has text: The error you get you have quoted incorrectly in the title (I bet) and just describe in the body. Please quote literally and fully.

http://stackoverflow.com/a/52247549
type: Answer
has comment: http://stackoverflow.com/comment/91443054
answers question: http://stackoverflow.com/q/52247537
upvote count: 7
score: 7
accepted answer of: http://stackoverflow.com/q/52247537
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91443084
has body: The value of the yield expression after resuming depends on the method which resumed the execution. If __next__() is used (typically via either a for or the next() builtin) then the result is None. Otherwise, if send() is used, then the result will be the value passed in to that method. So this: def f(): yield (yield 1) Is equivalent to this: def f(): x = yield 1 yield x Which in this case (since you're not using generator.send()) is equivalent to this: def f(): yield 1 yield None Your code is only looking at the first item yielded by the generator. If you instead call list() to consume the whole sequence, you'll see what I describe: def f(): yield (yield 1) def g(): yield (yield (yield 1)) print(list(f())) print(list(g())) Output: $ python3 yield.py [1, None] [1, None, None] If we iterate the generator manually (as you have), but .send() it values, then you can see that yield "returns" this value: gen = f() print(next(gen)) print(gen.send(42)) Output: $ python3 yield_manual.py 1 42

http://stackoverflow.com/comment/91343096
has text: If you see the output, you will see it has 2 `AutoVerifiy`. It is failing to capture the autoverify under Filter #1 in the dataset. https://regex101.com/r/yfcjjG/2
comment on: http://stackoverflow.com/a/52196736
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/52122070
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52121947
has comment: http://stackoverflow.com/comment/91201973
type: Answer
answers question: http://stackoverflow.com/q/52121947
upvote count: 3
has comment: http://stackoverflow.com/comment/91196458
has comment: http://stackoverflow.com/comment/91195547
has body: You're going to need to pass the index to the form and then use that index for the offset. You probably need to add an orderby as well but I didn't include that here. Something like this: def index(): next_item = request.form.get('next_item') next_item_index = int(request.form.get('next_item_index', 0)) data = db.query(column='Nauka').offset(next_item_index).limit(1).all()[0] return render_template('home.html', data=data, next_item_index=next_item_index + 1) And in your HTML: {{ data.title }} {{ data.content }} Next You'll also need to handle the case where there is no next result, as it will almost certainly cause an exception in this code.
has comment: http://stackoverflow.com/comment/91195820
score: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91195805

http://stackoverflow.com/q/52164640
answer count: 1
tagged with: python-2.x
type: UnansweredQuestion
has body: My modelform is a dynamically generated modelform,I want to know the type of is_true in the modelForm. The type of the input tag is the checkbook type. If I know the type=‘checkbox’ of the is_true field, add a class attr to him separately. The default type='checkbox’ interface is too ugly models class Employee(AbstractBaseUser): """ 用户表 """ username = models.CharField(max_length=30, verbose_name='姓名') email = models.EmailField(verbose_name='邮箱', unique=True) is_true = models.BooleanField(default=False, verbose_name='是否超级用户') views class ModelFormDemo(ModelForm): class Meta: model = self.model if self.list_editable: fields = self.list_editable else: fields = '__all__' excluded = self.excluded def __init__(self, *args, **kwargs): super(ModelFormDemo, self).__init__(*args, **kwargs) def add_view(self, request): form = ModelFormDemo() if request.method == "POST": res_dict = {'status': 1, 'msg': 'success'} form = ModelFormDemo(request.POST) if form.is_valid(): obj = form.save() else: res_dict['msg'] = form.errors res_dict['status'] = 2 return JsonResponse(res_dict) return render(request, "xadmin/add_view.html", locals()) html {% csrf_token %} {% for field in form %} {% if field.name == 'employee' %} {% else %} {{ field.label }} {{ field }} {% endif %} {% endfor %} reset
tagged with: django
tagged with: python
has title: django modelform how to know input type is checkbook?
type: Question
has answer: http://stackoverflow.com/a/52170501
tagged with: python-2.7
score: 0

http://stackoverflow.com/a/52225346
type: Answer
downvote count: 0
score: 7
has body: According to this article https://www.pyimagesearch.com/2016/04/11/finding-extreme-points-in-contours-with-opencv/ and this question CV - Extract differences between two images I wrote some python code as below. As my predecessor said it is also far from perfect. The main disadvantages of this code are constants value to set manually: minThres (50), maxThres(100), dilate iteration count and erode iteration count. import cv2 import numpy as np windowName = "Edges" pictureRaw = cv2.imread("bird.jpg") ## set to gray pictureGray = cv2.cvtColor(pictureRaw, cv2.COLOR_BGR2GRAY) ## blur pictureGaussian = cv2.GaussianBlur(pictureGray, (7,7), 0) ## canny edge detector - you must specify threshold values pictureCanny = cv2.Canny(pictureGaussian, 50, 100) ## perform a series of erosions + dilations to remove any small regions of noise pictureDilate = cv2.dilate(pictureCanny, None, iterations=20) pictureErode = cv2.erode(pictureDilate, None, iterations=5) ## find the nozero regions in the erode imask2 = pictureErode&gt;0 ## create a Mat like pictureRaw canvas = np.full_like(pictureRaw, np.array([255,0,0]), dtype=np.uint8) ## set mask canvas[imask2] = pictureRaw[imask2] cv2.imwrite("result.png", canvas)
upvote count: 7
answers question: http://stackoverflow.com/q/52153979

numpy
tags question: http://stackoverflow.com/q/52136678
tags question: http://stackoverflow.com/q/52154835
tags question: http://stackoverflow.com/q/52220023
tags question: http://stackoverflow.com/q/52153594
tags question: http://stackoverflow.com/q/52258202
tags question: http://stackoverflow.com/q/52175284
tags question: http://stackoverflow.com/q/52190024
tags question: http://stackoverflow.com/q/52118339
tags question: http://stackoverflow.com/q/52260698
tags question: http://stackoverflow.com/q/52166639
tags question: http://stackoverflow.com/q/52240476
tags question: http://stackoverflow.com/q/52213628
tags question: http://stackoverflow.com/q/52201744
tags question: http://stackoverflow.com/q/52250486
tags question: http://stackoverflow.com/q/52267788
tags question: http://stackoverflow.com/q/52145755
tags question: http://stackoverflow.com/q/52152712
tags question: http://stackoverflow.com/q/52167672
tags question: http://stackoverflow.com/q/52118454
tags question: http://stackoverflow.com/q/52195716
tags question: http://stackoverflow.com/q/52172442
tags question: http://stackoverflow.com/q/52221393
tags question: http://stackoverflow.com/q/52126542
tags question: http://stackoverflow.com/q/52130441
tags question: http://stackoverflow.com/q/52120630
tags question: http://stackoverflow.com/q/52196699
tags question: http://stackoverflow.com/q/52254594
tags question: http://stackoverflow.com/q/52242916
tags question: http://stackoverflow.com/q/52247579
tags question: http://stackoverflow.com/q/52211929
tags question: http://stackoverflow.com/q/52223432
tags question: http://stackoverflow.com/q/52185208
tags question: http://stackoverflow.com/q/52254678
tags question: http://stackoverflow.com/q/52256932
tags question: http://stackoverflow.com/q/52226200
tags question: http://stackoverflow.com/q/52120776
tags question: http://stackoverflow.com/q/52258435
tags question: http://stackoverflow.com/q/52267545
tags question: http://stackoverflow.com/q/52218173
tags question: http://stackoverflow.com/q/52211898
tags question: http://stackoverflow.com/q/52210441
tags question: http://stackoverflow.com/q/52123272
tags question: http://stackoverflow.com/q/52216040
tags question: http://stackoverflow.com/q/52238567
tags question: http://stackoverflow.com/q/52225045
tags question: http://stackoverflow.com/q/52168400
tags question: http://stackoverflow.com/q/52243451
tags question: http://stackoverflow.com/q/52211906
tags question: http://stackoverflow.com/q/52176575
tags question: http://stackoverflow.com/q/52168164
tags question: http://stackoverflow.com/q/52159617
tags question: http://stackoverflow.com/q/52149479
tags question: http://stackoverflow.com/q/52133838
tags question: http://stackoverflow.com/q/52242859
tags question: http://stackoverflow.com/q/52154509
tags question: http://stackoverflow.com/q/52225908
tags question: http://stackoverflow.com/q/52250013
tags question: http://stackoverflow.com/q/52114107
tags question: http://stackoverflow.com/q/52232502
tags question: http://stackoverflow.com/q/52231446
tags question: http://stackoverflow.com/q/52235024
tags question: http://stackoverflow.com/q/52116786
tags question: http://stackoverflow.com/q/52117418
tags question: http://stackoverflow.com/q/52176395
tags question: http://stackoverflow.com/q/52165240
tags question: http://stackoverflow.com/q/52262516
tags question: http://stackoverflow.com/q/52136625
tags question: http://stackoverflow.com/q/52259981
tags question: http://stackoverflow.com/q/52195943
tags question: http://stackoverflow.com/q/52130109
tags question: http://stackoverflow.com/q/52153208
tags question: http://stackoverflow.com/q/52194838
tags question: http://stackoverflow.com/q/52176245
tags question: http://stackoverflow.com/q/52196509
tags question: http://stackoverflow.com/q/52243981
tags question: http://stackoverflow.com/q/52113401
tags question: http://stackoverflow.com/q/52207621
tags question: http://stackoverflow.com/q/52258617
tags question: http://stackoverflow.com/q/52179275
tags question: http://stackoverflow.com/q/52167120

http://stackoverflow.com/comment/91222939
type: AnswerComment
score: 1
type: Comment
has text: that may work...but may be slow. thanks anyway, until the idea comes up, I will do that way
comment on: http://stackoverflow.com/a/52136519

http://stackoverflow.com/a/52199941
score: 10
upvote count: 10
has body: You are looking for torch.set_default_tensor_type: torch.set_default_tensor_type(torch.DoubleTensor) Aletrnatively, you can use torch.set_default_dtype: torch.set_default_dtype(torch.float64)
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52199728

http://stackoverflow.com/q/52143512
has title: Selenium python: can't scroll down an overlay window
score: 0
answer count: 1
tagged with: quora
linked to: http://stackoverflow.com/q/15788679
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: On Quora, i want to scroll to the bottom of the window i am getting when clicking on view upvoters button, in order to get all upvoters names, the code for scrolling down a standard browser window does not seem to work with an overlay window, any suggestion? Here is my code for scrolldown function and for clicking on 'View upvoters' Button: def scrolldown(browser): src_updated = browser.page_source src = "" while src != src_updated: src = src_updated time.sleep(5) browser.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(5) src_updated = browser.page_source #if (DEBUG): print ("window maximized...") return browser browser.get('https://www.quora.com/What-is-it-like-to-regret-having-children') for p in browser.find_elements_by_class_name('AnswerVoterListModalLink'): time.sleep(5) p.click() time.sleep(5) browser=scrolldown(browser) time.sleep(5) c=0 for div in upvoter_name :#browser.find_elements_by_class_name('author_info'): list_of_upvoters.append(div.find_element_by_class_name('user').text) c+=1 print("number of upvoters for this answer is :" + str(c))
has answer: http://stackoverflow.com/a/52143739
linked to: http://stackoverflow.com/q/41744368
type: UnansweredQuestion
tagged with: selenium
tagged with: web-scraping
type: Question

http://stackoverflow.com/a/52130446
answers question: http://stackoverflow.com/q/52130409
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: You need to include a capture group inside the parenthesis. Also, when using extractall, I'd use unstack so it matches the structure of your DataFrame: df.header2.str.extractall(r'\((.*?)\)').unstack() 0 match 0 1 2 0 qwer NaN NaN 1 hghg lkjh NaN 2 poiu vbnc hjgk If you're concerned about performance, don't use pandas string operations: pd.DataFrame([re.findall(r'\((.*?)\)', row) for row in df.header2]) 0 1 2 0 qwer None None 1 hghg lkjh None 2 poiu vbnc hjgk
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91211312
accepted answer of: http://stackoverflow.com/q/52130409

http://stackoverflow.com/q/52210812
score: 4
upvote count: 4
has title: pandas - create new column based off of 'next' row value
answer count: 2
has answer: http://stackoverflow.com/a/52210835
tagged with: pandas
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/52210939
tagged with: python
has answer: http://stackoverflow.com/a/52210939
accepted answer: http://stackoverflow.com/a/52210835
type: Question
type: AnsweredQuestion
has body: I have the following dataframe: date country 6/1/18 USA 6/1/18 BEL 6/4/18 USA 6/5/18 BEL 6/6/18 USA I want to create a column that tells you what the next date for the corresponding country is. You can assume the dates are ordered if it helps. If the date is the last date for the country, you can fill in next date with the same date or a null value. date country next_date 6/1/18 USA 6/4/18 6/1/18 BEL 6/5/18 6/4/18 USA 6/6/18 6/5/18 BEL 6/5/18 6/6/18 USA 6/6/18
tagged with: dataframe

http://stackoverflow.com/comment/91511114
comment on: http://stackoverflow.com/a/52270855
has text: Sorry, you have to get the string value by using `message.content.startswith()` and try googling the command to see how it works because it only takes a string or a tuple of strings so `message.startswith('([;]|[?]|[!]+)` won't give you the correct result. Rather something like `message.content.startswith(';')`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/52217032
tagged with: list
score: 0
has answer: http://stackoverflow.com/a/52218209
type: UnansweredQuestion
has body: Im trying to take use certain items in this sublists and use it in a if statement it doesn't want to work its probably oblivious just cant seem to find anything on it path = [['Start', 'Centre', 2], ['East', 3, 2], ['West', 6, 3], ['North', 1, 1]] x = path[0] if x == 'Start': print(x)
answer count: 4
has answer: http://stackoverflow.com/a/52217229
tagged with: nested
has answer: http://stackoverflow.com/a/52217102
has answer: http://stackoverflow.com/a/52217125
tagged with: python-3.x
has title: Python extracting item from sublist into variable
type: Question
tagged with: python

http://stackoverflow.com/q/52137521
has body: I am working on a project that scan qrcodes on a product e.g Cup, and verify whether the product is the database or not, I have built the scanning app using Flutter, now my problem is creating QRCODES each having a unique identity or a specified URL that is linked to the database. I have tried to search on the internet how I can do this but I am not finding useful answers any provided on this will be highly appreciated thanks in advance!
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/52140186
upvote count: 1
tagged with: flutter
type: Question
type: AnsweredQuestion
tagged with: reactjs
accepted answer: http://stackoverflow.com/a/52140186
has title: Product verification using QRCODES
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91227794
has comment: http://stackoverflow.com/comment/91228852
favorite count: 0

http://stackoverflow.com/q/52191813
answer count: 1
has comment: http://stackoverflow.com/comment/91337679
has body: I'm playing a game in which to proceed to the next level, we must defeat each level before it. Each level corresponds to a certain letter. I've represented this as a graph traversal problem, but I'm trying to find all paths in a graph without a start or end node. My graph is represented as a dictionary, with the key being strings and the values being a list of strings. { 'A2': ['A1', 'B'], 'A1': [], 'B': [], 'C': ['A2'], } To go to level A2, we must complete A1 and B. For example, an example path would be A1, B, A2, C. Another path could be B, A1, A2, C. Implementations of depth first search or breadth first search require a start node. I'm thinking a good start node would be any key whose values are empty: in this case, A1 and B, but I'm uncertain how to implement dfs or bfs with two start nodes. I've been working with tweaking this implementation of finding paths, but this only works with a start level and an end level. def find_path(graph, start, end, path=[]): path = path + [start] if start == end: return path if start not in graph: return None for node in graph[start]: if node not in path: newpath = find_path(graph, node, end, path) if newpath: return newpath return None print(find_path(course_dict, 'A1', 'PC')) but I'm getting None for my answer.
score: 0
accepted answer: http://stackoverflow.com/a/52192026
tagged with: python
has title: find all paths in graph without start or end node
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91333815
has comment: http://stackoverflow.com/comment/91333534
type: Question
tagged with: graph
has comment: http://stackoverflow.com/comment/91333409
has answer: http://stackoverflow.com/a/52192026

http://stackoverflow.com/a/52198884
type: Answer
upvote count: 1
score: 1
has body: I didn't realize you need to use a inject node to inject a flow into the python function node to get the flow to work.
answers question: http://stackoverflow.com/q/52182757
downvote count: 0

http://stackoverflow.com/comment/91315332
has text: @Marisa - Yes, good idea. If working nice sample data problem is in data format obviously.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52181071

http://stackoverflow.com/q/52194927
has comment: http://stackoverflow.com/comment/91339446
has answer: http://stackoverflow.com/a/52195091
has title: How to generate all possible arrangements of numbers from a list in Python?
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/52194943
tagged with: permutation
has body: Problem: Given a list of 3 numbers [4, 8, 15] generate a list of all possible arrangements of the numbers. That's 3*3*3 = 27 unique entries from what I can gather. Something like: 4,4,4 4,4,8 4,4,15 4,8,4 4,8,8 4,8,15 4,15,4 4,15,8 4,15,15 ... I tried using itertools.permutations and itertools.combinations but I can't get all 27 values. list(itertools.permutations([4,8,15],3)) for example only prints 6 values: [(4, 8, 15), (4, 15, 8), (8, 4, 15), (8, 15, 4), (15, 4, 8), (15, 8, 4)] Is there something that's available out of the box or is this more of a "roll your own" problem?
favorite count: 0
possible better answer: http://stackoverflow.com/a/52194944
has answer: http://stackoverflow.com/a/52194944
accepted answer: http://stackoverflow.com/a/52194943
linked to: http://stackoverflow.com/q/3099987
tagged with: python
has comment: http://stackoverflow.com/comment/91339487
score: 2
upvote count: 2
duplicate of: http://stackoverflow.com/q/3099987
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/91466245
comment on: http://stackoverflow.com/q/52259159
score: 0
has text: ...and [here](https://stackoverflow.com/questions/18499497/how-to-process-sigterm-signal-gracefully)...SIGKILL?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52139598
score: 3
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52139518
answers question: http://stackoverflow.com/q/52139518
type: Answer
has comment: http://stackoverflow.com/comment/91298293
downvote count: 0
has body: You are looking at the documentation for Numpy 1.15, and this uses a new feature of nditer() introduced in that release: Under certain conditions, nditer must be used in a context manager When using an numpy.nditer with the "writeonly" or "readwrite" flags, there are some circumstances where nditer doesn’t actually give you a view of the writable array. Instead, it gives you a copy, and if you make changes to the copy, nditer later writes those changes back into your actual array. Currently, this writeback occurs when the array objects are garbage collected, which makes this API error-prone on CPython and entirely broken on PyPy. Therefore, nditer should now be used as a context manager whenever it is used with writeable arrays, e.g., with np.nditer(...) as it: .... You may also explicitly call it.close() for cases where a context manager is unusable, for instance in generator expressions. The error indicates you have an earlier version of Numpy; the with statement only works with context managers, which must implement __exit__ (and __enter__), and the AttributeError exception indicates that in your Numpy version the required implementation isn’t there. Either upgrade, or don't use with: for x in np.nditer(a, op_flags=['readwrite']): x[...] = 2 * x When using CPython you may still run into the issues that caused the change made in the 1.15 release however. When using PyPy you will run into those issues, and upgrading is your only proper recourse. You probably want to refer to the 1.14 version of the same documentation entry you used (or more specifically, make sure to pick the right documentation for your local version.

http://stackoverflow.com/q/52121761
has answer: http://stackoverflow.com/a/52121858
accepted answer: http://stackoverflow.com/a/52121858
type: Question
answer count: 2
upvote count: 1
tagged with: django-2.1
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/52121914
has title: Highlighted post in Django templates
has answer: http://stackoverflow.com/a/52121914
tagged with: python-3.x
has body: I've created this model: class PostModel(models.Model): post_title = models.CharField(max_length=70) post_short_description = models.TextField(max_length=200) post_contents = models.TextField() post_publishing_date = models.DateTimeField(auto_now=False, auto_now_add=True) post_author = models.ForeignKey(AuthorModel, on_delete=models.CASCADE) post_keyconcept = models.ManyToManyField(KeyConceptModel) slug = models.SlugField(verbose_name="Slug", unique="True") post_highlighted = models.BooleanField(default=False) def __str__(self): return self.post_title def get_absolute_url(self): return reverse("singlepostManuscriptusView", kwargs={"slug": self.slug}) class Meta: verbose_name = "Articolo" verbose_name_plural = "Articoli" I want use post_highlighted for put in a div only the article or the articles that have response true. How I can set up the "for cicle"? Here there is the cicle for show the list of posts: {% for posts in object_list %} {{ posts.post_title }} Pubblicato il Keywords: {% for keyword in object_list.all %} {{ keyword }} {% endfor %} {% empty %} Go to the admin panel and create your first post! {% endfor %}
has comment: http://stackoverflow.com/comment/91194847
tagged with: django
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/comment/91413924
has text: I already followed the instructions there but the jre folder is no longer under the jdk folder as of the current version so I specified the folder where it is installed
comment on: http://stackoverflow.com/q/52231907
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91298296
has text: Does the repeated second represent duplicated data? Or additional data without enough temporal precision. Only you can provide that answer.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52172098

http://stackoverflow.com/comment/91213304
comment on: http://stackoverflow.com/q/52131340
score: 0
type: Comment
has text: I using the version 2.1
type: QuestionComment

http://stackoverflow.com/a/52133155
has body: You can use a list comprehension and use list indexing twice to select your row and column: L = [[1, 4, 6], [6, 3, 7], [2, 7, 9]] n = len(L) res = [L[i][n-i-1] for i in range(n)] # [6, 3, 2] An alternative formulation is to use enumerate as per @OlivierMelançon's solution. If you can use a 3rd party library, you can use NumPy to extract the diagonal of a flipped array: import numpy as np arr = np.array(L) res = np.diag(np.fliplr(arr)) # array([6, 3, 2])
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52131612

http://stackoverflow.com/q/52189075
has title: Cannot scrape crumb from yahoo finance
score: 3
type: Question
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/44112403
has answer: http://stackoverflow.com/a/52201721
has answer: http://stackoverflow.com/a/52189934
tagged with: python
tagged with: yahoo-finance
favorite count: 0
has comment: http://stackoverflow.com/comment/91334630
upvote count: 3
type: UnansweredQuestion
has body: I am trying to scrape the historical data from Yahoo finance stocks. I found some code from the internet and modified it. It worked at first, but now I cannot scrape the crumb from yahoo. Can anyone advise how to fix this? The first time I scraped yahoo, it scraped 20 sets of data and stopped working. I started it again and it did't work The relevant code is attached below def _get_crumbs_and_cookies(stock): """ get crumb and cookies for historical data csv download from yahoo finance parameters: stock - short-handle identifier of the company returns a tuple of header, crumb and cookie """ url = 'https://finance.yahoo.com/quote/{}/history'.format(stock) with requests.session(): header = {'Connection': 'keep-alive', 'Expires': '-1', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) \ AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36' } website = requests.get(url, headers=header) soup = BeautifulSoup(website.text, 'lxml') crumb = re.findall('"CrumbStore":{"crumb":"(.+?)"}', str(soup)) return (header, crumb[0], website.cookies) And the entire original code can be found at: https://maikros.github.io/yahoo-finance-python/ Thanks in advance for your help

http://stackoverflow.com/comment/91340515
type: AnswerComment
score: 0
has text: Firstly thank you very much for showing interest. I have already posted the desired output. All I need is dependency relationship path which I have already shown in question Maybe you are correct that the dependency relationship can't be represented in tree structure but I don't even need that. I just need the root-to-leaf dependency relation path.
type: Comment
comment on: http://stackoverflow.com/a/52161069

http://stackoverflow.com/q/52242843
downvote count: 1
type: Question
has title: How to render my Sudoku generator results to html table using Django?
tagged with: javascript
accepted answer: http://stackoverflow.com/a/52243100
score: 0
has comment: http://stackoverflow.com/comment/91434373
answer count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: python
tagged with: sudoku
has comment: http://stackoverflow.com/comment/91434068
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52243100
has body: I am pretty new to Django and currently making a Sudoku web app. I wrote a python program to generate the Sudoku games, here is an example of the result/matrix looks like when i run the code (Sudoku Generator.py). [[3, 8, 2, 7, 5, 6, 1, 4, 9],[1, 4, 5, 2, 3, 9, 6, 7, 8],[6, 7, 9, 1, 4, 8, 2, 3, 5],[2, 1, 3, 4, 6, 5, 8, 9, 7],[4, 5, 6, 8, 9, 7, 3, 1, 2],[7, 9, 8, 3, 1, 2, 4, 5, 6],[5, 2, 1, 6, 7, 3, 9, 8, 4],[8, 3, 7, 9, 2, 4, 5, 6, 1],[9, 6, 4, 5, 8, 1, 7, 2, 3]] My question is, how can I render all these generated numbers to my html file? here is the html codes i've created under the templates: {% extends 'base.html' %} {% block sudoku %} Sudoku of the day {% endblock %} Basically what I wanted is to get each number populated to each tag accordingly; also, whenever clicks "next game" button, the board will refresh and generate another bunch of numbers to form a new game. Attached is the screen shot of my Django work project directory so far: mysite directory Now I totally got stuck, not sure if what i've done so far is correct and don't know what to do next... Anyone can help??
upvote count: 1

http://stackoverflow.com/comment/91395932
type: AnswerComment
comment on: http://stackoverflow.com/a/52214736
type: Comment
has text: Can you post the stack trace for the error? Is it happening in the view or in the template?
score: 0

http://stackoverflow.com/comment/91427419
type: Comment
type: QuestionComment
has text: did you execute the 'collectstatic' command? https://docs.djangoproject.com/en/2.1/howto/static-files/#deployment
comment on: http://stackoverflow.com/q/52239344
score: 0

http://stackoverflow.com/comment/104005087
score: 1
type: AnswerComment
has text: @markusN looks like they [took my advice to heart](https://trac.osgeo.org/grass/changeset/73906).
comment on: http://stackoverflow.com/a/52541326
type: Comment

http://stackoverflow.com/comment/95573744
score: 0
comment on: http://stackoverflow.com/a/52136757
type: Comment
type: AnswerComment
has text: @JingpengWu, a quick-and-dirty approach would be to copy the array and then transpose the copy.

http://stackoverflow.com/comment/91357955
score: 0
type: Comment
has text: The problem is that i don't have a triangulation per se. I have elements with 4 nodes, and i think that `tricontour` only works for triangles..
type: AnswerComment
comment on: http://stackoverflow.com/a/52203447

http://stackoverflow.com/comment/91268520
comment on: http://stackoverflow.com/q/52135667
score: 0
has text: What is param, and why is your instantiation not in a comprehension? It looks like you're jumping through ridiculous hoops to achieve a trivial result.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91259231
comment on: http://stackoverflow.com/a/52154264
has text: @user61629 Show us your template setting in `settings.py`. Did you add `templates` to `DIRS` ??
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/52186641
accepted answer of: http://stackoverflow.com/q/52186560
answers question: http://stackoverflow.com/q/52186560
has comment: http://stackoverflow.com/comment/91324535
upvote count: 2
has body: Is there a way to tell pandas that not all of the column headings in the 'names' list may be present? You can simply omit the names parameter: df = pd.read_csv(fle, delim_whitespace=True, error_bad_lines=False, encoding='utf-8', skiprows=7) Then assign column names in a subsequent step: n = len(df.columns) df.columns = ['Time (s)'] + [f'Col{i}' for i in range(1, n-1)] + ['Important']
score: 2
has comment: http://stackoverflow.com/comment/91325012
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91324632
type: Answer

http://stackoverflow.com/q/52112774
score: -1
type: Question
has answer: http://stackoverflow.com/a/52112847
upvote count: 0
has comment: http://stackoverflow.com/comment/91176539
has body: I have a user defined list(so it is not static.For example's sake let's say the user entered the following elements in the list) ['sam', '25', 'matt', '30', 'jack', '27'] Is it possible to convert it into dictionary with name as key and age as value?
has comment: http://stackoverflow.com/comment/91176299
has title: dictionary from a single list in python
favorite count: 0
has comment: http://stackoverflow.com/comment/91176416
answer count: 3
has comment: http://stackoverflow.com/comment/91176616
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52112920
linked to: http://stackoverflow.com/q/4576115
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91176169
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/91176079
has comment: http://stackoverflow.com/comment/91176050
duplicate of: http://stackoverflow.com/q/4576115
has answer: http://stackoverflow.com/a/52112878
linked to: http://stackoverflow.com/q/6900955

http://stackoverflow.com/q/52205363
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52213157
favorite count: 0
tagged with: python
has title: Have nosetests ignore minimum coverage if exit due to test failure?
tagged with: nose
type: UnansweredQuestion
upvote count: 1
tagged with: unit-testing
type: Question
has body: On my test runner to determine if a git branch passes or fails, I test my python like so: nosetests -x --with-coverage ${PACKAGE} --cover-min-percentage=80 The -x (exit on first failure) is a new addition, as we want to immediately fail the build if any unit tests fail. However, if an early test fails and we exit, nosetests falsely says that min coverage has not been met if some of the early packages have low coverage because it wasn't able to cover everything. How can I have the coverage check be aborted/ignored if any tests fail?
answer count: 1

http://stackoverflow.com/q/52226044
duplicate of: http://stackoverflow.com/q/34567037
downvote count: 0
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91401715
has comment: http://stackoverflow.com/comment/91401660
has comment: http://stackoverflow.com/comment/91401756
has comment: http://stackoverflow.com/comment/91401965
tagged with: windows
tagged with: python
tagged with: cmd
favorite count: 0
tagged with: py2neo
linked to: http://stackoverflow.com/q/17557168
has comment: http://stackoverflow.com/comment/91415073
type: Question
has comment: http://stackoverflow.com/comment/91401810
upvote count: 1
has answer: http://stackoverflow.com/a/52226154
answer count: 1
has title: python code works fine on python shell but not through cmd when importing py2neo
linked to: http://stackoverflow.com/q/34567037
duplicate of: http://stackoverflow.com/q/17557168
has body: as said in the title I'm having problem runnig my code from cmd which is working just fine in python shell. I have py2neo version 4. here is my code: from py2neo import Graph print ("passed") here is the output from python shell: passed &gt;&gt;&gt; here is the output from cmd command: D:\py2neo&gt;python py2neo.py Traceback (most recent call last): File "py2neo.py", line 1, in &lt;module&gt; from py2neo import Graph File "D:\ALI\Desktop\ayten\mine-py2neo\py2neo.py", line 1, in &lt;module&gt; from py2neo import Graph ImportError: cannot import name 'Graph' I've been searching, the answer out there were the different versions of python that I have on my system, which has cause this problem. But I checked that out and realized that both of them have the same version. here is how i figured out the versions: opening the python shell: Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. &gt;&gt;&gt; in cmd: D:\py2neo&gt;python --version Python 3.6.4 D:\py2neo&gt;python Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; Thank you in advance.

http://stackoverflow.com/comment/91470392
type: AnswerComment
score: 0
has text: If you don't want to look at the docs (link in my first comment), install OutlookSpy and take a look at the live objects.
type: Comment
comment on: http://stackoverflow.com/a/52207308

http://stackoverflow.com/comment/91197470
type: QuestionComment
type: Comment
has text: The second code has a syntax error. And, afaik, that error can only happen when dealing with lists, and your code doesn't use any. Please show this as a proper [mcve]. There's no effective difference between the two that I can see with respect to that error. `j` must be becoming a list somewhere.
comment on: http://stackoverflow.com/q/52123099
score: 0

http://stackoverflow.com/a/52249977
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52249912
type: Answer
has body: You'll need to check the API Documentation but generally there will be a parameter "maxResults (or similar) that you can add to the url to retrieve more than the default number of results. Your request (by modify the query string in the url) would look something like this: resp = requests.get ('apipath' &amp; '?company=XXXX&amp;maxResults=1000', auth=(XXXXX', 'XXXXXX'))
upvote count: 1

http://stackoverflow.com/q/52154912
tagged with: python-3.x
has title: list sorting returning unexpected output
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52154964
accepted answer: http://stackoverflow.com/a/52154964
type: Question
has body: Input 4 2 4 5 9 4 2 4 11 12 Output 11 12 5 9 Expected output 5 9 11 12 I was expecting the list to be sorted but it is getting sorted according to the sets , even after it was converted from the set to a list. Code m = int(input()) minp=input().split() n = int(input()) ninp=input().split() a,b=set(minp),set(ninp) set3=list(b.difference(a).union(a.difference(b))) set3.sort() for i in set3: print(i)
score: 0
answer count: 1

http://stackoverflow.com/q/52130087
tagged with: algorithm
tagged with: java
type: Question
score: 0
answer count: 2
has body: I came across the following question. Given a list where each item represents the duration expressed in seconds of a song, return the total number of pairs of songs such their durations sum to minutes (e.g., 1m0s, 2m0s,..) Example: Input: [10,50,20,110,40] Output: 3 (considering pairs at indexes (0,1),(0,3),(2,4)) I can only think to a brute force approach where I consider all pairs of songs. The time complexity of this approach is O(n^2). Is there any better way of doing it?
tagged with: time-complexity
favorite count: 0
upvote count: 3
has answer: http://stackoverflow.com/a/52132569
has title: Counting efficiently all the pairs with given sum
tagged with: python
type: UnansweredQuestion
downvote count: 3
has answer: http://stackoverflow.com/a/56094820

http://stackoverflow.com/comment/91595224
has text: I did what you said however I see nothing within the developer console. Would you like me to make an edit to my main post to see what I did wrong
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52171603
type: Comment

http://stackoverflow.com/q/52255737
has comment: http://stackoverflow.com/comment/91460360
has comment: http://stackoverflow.com/comment/91460163
tagged with: rar
has body: I wanted to collect comment data of a zip file from multiple files(as the optional comment you get on the side when opening a Zip or a Rar file) but now I realize that they are not Zip but Rar files, what do i need to change in order for it to work on a Rar file? import unicodedata from zipfile import ZipFile rootFolder = u"C:/Users/user/Desktop/archives/" zipfiles = [os.path.join(rootFolder, f) for f in os.listdir(rootFolder)] for zfile in zipfiles: print("Opening: {}".format(zfile)) with ZipFile(zfile, 'r') as testzip: print(testzip.comment) # comment for entire zip l = testzip.infolist() #list all files in archive for finfo in l: # per file/directory comments print("{}:{}".format(finfo.filename, finfo.comment))
has answer: http://stackoverflow.com/a/58760120
type: Question
answer count: 1
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91461161
tagged with: python
has comment: http://stackoverflow.com/comment/91460469
has title: Collecting comment data from multiple Rar files without unzipping
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/q/52174164
has title: Passing a Python list to function, to insert into json list
score: 0
accepted answer: http://stackoverflow.com/a/52174234
has body: I am passing URLs to a filtering service. The json body I post is: body = { "url-filter": [ "www.reddit.com", "www.cnn.com", "www.espn.com" ] } I would like to create a function that will allow me to pass one or more URLs to filter. What is unclear to me is: 1) How I should pass these URLs to a function - Python list? The URLs do not need to retain order/sequence. 2) How I should insert the URLs into this json body? Is there a function that will do this or is something more required?
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52174458
has answer: http://stackoverflow.com/a/52174458
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52174234

http://stackoverflow.com/q/52262524
linked to: http://stackoverflow.com/q/18114138
has body: I need to get phi-function (Euler's) of some randomly generated 128-bit numbers. I tried to use this code below but computer is just thinking too much. import fractions def phi(n): amount = 0 for k in range(1, n + 1): if fractions.gcd(n, k) == 1: amount += 1 return amount Is there something faster?
answer count: 1
has comment: http://stackoverflow.com/comment/91473442
favorite count: 0
has comment: http://stackoverflow.com/comment/91472906
tagged with: bignum
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/91474411
has comment: http://stackoverflow.com/comment/91472991
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/52263174
tagged with: math
has comment: http://stackoverflow.com/comment/91473381
type: Question
has comment: http://stackoverflow.com/comment/91473447
has answer: http://stackoverflow.com/a/52263174
score: 4
has title: Is there a fast algorithm for Euler's totient function of BIG numbers (128bit)?

http://stackoverflow.com/comment/91232100
has text: Could you please post your python code. @DjKniteX
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52140023

http://stackoverflow.com/q/52198414
tagged with: http://stackoverflow.com/tag/xml
has answer: http://stackoverflow.com/a/52200547
has comment: http://stackoverflow.com/comment/91348524
type: Question
tagged with: odoo
has comment: http://stackoverflow.com/comment/91349278
has comment: http://stackoverflow.com/comment/91348199
has comment: http://stackoverflow.com/comment/91348418
score: 0
has comment: http://stackoverflow.com/comment/91347209
has comment: http://stackoverflow.com/comment/91347272
has title: Odoo 10 - install data from a model automatically when installing a custom module
answer count: 1
has body: I want to install the installer I wanted to know if it is possible? And how to proceed? While searching on the internet, I saw this tutorial well presented. However, I do not see how the table will be correctly filled to a module. Will you help me? Thank you
has comment: http://stackoverflow.com/comment/91348333
has comment: http://stackoverflow.com/comment/91347330
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52231692
score: -1
has title: Creating an if, else statement for answers accordingly to the self.questions list
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91412887
tagged with: tkinter
type: UnansweredQuestion
downvote count: 1
has body: How do I create these if and else statements from the self.questions list? What I am trying to do right now is that when the program is run, there are three option boxes with answers in each one. I want the user to select one of those answers and see if they are correct or not according to the answers in the self.questions list corresponding to the asked question. def __init__(self): self.newWindow = self.new_window('QUESTION') self.window = self.newWindow #This is a counter for the questions self.question_counter = 0 #This is the questions, there is a list of questions self.questions = ["Question One: What is the capital of France?", "Question Two: What martial arts movie was first produced by Hollywood?", "Question Three: What year did World War II start?", "Question Four: What year did Abraham Licoln get assassinated?"] #This is the answers, there is a list of three possible answers for each question self.answers = [["Madrid", "London", "Paris"], ["The Karate Kid", "Enter the Dragon", "Ip Man"], ["1914", "1939", "1940"], ["1865", "1912", "1688"]] self.label = Label(self.newWindow, text=self.questions[self.question_counter], font = ("Arial", "24"), pady=30) self.answer1button = Button(self.window, text=self.answers[self.question_counter][0]) self.answer2button = Button(self.window, text=self.answers[self.question_counter][1]) self.answer3button = Button(self.window, text=self.answers[self.question_counter][2])
type: Question
has answer: http://stackoverflow.com/a/52236771

http://stackoverflow.com/q/52137645
type: Question
tagged with: mnist
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52145642
has body: I am new to Machine Learning and I was given the task of replicating the code from Binarized Neural Networks: Training Neural Networks with Weights and Activations Constrained to +1 or −1 . I would like to implement it on Keras. I have written the code as shown below, however, the result obtained is stuck at 9.87% BNN.ipynb import keras from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D,Dropout, Flatten, Dense from keras.datasets import mnist from keras.layers import Dense, Activation, BatchNormalization from keras.constraints import min_max_norm from keras.optimizers import SGD from activations import binary_tanh as binary_tanh_op #Load the data (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = X_train.reshape(-1, 784) X_test = X_test.reshape(-1, 784) X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 #one-hot encoding y_train = keras.utils.to_categorical(y_train, 10) y_test = keras.utils.to_categorical(y_test, 10) #import to obtain _hard_tanh activation def binary_tanh(x): return binary_tanh_op(x) model = Sequential() model.add(Dense(256, input_dim=784, activation=binary_tanh, kernel_initializer='glorot_uniform', bias_initializer='zeros')) BatchNormalization(momentum=0.9,epsilon=0.000001) model.add(Dense(128,activation=binary_tanh)) BatchNormalization(momentum=0.9,epsilon=0.000001) model.add(Dense(64,activation=binary_tanh)) BatchNormalization(momentum=0.9,epsilon=0.000001) model.add(Dense(10, activation=binary_tanh)) # Step 2: Build the Model print(model.summary()) for layer in model.layers: h = layer.get_weights() print(h) opt = SGD(lr=0.000001) # Step 3: Compile the Model model.compile(loss='categorical_crossentropy',optimizer=opt,metrics=['accuracy']) # Step 4: Train the Model model.fit(X_train,y_train,epochs=50,batch_size=100) This is the activations.py file from __future__ import absolute_import import keras.backend as K def round_through(x): '''Element-wise round…
tagged with: neural-network
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/52137667
tagged with: python
linked to: http://stackoverflow.com/q/36456436
type: UnansweredQuestion
has title: Keras Accuracy not changing for MNIST Dataset
tagged with: machine-learning
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/91320181
has text: You don't need to pass self to a class method, it's passed automatically, so that should say '...command=self.createCaseDetails, width=30...'
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52181202

http://stackoverflow.com/q/52234935
accepted answer: http://stackoverflow.com/a/52294604
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52294604
tagged with: report
tagged with: matplotlib
has title: Which is the best way to make a report in PDF with more than 100 plots with Python?
linked to: http://stackoverflow.com/q/29414060
type: Question
has comment: http://stackoverflow.com/comment/91418932
tagged with: pandas
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
downvote count: 0
favorite count: 0
has body: I need to have a report in PDF with a lot of plots. Most of them will be created with matplotlib within a loop, but I would need also to include pandas plots and dataframes (the whole view) and seaborn plots. Right now I have explored the following solutions: PythonTex. I have already used it for other projects, but it would consume a lot of time because you have to write \pythontexprint for each plot you want to display. Use savefig command in every iteration of the loop and save all the plots as image for inserting all in Latex later. That would be very time consuming choice too. Other option is with that command save the plots as pdf and then merge all the pdfs. That would create an ugly report since the plots are not going to fit the whole page. Use RStudio with reticulate for creating a Markdown report. The problem here is that I would need to learn reticulate functionality, thus spending time. As far as I know, PyPDF does not fit my needs. Create a jupyter notebook and then try to export it to a PDF. Once again, I do not know how to use jupyter notebook and I read that I would have to convert first to html and then to pdf. Solutions from here: Generating Reports with Python: PDF or HTML to PDF However, the question is from three years ago and it might better options nowadays. So my question is the following: is there any easy and quick way of getting all those plots (if it is along the code which generates them even better) in a PDF with a decent aspect?

http://stackoverflow.com/comment/91180929
score: 0
type: Comment
has text: Ok, How do I take an input and perform the aggregation based on the input?
type: AnswerComment
comment on: http://stackoverflow.com/a/52113275

http://stackoverflow.com/comment/91189289
has text: Instead,I suggest that you pick your first problem and post a [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) to give us a good, focused problem to solve.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52119138

storage
tag name: storage
tags question: http://stackoverflow.com/q/52144829
tags question: http://stackoverflow.com/q/52163770
type: Tag

http://stackoverflow.com/q/52210108
tagged with: python
has body: I have a dataframe like this: userId dateTime 2233 2018-08-01 12:30:29 1455 2018-08-01 13:08:01 2233 2018-08-01 15:08:01 1909 2018-08-01 15:18:01 2233 2018-08-01 17:58:01 1455 2018-08-01 19:08:01 So I want to append a new column, based on the nth time the same user is appearing. So my desired dataframe will look something like this: userId dateTime Appearance_no 2233 2018-08-01 12:30:29 1 1455 2018-08-01 13:08:01 1 2233 2018-08-01 15:08:01 2 1909 2018-08-01 15:18:01 1 2233 2018-08-01 17:58:01 3 1455 2018-08-01 19:08:01 2 which is almost similar like a serial no., but I'm not able to generate the column.
has answer: http://stackoverflow.com/a/52210156
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/52215318
accepted answer: http://stackoverflow.com/a/52210156
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
has title: Create a Pandas Column based on n-th repetition of a value
favorite count: 0
type: Question

http://stackoverflow.com/a/52266897
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52266168
has body: Reimplementing QCheckBox.hitButton and replacing SE_CheckBoxClickRect with SE_CheckBoxIndicator is indeed the right approach to make only the check indicator clickable. I have tested it in C++ and it works as expected: bool CheckBox::hitButton(const QPoint &amp;pos) const { QStyleOptionButton opt; initStyleOption(&amp;opt); return style()-&gt;subElementRect(QStyle::SE_CheckBoxIndicator, &amp;opt, this).contains(pos); } Now, try to exactly translate that to Python, including the call to initStyleOption you are missing: def hitButton(self, pos): opt = QStyleOptionButton() self.initStyleOption(opt) return self.style().subElementRect(QStyle.SE_CheckBoxIndicator, opt, self).contains(pos)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91481699
answers question: http://stackoverflow.com/q/52266168
type: Answer
score: 1

http://stackoverflow.com/comment/91186570
has text: I need car's value. I need to compare the values from Bike and Cars whenever a city have bike.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52115845

http://stackoverflow.com/comment/91334507
type: Comment
comment on: http://stackoverflow.com/a/52192154
has text: Nice Idea! However it does not work in all cases, like in [this one](https://gist.github.com/Dobiasd/352f9b4f188a941b1728f402d4bb0e53).
score: 1
type: AnswerComment

http://stackoverflow.com/a/52166339
score: 0
has comment: http://stackoverflow.com/comment/91284174
has comment: http://stackoverflow.com/comment/91283247
type: Answer
has comment: http://stackoverflow.com/comment/91282631
answers question: http://stackoverflow.com/q/52166034
has body: Numpy to the rescue! Specifically, you need a multinomial distribution: import numpy as np desired_sum = 100 n = 10 np.random.multinomial(desired_sum, np.ones(n)/n, size=1000000) It outputs a matrix with a million rows of 10 random integers in a few seconds. Each row sums up to 100. Here's a smaller example: np.random.multinomial(desired_sum, np.ones(n)/n, size=10) which outputs: array([[ 8, 7, 12, 11, 11, 9, 9, 10, 11, 12], [ 7, 11, 8, 9, 9, 10, 11, 14, 11, 10], [ 6, 10, 11, 13, 8, 10, 14, 12, 9, 7], [ 6, 11, 6, 7, 8, 10, 8, 18, 13, 13], [ 7, 7, 13, 11, 9, 12, 13, 8, 8, 12], [10, 11, 13, 9, 6, 11, 7, 5, 14, 14], [12, 5, 9, 9, 10, 8, 8, 16, 9, 14], [14, 8, 14, 9, 11, 6, 10, 9, 11, 8], [12, 10, 12, 9, 12, 10, 7, 10, 8, 10], [10, 7, 10, 19, 8, 5, 11, 8, 8, 14]]) The sums appear to be correct: sum(np.random.multinomial(desired_sum, np.ones(n)/n, size=10).T) # array([100, 100, 100, 100, 100, 100, 100, 100, 100, 100]) Python only You could also start with a list on 10 zeroes, iterate 100 times and increment a random cell each time : import random desired_sum = 100 n = 10 row = [0] * n for _ in range(desired_sum): row[random.randrange(n)] += 1 row # [16, 7, 9, 7, 10, 11, 4, 19, 4, 13] sum(row) # 100

http://stackoverflow.com/q/52225009
has title: How to construct regex to identify dollar ($) money sum
has body: I'm trying to create a regex that can identify sum of money (in dollars). The problem is that the data is generated by OCR on scanned PDF files, so the data is not precise: $ can be represented by S . can be represented by , 1 can be represented by l or I 5 can be represented by S Examples: Data: What is should be: S0.01 =&gt; $0.01 S1 =&gt; $1 S400.05 =&gt; $400.05 $0,01 =&gt; $0.01 S0,SI =&gt; $0.51 Question: Is it possible to construct a regex that can search for such a complex pattern?
upvote count: 1
has answer: http://stackoverflow.com/a/52225190
type: Question
has comment: http://stackoverflow.com/comment/91399470
tagged with: dollar-sign
has comment: http://stackoverflow.com/comment/91399252
answer count: 1
accepted answer: http://stackoverflow.com/a/52225190
downvote count: 0
has comment: http://stackoverflow.com/comment/91399811
favorite count: 0
tagged with: python
tagged with: regex
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91399452
score: 1

http://stackoverflow.com/a/53677571
answers question: http://stackoverflow.com/q/52168852
downvote count: 0
upvote count: 11
has body: hash = 'list:123' key = 'count' n = 1 r.hincrby(hash, key, n)
type: Answer
score: 11

http://stackoverflow.com/a/52212568
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91374672
type: Answer
has body: You need this: ma.loc[ ma.LID.isin( df.LID ) ] Note the difference between your original expression (the added .loc). The expression ma.loc[ list-like-object ] selects rows by a Boolean vector (which must be the same length as ma). The rows that have 'true' will be returned. (on the other hand, in expressions like df[ something ], the 'something' is usually a column or a list of columns, not what you intended). NOTE that while ma.loc[ ma.LID.isin( df.LID ) ] should work, it isn't very efficient for large amounts of data. You might want to re-index your dataframe (or a copy of it) to have the values in LID as the index, then you can select them directly with ma_indexed_by_LOC.loc[ df.LOC ]. (this is assuming that the LOC values are unique).
score: 0
answers question: http://stackoverflow.com/q/52190227
accepted answer of: http://stackoverflow.com/q/52190227

http://stackoverflow.com/q/52136299
has comment: http://stackoverflow.com/comment/91222298
tagged with: django
tagged with: python
tagged with: regex
type: AnsweredQuestion
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52136313
has title: Django 1.11 url pattern error, how to solve?
accepted answer: http://stackoverflow.com/a/52136313
has body: When I try to fix the url in my urlpatterns it shows me this error : The error: Your URL pattern "url(r'^player/[?P[-\w\x20]+]/$', PlayerDetailView.as_view(), name='player-detail-view')," is invalid. Ensure that urlpatterns is a list of url() instance. try removing the string 'url(r'^player/[?P[-\w\x20]+]/$', PlayerDetailView.as_view(), name='player-detail-view'),'. The list of urlpatterns should not have a prefix string as the first element.* My Code : urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', HomePageView.as_view(), name='home-page'), url(r'^teams/$', TeamsListView.as_view(), name='teams-list-view'), url(r'^scores/$', ScoresListView.as_view(), name='scores-list-view'), url(r'^player/[?P&lt;slug&gt;[-\w\x20]+]/$', PlayerDetailView.as_view(), name='player-detail-view'), ] Can anyone help me??
answer count: 1
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/a/52217794
answers question: http://stackoverflow.com/q/52217289
score: 0
type: Answer
has body: Apparently you are using networkx. Looking up the documentation for Graph I can see that it says this: A NodeView of the Graph as G.nodes or G.nodes(). Can be used as G.nodes for data lookup and for set-like operations. [...] Returns NodeView Allows set-like operations over the nodes as well as node attribute dict lookup and calling to get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A NodeView iterates over n and includes set operations. However random.choice needs a sequence not a set/map-like object. You can obtain a sequence by simply calling list: random.choice(list(G.nodes())) The error is due to the fact that the NodeView is not indexed by the position of the nodes in the set, hence when random.choice generates the random index (according to the number of nodes present) to return the random node it fails with that KeyError.

http://stackoverflow.com/q/52236837
tagged with: google-api
type: UnansweredQuestion
tagged with: google-text-to-speech
tagged with: python
tagged with: ssml
answer count: 0
has comment: http://stackoverflow.com/comment/91459612
type: Question
has body: I'm starting to know how to use google APIs modifying the python example code of the texttospeech API I found an issue, when I use ssml languaje in a txt file to pass the text to the API the resultant mp3 audio changed the character 'é' with the sentence 'derechos de autor' and the character 'á' with a silence. That only happens when I read the text from file, if i provide the ssml sentence direct to the applicacion by argunment when calling it this change doesn't happens. I searched for this issue and I didn't find it, colud anyone give a hint of that is going on here? This is the function that takes the ssml texto from the console, and creates the correct mp3 audio file: def synthesize_ssml(ssml, output): from google.cloud import texttospeech as texttospeech client = texttospeech.TextToSpeechClient() input_text = texttospeech.types.SynthesisInput(ssml=ssml) voice = texttospeech.types.VoiceSelectionParams(language_code='es-ES') audio_config = texttospeech.types.AudioConfig( audio_encoding=texttospeech.enums.AudioEncoding.MP3) response = client.synthesize_speech(input_text, voice, audio_config) with open(output, 'wb') as out: out.write(response.audio_content) print('Audio content written to file "%s"' % output) And this is the function that takes the ssml from a file, the same text, produce different audio files: def synthesize_ssml_file(input, output): from google.cloud import texttospeech as texttospeech with open(input,'r') as inp: input_text=texttospeech.types.SynthesisInput(ssml=str(inp.read())) client = texttospeech.TextToSpeechClient() voice = texttospeech.types.VoiceSelectionParams(language_code='es-ES') audio_config = texttospeech.types.AudioConfig( audio_encoding=texttospeech.enums.AudioEncoding.MP3) response = client.synthesize_speech(input_text, voice, audio_config) with open(output, 'wb') as out: out.write(response.audio_content) print('Audio content written to file "%s"' % output)
has comment: http://stackoverflow.com/comment/91422847
score: 0
has title: Strage behaviour with texttospeech google api

http://stackoverflow.com/q/52131345
has comment: http://stackoverflow.com/comment/91214089
tagged with: bash
tagged with: grep
has comment: http://stackoverflow.com/comment/91213587
answer count: 1
has comment: http://stackoverflow.com/comment/91213541
has title: Filtering with `egrep` in a complex Bash expression reporting Python version
linked to: http://stackoverflow.com/q/7522712
has comment: http://stackoverflow.com/comment/91213281
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52131450
accepted answer: http://stackoverflow.com/a/52131450
has body: I'm trying select a part of some output in Bash, but can't figure out where to place the filter and am confused about the output I'm getting. I'm starting from declare -a pythons=("python" "python2" "python3") for p in "${pythons[@]}" do echo "$p: $($p --version 2&gt;&amp;1) in $(which $p)" &amp;&amp; for i in $(which -a $p); do echo " $i ($($i --version 2&gt;&amp;1))"; done &amp;&amp; echo; done which has worked for years to produce the output I expect, namely python: Python 2.7.15 in /usr/local/bin/python /usr/local/bin/python (Python 2.7.15) /usr/bin/python (Python 2.7.10) python2: Python 2.7.15 in /usr/local/bin/python2 /usr/local/bin/python2 (Python 2.7.15) python3: Python 3.7.0 in /usr/local/bin/python3 /usr/local/bin/python3 (Python 3.7.0) but now produces python3: Python 3.7.0 (default, Jun 29 2018, 20:13:13) [Clang 9.1.0 (clang-902.0.39.2)] in /usr/local/bin/python3 /usr/local/bin/python3 (Python 3.7.0 (default, Jun 29 2018, 20:13:13) [Clang 9.1.0 (clang-902.0.39.2)]) for the final grouping. I'd thought that I could simply fix this by adding egrep -o 'Python\s[0-9\\.]+' right after each python --version with for p in "${pythons[@]}" do echo "$p: $($p --version | egrep -o 'Python\s[0-9\\.]+' 2&gt;&amp;1) in $(which $p)" &amp;&amp; for i in $(which -a $p); do echo " $i ($($i --version | egrep -o 'Python\s[0-9\\.]+' 2&gt;&amp;1))"; done &amp;&amp; echo; done but this surprises me by pulling the Python 2 versions out onto a separate line before lines where I expect it Python 2.7.15 python: in /usr/local/bin/python Python 2.7.15 /usr/local/bin/python () Python 2.7.10 /usr/bin/python () Python 2.7.15 python2: in /usr/local/bin/python2 Python 2.7.15 /usr/local/bin/python2 () python3: Python 3.7.0 in /usr/local/bin/python3 /usr/local/bin/python3 (Python 3.7.0) I think I've totally lost my bearings about where output is being sent, and need help sorting out where I'm making my — probably very basic — Bash scripting mistake.
has comment: http://stackoverflow.com/comment/91213418
type: Question
linked to: http://stackoverflow.com/q/592620
score: 0

http://stackoverflow.com/comment/91472672
comment on: http://stackoverflow.com/q/52262430
score: 0
type: Comment
type: QuestionComment
has text: Does form become visible after you click on text input field?

http://stackoverflow.com/q/52239990
has body: I need some help with a fuction. I have multiple lists called 'info' that are displayed as follows in a single textfile: [['a', 'b', 'c'],['d1','e2','f2'],['g','h','i']] [['test', 'test1', 'test2']['test3', 'test4', 'test5']['test6', 'test7', 'test8']] I am trying to write a function that changes all triplets into one string and then loops through all the triples in the list to change them. Output should be: ['a b c','d1 e2 f2','g h i'] ['test test1 test2','test3 test4 test5','test6 test7 test8'] I am trying things such as: def short(x) if len(x) == 3 ' ' .join(x) And then I have to do something to loop trough the list and check the parameters. I've been trying things such as: def check (y) param=info[0] short(param) and trying with for statements But I'm getting nowhere... Provided answer does not help at all. It just shows the same things that I've been trying
has comment: http://stackoverflow.com/comment/91428698
score: 0
upvote count: 1
tagged with: function
has comment: http://stackoverflow.com/comment/91428663
downvote count: 1
has title: Python: Combine triple into a single string
favorite count: 0
duplicate of: http://stackoverflow.com/q/41925504
has comment: http://stackoverflow.com/comment/91429897
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91463682
has comment: http://stackoverflow.com/comment/91435551
answer count: 0
has comment: http://stackoverflow.com/comment/91428712
linked to: http://stackoverflow.com/q/41925504
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/91429862

http://stackoverflow.com/comment/91480903
has text: Nope, I've already perused that article. They never do return_sequences=False.
comment on: http://stackoverflow.com/a/52266425
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91428578
has text: There is nothing to "fix". A given program can only use the local IP addresses. You need to explain more the core problem you have and you try to address.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52234324

http://stackoverflow.com/comment/91222245
comment on: http://stackoverflow.com/q/52136168
score: 0
has text: I'm not that advanced of a programmer. I just learned what a daemon was 3 days ago and have forgotten already. You're going to have to dumb things down a little bit if you want me to understand you.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52269272
linked to: http://stackoverflow.com/q/52264156
downvote count: 0
tagged with: javascript
favorite count: 0
tagged with: python
has title: Run local JavaScript functions from Python 3
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/52271211
linked to: http://stackoverflow.com/q/450285
score: 1
type: Question
has body: So, I'm teaching myself various AI techniques, and I figured the best way to do so would be to create my own Python bot which can play the game Pokemon using an online open-source Pokemon simulator. The issue is that this simulator has all its source code written in JavaScript, whereas my bot uses Python. At first, I solved the problem of grabbing the full list of valid Pokemon and such by simply downloading the server's .js files, which (handily) contained all valid Pokemon/moves as JSON objects that I could easily import into Python. This was all well and good when I just needed Pokemon names and such, but now that I'm building out the actual engine I've discovered that it uses these same JSON files for its actual gameplay code. For example, here's the Pokemon "Ability" Aftermath. Pay attention to onAfterDamage: "aftermath": { desc: "If this Pokemon is knocked out with a contact move, that move's user loses 1/4 of its maximum HP, rounded down. If any active Pokemon has the Damp Ability, this effect is prevented.", shortDesc: "If this Pokemon is KOed with a contact move, that move's user loses 1/4 its max HP.", id: "aftermath", name: "Aftermath", onAfterDamageOrder: 1, onAfterDamage: function (damage, target, source, move) { if (source &amp;&amp; source !== target &amp;&amp; move &amp;&amp; move.flags['contact'] &amp;&amp; !target.hp) { this.damage(source.maxhp / 4, source, target); } }, rating: 2.5, num: 106, } As you can see, onAfterDamage is a JavaScript function, one that I can't easily call from Python (to my knowledge). So now I'm at a crossroads: Stop grabbing the .js files from the server and write my own code entirely in Python, essentially "translating" the JavaScript code myself. Rewrite my entire bot in JavaScript instead of Python, although I'm far less experienced and comfortable in JavaScript. Find a way to run the JavaScript code I'm downloading from the server from within my Python bot, calling arbitrary functions from within the code and returning…
answer count: 1

http://stackoverflow.com/comment/91274926
type: QuestionComment
type: Comment
score: 1
has text: Cannot reproduce the error, works perfectly fine on my end (with `tb_batch.py` containing `import datetime as dt` and the line you quoted). Can you make a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) for us that displays the error?
comment on: http://stackoverflow.com/q/52162671

http://stackoverflow.com/q/52219586
tagged with: keras
favorite count: 0
type: UnansweredQuestion
has body: I am trying to pass to my triplet network 3 images using my data generator. I am loading the different pairs and stacking them into batches. I don't know how can I return it back as 3 different arrays. I tried appending into a list, but that also didn't work. How can I use a data generator to return them back? class DataGenerator(keras.utils.Sequence): 'Generates data for Keras' def __init__(self, list_IDs, batch_size=16, dim=(244,244,3), n_channels=3, shuffle=True): 'Initialization' self.dim = dim self.batch_size = batch_size self.list_IDs = list_IDs self.n_channels = n_channels self.shuffle = shuffle self.on_epoch_end() def __len__(self): 'Denotes the number of batches per epoch' return int(np.floor(len(self.list_IDs) / self.batch_size)) def __getitem__(self, index): 'Generate one batch of data' # Generate indexes of the batch indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size] # Find list of IDs list_IDs_temp = [self.list_IDs[k] for k in indexes] # Generate data X,Z, y = self.__data_generation(list_IDs_temp) return X, Z, y def on_epoch_end(self): 'Updates indexes after each epoch' self.indexes = np.arange(len(self.list_IDs)) if self.shuffle == True: np.random.shuffle(self.indexes) # V = np.stack((X, Z), axis=-1) # F = np.stack((V, y), axis=-1) def __data_generation(self, list_IDs_temp): 'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels) # Initialization X = np.empty((self.batch_size, *self.dim)) Z = np.empty((self.batch_size, *self.dim)) y = np.empty((self.batch_size, *self.dim)) # Generate data for i, ID in enumerate(list_IDs_temp): # Store sample image = plt.imread(os.path.join(IMAGE_DIR, ID[0])).astype(np.float32) image = imresize(image, (IM_SIZE, IM_SIZE)) image1 = plt.imread(os.path.join(IMAGE_DIR, ID[1])).astype(np.float32) image1 = imresize(image1, (IM_SIZE, IM_SIZE)) image2 = plt.imread(os.path.join(IMAGE_DIR, ID[2])).astype(np.float32) image2 = imresize(image2, (IM_SIZE, IM_SIZE)) X[i,] = image Z[i,] = …
tagged with: python
has comment: http://stackoverflow.com/comment/91391914
has title: Returning 3 images from data generator
tagged with: tensorflow
type: Question
score: 5
upvote count: 5
has answer: http://stackoverflow.com/a/52276532
has comment: http://stackoverflow.com/comment/91395567
answer count: 1
downvote count: 0

http://stackoverflow.com/q/52114443
answer count: 3
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52118593
tagged with: python-3.x
tagged with: rest
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52850469
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91179403
has comment: http://stackoverflow.com/comment/91179328
has comment: http://stackoverflow.com/comment/91183581
has title: Django Rest Framework how to forbid users to change their username?
possible better answer: http://stackoverflow.com/a/52118593
has body: I'm creating UserSerializer and want to allow users to create new accounts but forbid them to change their usernames. There is a read_only attribute that I can apply but then users won't be able to set a username when creating a new one. But without that It allows me to change it. There is also a required attribute which unfortunately cannot be used with read_only. There is no other relevant attribute. One solution is to create 2 different Serializers one for creating User and another from changing him, but that seems the ugly and wrong thing to do. Do you have any suggestions on how to accomplish that without writing 2 serializers? Thanks for any advice. PS: I'm using python3.6 and django2.1 EDIT: I'm using generics.{ListCreateAPIView|RetrieveUpdateDestroyAPIView} classes for views. Like this: class UserList(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetails(generics.RetrieveUpdateAPIView): # this magic means (read only request OR accessing user is the same user being edited OR user is admin) permission_classes = (perm_or(ReadOnly, perm_or(IsUserOwner, IsAdmin)),) queryset = User.objects.all() serializer_class = UserSerializer EDIT2: There is a duplicate question (probably mine is duplicate) here
type: Question
has answer: http://stackoverflow.com/a/52114573
accepted answer: http://stackoverflow.com/a/52114573
linked to: http://stackoverflow.com/q/22124555
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/91208122
upvote count: 2

http://stackoverflow.com/q/52129523
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91209422
has body: Assuming that n is a positive integer this is my code: def sum_odd_n(n): x =1 for x in range(n): if x%2==1: continue return x + 2 but when I run it on Python it gives me the answer 2. Could you help me by telling me what's wrong and what I should do to solve this?
tagged with: python
has comment: http://stackoverflow.com/comment/91209413
has comment: http://stackoverflow.com/comment/91209521
has answer: http://stackoverflow.com/a/52129722
has title: How do I write an iterative function that computes the sum of the first n odd numbers it returns 1 + 3 + .... + (2n - 1), using a for loop?
downvote count: 0
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52129670
type: Question
has answer: http://stackoverflow.com/a/52129585
answer count: 3

http://stackoverflow.com/q/52228458
possible better answer: http://stackoverflow.com/a/52229937
has answer: http://stackoverflow.com/a/52229970
has answer: http://stackoverflow.com/a/52229937
answer count: 2
score: 0
accepted answer: http://stackoverflow.com/a/52229970
tagged with: python
has body: I would like to display values from one table, but filter these values based on a value from another table. for example: I want to display values from data/models.py that are filtered by the customer_tag in the CustomUser table (accounts/models.py). These are related tables, but I can't figure out the right syntax to filter this view. Any ideas? Or is this not possible with my current schema.. data/views.py from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView, CreateView from django.urls import reverse_lazy from .models import Data from django.contrib.auth.mixins import LoginRequiredMixin from rest_framework import generics from .models import Data from accounts.models import CustomUser from .serializers import DataSerializer from .permissions import IsAuthorOrReadOnly class DataListView(LoginRequiredMixin,ListView): queryset = Data.objects.all() context = { "object_list": queryset } template_name = 'data_list.html' login_url = 'login' accounts/models.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): customer_Tag = models.CharField(max_length=50,) isAdmin = models.BooleanField(default = False,) notifications = models.BooleanField(default = True,) deviceSerial= models.CharField(max_length=50,) machineName= models.CharField(max_length=50,default="ESP1",) machineDescription = models.CharField(max_length=200,) class Customer(models.Model): customerTag= models.CharField(max_length=50,) customerName = models.CharField(max_length=50,) mainContact = models.CharField(max_length=100,default='',) Address = models.CharField(max_length=100,default='',) city = models.CharField(max_length=100,default='',) website = models.URLField(max_length=100,default='',) phone = models.IntegerField(default=0,) def __str__(self): return self.customerName data/models.py from django.db import models from django.conf import settings from django.contrib.auth import get_use…
tagged with: django
type: Question
type: AnsweredQuestion
has title: query data from one model, filter from another

http://stackoverflow.com/q/52254994
linked to: http://stackoverflow.com/q/21030171
has title: How to apply avg function to DataFrame series monthly?
has comment: http://stackoverflow.com/comment/91457442
linked to: http://stackoverflow.com/q/42388707
type: UnansweredQuestion
tagged with: python
score: 0
type: Question
has body: I have a DataFrame series with day resolution. I want to transform the series to a series of monthly averages. Ofcourse I can apply rolling mean and select only every 30th of means but it would not precise. I want to get series which contains mean value from the previous month on every first day of a month. For example, on February 1 I want to have daily average for the January. How can I do this in pythonic way?
has comment: http://stackoverflow.com/comment/91457355
has answer: http://stackoverflow.com/a/52255420
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91458057
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/91457446

http://stackoverflow.com/comment/91231920
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52140968
has text: I see. A wrapper class it is, then. Thank you!

http://stackoverflow.com/q/52221954
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/91541586
type: Question
linked to: http://stackoverflow.com/q/44616073
tagged with: memory
score: 0
tagged with: workflow
has body: I have prepared a Snakemake pipeline (Snakemake v5.2.2, Python v3.6.5) for analysing RRBS data (full pipeline viewable on GitHub) and put it into Singularity (v2.5.2, made with Ubuntu 18.04 - also viewable on GitHub). I have tested this workflow with 5 shortened FASTQ files and it worked well. Problems started when I increased number of my short, test FASTQ files to 20 (my unit of analysis for this experiment). After running several steps, pipeline failed with Error 127: command not found. This error is not specific to any file or rule - sometimes it crashed during trim galore rule, sometimes bismark. After some investigation I managed to find a solution: adding restriction of memory usage for each rule (e.g. resources: 32000) and running Snakemake with the flag --resources mem_mb=100000. Sadly, when I started the actual analysis using full-sized files, the error returned. I already tried even most desperate things that crossed my mind: removing all mv commands in snakefile and leaving each rule with only single line of shell commands running snakemake with various flags (--wait-for-files, --latency-wait 30 --nolock --force-use-threads --restart-times 2) putting all programs used in the pipeline into Singularity PATH increasing resources restriction up to 50GB of RAM per rule running smaller number of samples in one workflow instance The error appears both while using Singularity container and not, both on my PC and on a server at work. The same commands that fail, work properly when run on their own via command line. I do not use Snakemake's cluster mode. I've tried and checked generally all I could think of, and I already (stupidly) told my supervisor that the analysis is running (It was! T__T). I would be very grateful for help. Any ideas what is going on and how I can resolve this? Here is a full, exemplary snakemake output with error: https://github.com/AdrianS85/varia/blob/master/error_snakemake And here is the meat of the problem: [Thu Sep 6 22:05:40 2018] ru…
has comment: http://stackoverflow.com/comment/91400910
type: UnansweredQuestion
tagged with: python
has title: snakemake - workflow fails after performing several jobs
answer count: 0
tagged with: snakemake

http://stackoverflow.com/a/53723980
score: 0
answers question: http://stackoverflow.com/q/52202137
has body: Its not a problem on code end. Your Facebook pixel is not activated. Just Goto Facebook and try to activate it. Once activated init the facebook pixel before tracking code. fbq("init", FACEBOOK_PIXEL);
type: Answer

http://stackoverflow.com/comment/129965573
type: QuestionComment
comment on: http://stackoverflow.com/q/52224813
has text: `warnings.filterwarnings(action='ignore')` is one terrible thing to do, it may suppress ALL warnings. You should either specify message, module, or category explicitly to suppress ONLY a *specific type* of warnings that you'd REALLY like to do so.
score: 0
type: Comment

http://stackoverflow.com/a/68619008
has body: You need to change the shape of the input to make it compatible with the decoder output. use Reshape((28, 28, 4)) to make it match.
type: Answer
answers question: http://stackoverflow.com/q/52152341
score: 0

http://stackoverflow.com/q/52159019
tagged with: python
has body: everyone I'm currently running a research using Multilayer perceptron. I previously run this using WEKA but I have migrated to scikit-learn in python for various reason. I tried to reproduce my prediction results in WEKA to scikit-learn so I made an exact perceptron with the exact same learning rate, momentum, hidden layer, etc However, the prediction results turns out differently for these both platforms. Can anybody gives me some explanation regarding this matter? The only thing that I notice is that scikit learn uses either lbfgs, adam, and sgd to optimize its connection weight while WEKA uses backpropagation. But could it be the only reason? or is there another reason? Best regards
downvote count: 0
score: 1
type: Question
tagged with: weka
tagged with: scikit-learn
has title: WEKA and Scikit-Learn Multilayer Perceptron Gives Different Result
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/52159197
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91309401
type: QuestionComment
comment on: http://stackoverflow.com/q/52179629
score: 0
has text: instead of posting to calculator/, just POST to home/ , and remove the calculator/ from the urls list. and move the calculator view code to home view
type: Comment

http://stackoverflow.com/comment/91375696
score: 0
type: Comment
type: QuestionComment
has text: @UnbearableLightness it was regarding groups. Now I want to know about specific group.
comment on: http://stackoverflow.com/q/52213070

http://stackoverflow.com/comment/91299182
score: 0
comment on: http://stackoverflow.com/q/52174095
type: Comment
type: QuestionComment
has text: Hi dheeraj. I [edit]ed your question so that the code stands out properly. (I did that by putting 4 spaces in front of each line of code.) I recommend you look closely at where you create `results_list`, as it's likely where not where you wanted to create it.

http://stackoverflow.com/q/52159364
has comment: http://stackoverflow.com/comment/91284001
has answer: http://stackoverflow.com/a/52159796
has answer: http://stackoverflow.com/a/52160380
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91268756
has comment: http://stackoverflow.com/comment/91269075
upvote count: 2
has comment: http://stackoverflow.com/comment/91283947
tagged with: python
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/52159796
type: Question
has title: Updating row in pandas dataframe using loc not working properly
has comment: http://stackoverflow.com/comment/91269014
tagged with: dataframe
has body: I have a dataframe named output - RAW_ENTITY_NAME ENTITY_TYPE ENTITY_NAME IS_MAIN 01-03-2017 TNRMATDT 01 03 2017 1 04-02-2017 TNRSTRTDT 04 02 2017 1 documents TNRTYPE SIGHT 1 documents TNRDOCSBY NOT FOUND 1 accept TNRDTL accept 1 23 TNRDAYS 23 1 print(df.dtypes()) RAW_ENTITY_NAME object ENTITY_TYPE object ENTITY_NAME object IS_MAIN object Note - ENTITY_TYPE = TNRTYPE, ENTITY_NAME = SIGHT AND IS_MAIN = 1 will only come once in the dataframe. I want to update some values if ENTITY_TYPE is TNRTYPE, ENTITY_NAME = SIGHT AND IS_MAIN = 1. temp = output.loc[(output['IS_MAIN'] == 1) &amp; (output['ENTITY_TYPE'] == 'TNRTYPE'), 'ENTITY_NAME'] temp = temp.reset_index(drop=True) temp = temp[0] if (temp == 'SIGHT'): output.loc[(output['IS_MAIN'] == '1') &amp; (output['ENTITY_TYPE'] == 'TNRDOCSBY'), 'ENTITY_NAME'] = 'PAYMENT' output.loc[(output['IS_MAIN'] == '1') &amp; (output['ENTITY_TYPE'].isin(['TNRDTL'])), ['ENTITY_NAME', 'RAW_ENTITY_NAME']] = 'NOT APPLICABLE' output.loc[(output['IS_MAIN'] == '1') &amp; (output['ENTITY_TYPE'].isin(['TNRDAYS'])), ['ENTITY_NAME']] = '0' output.loc[(output['IS_MAIN'] == '1') &amp; (output['ENTITY_TYPE'].isin(['TNRDAYS'])), ['RAW_ENTITY_NAME']] = '' output.loc[(output['IS_MAIN'] == '1') &amp; (output['ENTITY_TYPE']=='TNRSTRTDT'), ['ENTITY_NAME', 'RAW_ENTITY_NAME']] = '' output.loc[(output['IS_MAIN'] == '1') &amp; (output['ENTITY_TYPE']=='TNRMATDT'), ['ENTITY_NAME', 'RAW_ENTITY_NAME']] = '' The final output is - RAW_ENTITY_NAME ENTITY_TYPE ENTITY_NAME IS_MAIN 01-03-2017 TNRMATDT 01 03 2017 1 04-02-2017 TNRSTRTDT 04 02 2017 1 documents TNRTYPE SIGHT 1 documents TNRDOCSBY PAYMENT 1 NOT APPLICABLE TNRDTL NOT APPLICABLE 1 TNRDAYS 0 1 As you can see everything is getting updated except the first two rows , i.e. ENTITY_TYPE = TNRMATDT AND TNRSTRTDAT. I want to know why the below code is not giving the desired results. output.loc[(output['IS_MAIN'] == '1') &amp; (output['ENTITY_TYPE']=='TNRSTRTDT'), ['ENTITY_NAME', 'RAW_ENTITY_NAME']] = '' output.loc[(out…
has comment: http://stackoverflow.com/comment/91269051
has comment: http://stackoverflow.com/comment/91268970
has comment: http://stackoverflow.com/comment/91268498
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/91268999
downvote count: 0
has comment: http://stackoverflow.com/comment/91270505
possible better answer: http://stackoverflow.com/a/52160380

http://stackoverflow.com/q/52127529
tagged with: arrays
tagged with: string
score: 0
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52127928
has title: Python help needed. Whats the best way to gather data from a spreadsheet into an array that can hold strings and numbers
tagged with: python
tagged with: excel
type: AnsweredQuestion
has body: Would like to import data from spreadsheet, currently using pyxl. Whats the best way to read the excel data and insert it into an 2D array. Is it Numpy? Pandas? Lists? I am new and I am struggling how to insert into a variable like so: MaterialData[y, x] = data from spreadsheet where y is the row and x the column. I am using a for loop to go through the cells but I am cant find the way to put the data into an array. for i in range(1, rows+1): for j in range(1, 6): col = sh.cell(i, j) col1 = col.value materialsList[i,j] = col1 The last line obviously is in error, but that's what i want to do, if it makes sense! The excel file is a list of materials where each column has a different prices, and depending on what the user selects in the program, that price is shown. (well that's a very simplified version of what i want to achieve). Part of the data in this array will be displayed on a listbox using tkinter, depending on flags set by the user. Any advice welcome!!
accepted answer: http://stackoverflow.com/a/52127685
has answer: http://stackoverflow.com/a/52127928
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52127685

http://stackoverflow.com/q/52214602
has title: How do I check when my next Airflow DAG run has been scheduled for a specific dag?
has body: I have airflow set up and running with some DAGs scheduled for once a day "0 0 * * *". I want to check when is the next time a specific dag has been scheduled to run, but I can't see where I can do that within the admin.
accepted answer: http://stackoverflow.com/a/56781909
type: Question
tagged with: airflow
score: 16
has answer: http://stackoverflow.com/a/52219032
downvote count: 0
tagged with: scheduled-tasks
favorite count: 0
has answer: http://stackoverflow.com/a/56781909
tagged with: python
possible better answer: http://stackoverflow.com/a/65544119
upvote count: 16
answer count: 4
linked to: http://stackoverflow.com/q/63527204
has answer: http://stackoverflow.com/a/71401851
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/65544119

http://stackoverflow.com/a/52175970
score: 0
answers question: http://stackoverflow.com/q/52174891
type: Answer
has body: There might be a better solution, but it's possible with numba.stencil: import numba # Define some input array x = np.arange(25).reshape(5,5) # Pad the array to one cell width with 0 y = np.pad(x, 1, mode='constant', constant_values=0) # Instantiate the output array ii = np.zeros_like(y) @numba.stencil def integral_image(A, B): # A is the input array, B is the output return A[0,0] + B[-1,0] + B[0,-1] - B[-1,-1] # Slice the output to get rid of padded cells ii = integral_image(y, ii, out=ii)[1:-1,1:-1] This generates a stencil function which uses values from the input image along with previously-calculated values from the output. The output needs to be instantiated as an array of zeros before performing the calculation and must be passed to the stencil function as an output array so that the function has access to the previously-calculated values. My primary issue with this is that it requires copying the input array to pad it for use with numba.stencil. It seems that the numba developers are thinking about adding adding different modes for boundary handling at some point, but currently it is necessary to pad the input in order for the stencil to be applied over every cell. I am also not sure how much faster this is compared to x.cumsum(0).cumsum(1). When I get around to performance-testing this against successive calls to np.cumsum I'll try to remember to post the specs.

http://stackoverflow.com/comment/91449709
type: Comment
has text: @tatlar I had not previously tried that, so I tried it now. Unfortunately, it did not affect the issue at all.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52250218

http://stackoverflow.com/q/52213265
tagged with: list
accepted answer: http://stackoverflow.com/a/52213316
tagged with: set
has answer: http://stackoverflow.com/a/52213327
has answer: http://stackoverflow.com/a/52213520
has comment: http://stackoverflow.com/comment/91376069
type: Question
has answer: http://stackoverflow.com/a/52213316
has title: Remove duplicates in a list of tuples based on max value
has body: Suppose I have a list of tuples like this: [('Machine1', 88), ('Machine2', 90), ('Machine3', 78), ('Machine1', 90), ('Machine3', 95)] And I want to filter the list such that I only have the highest values pertaining to each tuple pairing. So in this example the filtered list would be: [('Machine2', 90),('Machine1', 90), ('Machine3', 95)] I basically want to remove duplicates by the highest value. I know set only removes exact duplicates so I won't be able to do that here. I thought another method I could use would be to use a dictionary and update it while iterating through the list if a higher value was seen. However, what is a more pythonic way to approach this?
answer count: 3
upvote count: 1
downvote count: 1
possible better answer: http://stackoverflow.com/a/52213327
favorite count: 0
tagged with: tuples
score: 0
tagged with: python
tagged with: dictionary
type: AnsweredQuestion

http://stackoverflow.com/a/52224626
has comment: http://stackoverflow.com/comment/91399337
has comment: http://stackoverflow.com/comment/91399413
score: 3
answers question: http://stackoverflow.com/q/52224426
downvote count: 0
has body: The problem you're facing is due to your first print(f.read()) line. Calling f.read() extracts all the data from the file, so the file read position will be at the end. The following read won't return anything, because you already reached the end of file. Removing the line should fix your issue. Another solution would be to add f.seek(0) before var1=f.read(), which resets the file read position to the beginning of the file.
type: Answer
upvote count: 3

http://stackoverflow.com/a/52194021
upvote count: 5
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52193937
score: 5
answers question: http://stackoverflow.com/q/52193937
has body: Add build-essential to the apt-get install package list. It seems that your base image is very basic, and does not have gcc installed, so you cannot compile anything.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91338523
has comment: http://stackoverflow.com/comment/91339164

http://stackoverflow.com/comment/91487474
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52269404
type: Comment
has text: What they said. Links that support an answer are great, but the answer needs to have useful on-site content too. Of course, the official docs link is fairly resistant to link rot, and pymotw should be ok too, but please see https://meta.stackexchange.com/questions/225370/your-answer-is-in-another-castle-when-is-an-answer-not-an-answer

http://stackoverflow.com/comment/91230027
comment on: http://stackoverflow.com/a/52140207
type: AnswerComment
score: 0
type: Comment
has text: your desired output starts with a \n which you could hard code in, it was unclear if you forgot it in your example variable or if you wanted it built in -- easy enough to check if \n is in the beginning and end of the string and add it if it isnt

http://stackoverflow.com/comment/91277056
comment on: http://stackoverflow.com/q/52163830
type: QuestionComment
has text: CEST is fixed here…?
score: 0
type: Comment

http://stackoverflow.com/a/52118554
answers question: http://stackoverflow.com/q/52118382
type: Answer
has comment: http://stackoverflow.com/comment/91195666
has comment: http://stackoverflow.com/comment/91203808
has comment: http://stackoverflow.com/comment/91202152
upvote count: 1
score: 1
has body: Assuming the special characters occur at the end of the string you may use: mydata = ['https://twitter.com/GVNyqWEu5u', "https://twitter.com/GVNyqWEu5u'", 'https://twitter.com/GVNyqWEu5u@#', 'https://twitter.com/GVNyqWEu5u"'] mydata = [re.sub('[^a-zA-Z0-9]+$','',item) for item in mydata] print(mydata) Prints: ['https://twitter.com/GVNyqWEu5u', 'https://twitter.com/GVNyqWEu5u', 'https://twitter.com/GVNyqWEu5u', 'https://twitter.com/GVNyqWEu5u']
has comment: http://stackoverflow.com/comment/91202196
has comment: http://stackoverflow.com/comment/91202206
downvote count: 0
has comment: http://stackoverflow.com/comment/91191517
has comment: http://stackoverflow.com/comment/91189893
has comment: http://stackoverflow.com/comment/91189877

http://stackoverflow.com/q/52262658
tagged with: pyside
has title: Check/Uncheck selected treeview items
has comment: http://stackoverflow.com/comment/91482131
type: Question
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/91484336
has comment: http://stackoverflow.com/comment/91475407
tagged with: qtreeview
has body: How can i make it so when a user clicks on the checkbox within the selected items, it changes all the selected items in the treeview to match the state of the clicked checkbox? The item that is clicked. As an example, when i click Jason, it should toggle all the other items selected to also be checked. However what currently happens instead, is Jason becomes the only item selected and checked. Before clicking Jason: Result currently after clicking Jason: What i would like to happen: import sys import os from PySide import QtGui, QtCore class Example(QtGui.QDialog): def __init__(self, parent=None): super(Example, self).__init__(parent) self.resize(300, 300) self.setWindowTitle('Example') self.ui_items = QtGui.QTreeView() self.ui_items.sortByColumn(1, QtCore.Qt.AscendingOrder) self.ui_items.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.ui_items.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) self.ui_items.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) self.ui_items.setModel(QtGui.QStandardItemModel()) grid = QtGui.QGridLayout() grid.setContentsMargins(0, 0, 0, 0) grid.addWidget(self.ui_items, 0, 0) self.setLayout(grid) self.setLayout(grid) self.create_model() def create_model(self): model = self.ui_items.model() model.clear() model.setHorizontalHeaderLabels(['Items']) self.ui_items.sortByColumn(0, QtCore.Qt.AscendingOrder) data = { 'Family 01': ['Amy', 'Kevin'], 'Family 02': ['Sarah', 'Jason', 'Abby'], 'Family 03': ['Michelle', 'Mike', 'Scott', 'Allie'] } for k, v in data.items(): root = [] # family root_node = QtGui.QStandardItem() root_node.setData(k, role=QtCore.Qt.DisplayRole) root.append(root_node) # children for child in v: row = [] row_node = QtGui.QStandardItem() row_node.setData(child, role=QtCore.Qt.DisplayRole) row_node.setCheckable(True) row.append(row_node) root_node.appendRow(row) model.appendRow(root) self.ui_items.expandAll() self.ui_items.resizeColumnToContents(0) def main(): app = QtGui.QApplication(sys.argv) ex =…
has comment: http://stackoverflow.com/comment/91473284
accepted answer: http://stackoverflow.com/a/52332376
tagged with: python
has answer: http://stackoverflow.com/a/52332376
type: AnsweredQuestion

http://stackoverflow.com/a/52155592
score: 0
has body: Here's taking what Jacques de Hooge said in his answer and I in the comments, but making it more specific to your code. Note how f can be any function from R^2 to R^2, and can be passed to your streamplot function. import numpy as np import matplotlib.pyplot as plt def f(x, y): return x + y, x*y def streamplot(f, x_min=0, x_max=1, y_min=0, y_max=1, x_num_divisions=100, y_num_divisions=100): """Displays the stream plot of a two-dimensional system of equations.""" x, y = np.meshgrid( np.linspace(x_min, x_max, x_num_divisions), np.linspace(y_min, y_max, y_num_divisions) ) xdot, ydot = f(x, y) plt.streamplot(x, y, xdot, ydot) plt.show() streamplot(f)
type: Answer
answers question: http://stackoverflow.com/q/52155194

http://stackoverflow.com/a/52185123
has comment: http://stackoverflow.com/comment/91320190
score: -1
answers question: http://stackoverflow.com/q/52184713
downvote count: 1
type: Answer
upvote count: 0
has body: Use line vat = invoice.partner_id.vat or '' #convert string to list vat = [x for x in val] vat = list(filter(lambda x: x.isnumeric(), vat[:2])) + vat[2:] to convert string to list first.

http://stackoverflow.com/q/52268130
has comment: http://stackoverflow.com/comment/91483876
type: Question
has body: I haves been looking for an answer to this but can't seem to find anything that does this elegantly or pythonic. Basically if I have a list: A = [["1a", "ab"], ["2b", "cd"], ["1a", "ef"]] I want to identify every item which has the same value in their first index and if that's the case amend the list so that A becomes: A = [["1a", ["ab", "ef"]], ["2b", "cd"]] As ordering is important I am trying to avoid dictionaries.
has comment: http://stackoverflow.com/comment/91484106
score: 0
upvote count: 1
downvote count: 1
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52268199
linked to: http://stackoverflow.com/q/1867861
has comment: http://stackoverflow.com/comment/91483874
has title: Removing duplicates in a list and using the duplicate to create a sublist in the first occuring list index
tagged with: python
has comment: http://stackoverflow.com/comment/91484230
has answer: http://stackoverflow.com/a/52268199
has comment: http://stackoverflow.com/comment/91484109
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91484113

http://stackoverflow.com/a/52243839
downvote count: 0
upvote count: 2
has body: You can GroupBy with count, then sort and drop duplicates: res = df.groupby(['size', 'vegetable'], as_index=False)['market'].count()\ .sort_values('market', ascending=False)\ .drop_duplicates('vegetable') print(res) size vegetable market 4 Small Onion 3 2 Large Tomato 2 3 Small Cabbage 2
answers question: http://stackoverflow.com/q/52243060
type: Answer
score: 2

http://stackoverflow.com/comment/91302991
comment on: http://stackoverflow.com/q/52176199
score: 0
type: QuestionComment
type: Comment
has text: sqrt is not the best name to use for variable, since it is also a function in math, numpy, and scipy.

http://stackoverflow.com/comment/91200172
comment on: http://stackoverflow.com/a/52124293
type: AnswerComment
has text: This worked! Thank you for the help. This was my first post on Stack, you guys rock.
score: 0
type: Comment

http://stackoverflow.com/comment/91692667
type: QuestionComment
has text: Thanks both, think I now understand far more about Linux memory allocation than I should ever need to! Having read around the subject, I think the real answer is actually that there isn't a "proper" solution to this, and so I'll have to work around it. One of the supposed advantages of Python is the cross-platform nature, easy portability, etc, and so whilst I can make some of the changes on my own systems to make it fail "in the right way", I can't expect that when I deploy elsewhere. So I'll have to make up some other metric as a proxy for a maximum amount of memory to use...
comment on: http://stackoverflow.com/q/52248531
score: 0
type: Comment

http://stackoverflow.com/a/52151978
score: 1
accepted answer of: http://stackoverflow.com/q/52151867
downvote count: 0
answers question: http://stackoverflow.com/q/52151867
has body: Use pd.Series.isin to index by a single Boolean series: df.loc[df['A'].isin(items), 'A'] = 'other' The bottleneck in your logic is df['A'] == item in a loop. The above method ensures only a single Boolean series is calculated for indexing.
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/91257221
comment on: http://stackoverflow.com/q/52152512
type: Comment
type: QuestionComment
has text: print(volume_dict["post"][count]) <-- aren't you getting error for this also ?
score: 0

http://stackoverflow.com/q/52129773
has answer: http://stackoverflow.com/a/52133699
has comment: http://stackoverflow.com/comment/91284263
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91277450
tagged with: cluster-analysis
has comment: http://stackoverflow.com/comment/91282472
has comment: http://stackoverflow.com/comment/91285085
has comment: http://stackoverflow.com/comment/91270685
answer count: 1
downvote count: 0
tagged with: scikit-learn
linked to: http://stackoverflow.com/q/52115697
favorite count: 0
tagged with: out-of-memory
type: UnansweredQuestion
has title: scikitlearn - memory error during MiniBatchKMeans clustering after HashingVectorizer
has body: my goal is to perform clustering of texts from a dataset of millions of rows, where each row is a string of words, which doesn't correspond to a proper document, but rather to a list of "keywords". The idea is that each row represents a Twitter user with the list of keywords taken from his/her tweets, here is an example of a row: "remove United States District Attorney Carmen Ortiz office overreach case Aaron Swartz" Here is my code: from __future__ import print_function from sklearn.feature_extraction.text import HashingVectorizer from sklearn.cluster import MiniBatchKMeans from time import time import csv # LOAD CSV print("Loading Dataset from a CSV...") csvinputfile = '...' t = time() dataset = open(csvinputfile, 'r') print("done in %0.3fs" % (time() - t)) print("") # TERM OCCURRENCES print("Calculating Term Occurrences...") t = time() vectorizer = HashingVectorizer(n_features=300000, stop_words=None, alternate_sign=False, norm='l2', binary=False) x = vectorizer.fit_transform(dataset) print("done in %0.3fs" % (time() - t)) print("") # CLUSTERING print("MiniBatchKMeans Clustering...") t = time() km = MiniBatchKMeans(n_clusters=10000, init='k-means++', n_init=1, init_size=10000, batch_size=10000, verbose=False) clusters = km.fit(x) print("done in %0.3fs" % (time() - t)) print("") My problem is that when it comes to do clustering I get a Memory Error: MiniBatchKMeans Clustering... Traceback (most recent call last): File ".../cluster-users.py", line 32, in &lt;module&gt; clusters = km.fit(x) File ".../python2.7/site-packages/sklearn/cluster/k_means_.py", line 1418, in fit init_size=init_size) File ".../python2.7/site-packages/sklearn/cluster/k_means_.py", line 684, in _init_centroids x_squared_norms=x_squared_norms) File ".../python2.7/site-packages/sklearn/cluster/k_means_.py", line 79, in _k_init centers = np.empty((n_clusters, n_features), dtype=X.dtype) MemoryError [Finished in 22.923s] I am quite new to python and scikitlearn so I don't understand really well wh…
tagged with: python
tagged with: large-data

http://stackoverflow.com/comment/91447266
score: 0
has text: sorry, actually I am new to python... I can only get (5, 4, False), not [(5, 4, False), (6, 4, False)], though it also have the maximum key.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52249484

http://stackoverflow.com/comment/91176787
type: QuestionComment
comment on: http://stackoverflow.com/q/52112788
has text: If you're set on the double loop, you should start the second loop at the value of the index in the first loop I think. Consider this post https://stackoverflow.com/questions/29324025/python-nested-loop-unique-pairs
score: 0
type: Comment

http://stackoverflow.com/comment/91444769
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52238488
has text: Well, that's my point... I am not sure what to do. When I looked at the link provided, I am not too sure how to add / extend the same.

http://stackoverflow.com/q/52131063
has comment: http://stackoverflow.com/comment/91213274
tagged with: django
has comment: http://stackoverflow.com/comment/91212929
has comment: http://stackoverflow.com/comment/91213241
type: Question
has comment: http://stackoverflow.com/comment/91218950
has comment: http://stackoverflow.com/comment/91213313
accepted answer: http://stackoverflow.com/a/52135227
has comment: http://stackoverflow.com/comment/91213316
possible better answer: http://stackoverflow.com/a/52135446
has comment: http://stackoverflow.com/comment/91212892
score: 0
has answer: http://stackoverflow.com/a/52135446
answer count: 2
has comment: http://stackoverflow.com/comment/91213329
has body: The code for using the pk is the following: views.py class CreatorUpdate(LoginRequiredMixin, UpdateView): model = Creator fields = ['first_name', 'last_name', 'location', 'country'] success_url = reverse_lazy('index') # these two methods only give access to the users own profile but not the others (prevents url hacking) def user_passes_test(self, request): if request.user.is_authenticated: self.object = self.get_object() return self.object.user == request.user return False def dispatch(self, request, *args, **kwargs): if not self.user_passes_test(request): return redirect_to_login(request.get_full_path()) return super(CreatorUpdate, self).dispatch(request, *args, **kwargs) urls.py path('creator/&lt;int:pk&gt;/update/', views.CreatorUpdate.as_view(), name='creator-update') HTML snippet to call the URL: &lt;a href="{% url 'creator-update' user.pk %}"&gt;{{ user.get_username }}&lt;/a&gt; Now I would like to use a slug (username) instead of the pk to access the UpdateView. I can successfully pass the username to the URL: &lt;a href="{% url 'creator-update' user.get_username %}"&gt;{{ user.get_username }}&lt;/a&gt; but seem not to be able to match it in urls.py path('creator/&lt;slug:slug&gt;/update/', views.CreatorUpdate.as_view(), name='creator-update') with the same logic. I also tried to set a SlugField in my Creator model like this: from django.template.defaultfilters import slugify class Creator(models.Model): ... username = models.CharField(max_length=100) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = slugify(self.username) super(Creator, self).save(*args, **kwargs) ... And setting slug_field = 'slug' in the UpdateView also does not get it. These modification result in a 404 error: raised by catalog.views.CreatorUpdate: No creator found matching the query When adjusting the HTML part to &lt;a href="{% url 'creator-update' user.creator.slug %}"&gt;{{ user.get_username }}&lt;/a&gt; I get a NoReverseMatcherror Reverse for 'creator-update' wit…
has title: Django: access generic UpdateView with slug instead of pk
has comment: http://stackoverflow.com/comment/91213539
tagged with: python
has comment: http://stackoverflow.com/comment/91213652
has comment: http://stackoverflow.com/comment/91219682
has answer: http://stackoverflow.com/a/52135227
type: AnsweredQuestion

http://stackoverflow.com/comment/91203563
has text: @Ayushimidha I am getting the desired output with loc. What is your pandas version.?
type: Comment
comment on: http://stackoverflow.com/a/52126175
score: 0
type: AnswerComment

http://stackoverflow.com/q/52158102
has comment: http://stackoverflow.com/comment/91266531
has comment: http://stackoverflow.com/comment/91266516
tagged with: python
has title: Is this a safe way to encode and decode a string in python?
has answer: http://stackoverflow.com/a/52158173
type: UnansweredQuestion
tagged with: encryption
upvote count: 1
type: Question
score: 1
has answer: http://stackoverflow.com/a/79020854
has comment: http://stackoverflow.com/comment/91266451
has comment: http://stackoverflow.com/comment/139330988
has comment: http://stackoverflow.com/comment/91266504
has body: I created a VERY simple password manager--not GUI. Basically my Python program generates a string of characters and I encode that password and then store the encoded form into an encrypted txt file. Now the catch is that I can take that encoded form and put it into my python program and it returns the original password. How safe is this? Also for whatever reason after encoding the password this is added to the password: “b’&lt;--Password here-->’.” Now I am asking how difficult it would be for a malicious hacker to take the encoded form of the original password and get the original. Here is my encoding code: byte_pass = str.encode(password) encoded = base64.b64encode(byte_pass) Now all I have to do to return the original password is make the following: base64.b64decode(old_pass) And if this is not safe how can I encrypt a string using a specific keyword--almost like a master password. Thank you! Note** Below are some examples of the before encoding and after: # Generated Password 2]+C!)5R@hwp\zebDjOlx&amp;xL}cRq”`n # Encoded form of password above b'Ml0rQyEpNVJAaHdwXHplYkRqT2x4JnhMfWNSceKAnWBu'
answer count: 2
has comment: http://stackoverflow.com/comment/91266522
downvote count: 0
has comment: http://stackoverflow.com/comment/91266489
has comment: http://stackoverflow.com/comment/91266519
favorite count: 0
has comment: http://stackoverflow.com/comment/91266536
has comment: http://stackoverflow.com/comment/91266494

http://stackoverflow.com/a/52243429
type: Answer
score: 0
has body: You capture only the labels in a group trying capturing also the values like so: print(re.findall('(latitude|longitude)=(-?\d+.\d+)', req)) This will return list of tuples: [('latitude', '32.7766642'), ('longitude', '-96.79698789999998')] Full example: import re req ="&lt;Request 'http://127.0.0.1:5000/findrisk? latitude=32.7766642&amp;longitude=-96.79698789999998' [GET]&gt;" print(re.findall('(latitude|longitude)=(-?\d+.\d+)', req))
answers question: http://stackoverflow.com/q/52243385

http://stackoverflow.com/comment/91411813
comment on: http://stackoverflow.com/a/52230708
has text: you're using `python3`? cast the `f.write()` parameters to `bytes()` and encode. see updated answer
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52188071
type: AnsweredQuestion
score: 1
tagged with: multithreading
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52194545
tagged with: thread-safety
answer count: 1
tagged with: user-interface
downvote count: 0
tagged with: wxpython
favorite count: 0
has title: wxpython CallAfter not changing GUI
accepted answer: http://stackoverflow.com/a/52194545
has body: I needed a start and stop button for reading data continuously with a while loop, so I used the first example in here https://wiki.wxpython.org/LongRunningTasks. Then I wanted to change a graphic in continuous as well but I couldn't do it so to simulate that I tried to just change a TextCtrl. So I used wx.CallAfter to write on the TextCtrl, and I see that 'internaly' it changes but it doesn´t update the frame. I also tried using the Update() and Refresh() but that didn't work either. So I have no idea what to do and I've search all the places I could and don't know what to do anymore, so any help is appreciated! import nidaqmx import wx import wxmplot import time from threading import Thread from numpy import mean, std from nidaqmx.constants import AcquisitionType, DataTransferActiveTransferMode, TerminalConfiguration ID_START = wx.NewId() ID_STOP = wx.NewId() EVT_RESULT_ID = wx.NewId() def EVT_RESULT(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_RESULT_ID, func) class ResultEvent(wx.PyEvent): """Simple event to carry arbitrary result data.""" def __init__(self, data): """Init Result Event.""" wx.PyEvent.__init__(self) self.SetEventType(EVT_RESULT_ID) self.data = data myEVT = wx.NewEventType() EVT = wx.PyEventBinder(myEVT, 1) class MyEvent(wx.PyCommandEvent): def __init__(self, evtType, id): wx.PyCommandEvent.__init__(self, evtType, id) myVal = None def SetMyVal(self, val): self.myVal = val def GetMyVal(self): return self.myVal # janela para ler canais class NewTaskWindow(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(1000,500)) self.parent = parent self.title = title self.task_panel = wx.Panel(self, wx.ID_ANY, size = (1000,500)) self.canais = ['Canal', 'Dev1/ai0','Dev1/ai1','Dev1/ai2','Dev1/ai3','Dev1/ai4','Dev1/ai5', 'Dev1/ai6','Dev1/ai7','Dev1/ai8','Dev1/ai9','Dev1/ai10','Dev1/ai11', 'Dev1/ai12','Dev1/ai13','Dev1/ai14','Dev1/ai15'] self.cfgs = [TerminalConfiguration.DEFAULT, TerminalConfiguration.…
tagged with: python

http://stackoverflow.com/a/52253538
downvote count: 0
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/52253357
has body: You should concatenate new characters to a string instead of appending them to a list. Only append a new string to the output list at the start of a tag: with open('doc.txt', 'r') as f: empty_tag_list = [] for line in f: isTag = False for chars in line: if chars == "&lt;": isTag = True empty_tag_list.append('') elif chars == "&gt;": isTag = False elif isTag: empty_tag_list[-1] += chars print(empty_tag_list)
answers question: http://stackoverflow.com/q/52253357
type: AcceptedAnswer

http://stackoverflow.com/comment/91180897
score: 0
has text: yes this is csv file
type: QuestionComment
comment on: http://stackoverflow.com/q/52115204
type: Comment

http://stackoverflow.com/comment/91220540
score: 0
type: Comment
has text: Thank you, I tried it but get this error: *** django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON (other) "chat__chat"."id",...
comment on: http://stackoverflow.com/a/52135046
type: AnswerComment

http://stackoverflow.com/q/52155191
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91267909
score: 1
type: Question
has title: Tshark running on CentOS inside Docker: Operation not permitted: '/usr/sbin/dumpcap'
downvote count: 0
has comment: http://stackoverflow.com/comment/91271061
tagged with: centos
tagged with: docker
tagged with: tshark
has body: I'm trying to run a Docker image with Tshark on CentOS. Unfortunately I keep getting this PermissionError: [Errno 1] Operation not permitted: '/usr/sbin/dumpcap' error. My docker-compose.yml: version: '2' services: tshark: build: dockerfile: Dockerfile context: . container_name: tshark Dockerfile: FROM centos RUN yum -y update &amp;&amp; \ yum -y install epel-release &amp;&amp; \ yum -y install python36 \ yum -y install libcap2-bin wireshark &amp;&amp; yum clean all &amp;&amp; \ curl -O https://bootstrap.pypa.io/get-pip.py &amp;&amp; \ /usr/bin/python36 get-pip.py &amp;&amp; \ rm get-pip.py &amp;&amp; \ pip install pyshark &amp;&amp; \ pip install tqdm requests &amp;&amp; \ ln -s /usr/bin/python36 /usr/bin/python3 # add extra user RUN useradd -ms /bin/bash shark RUN usermod -aG wireshark shark RUN newgrp wireshark RUN chgrp wireshark /usr/sbin/dumpcap RUN chmod 750 /usr/sbin/dumpcap RUN setcap 'CAP_NET_RAW+eip CAP_NET_ADMIN+eip' /usr/sbin/dumpcap # wireshark fixes # RUN newgrp wireshark ADD . /app WORKDIR /app # switch user USER shark CMD ["python3", "process.py"] My process.py: #!/usr/bin/env python3 import pyshark capture = pyshark.LiveRingCapture(interface='eth0') for packet in capture.sniff_continuously(packet_count=5): print('Just arrived:', packet) I tried different solutions. It seems it has something to do with the fact it won't run while using a root user, or a user which hasn't got the right permissions. Hopefully someone can help me out. This is the result I keep getting after running docker-compose up --build: tshark | Traceback (most recent call last): tshark | File "process.py", line 6, in &lt;module&gt; tshark | for packet in capture.sniff_continuously(packet_count=5): tshark | File "/usr/local/lib/python3.6/site-packages/pyshark/capture/capture.py", line 207, in _packets_from_tshark_sync tshark | tshark_process = existing_process or self.eventloop.run_until_complete(self._get_tshark_process()) tshark | File "/usr/lib64/python3.6/asyncio/base_events.p…
tagged with: wireshark

http://stackoverflow.com/comment/91311979
score: 0
has text: how about this? new_array=[your_list]
comment on: http://stackoverflow.com/q/52180975
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52136220
score: 0
type: Answer
has body: Use Xenus Link Sleuth, WebCheck and DRKSpider. Here are the links below Link Sleuth : http://home.snafu.de/tilman/xenulink.html WebCheck : https://arthurdejong.org/webcheck/ DRKSpider : http://www.drk.com.ar/spider.php
answers question: http://stackoverflow.com/q/52135929

http://stackoverflow.com/comment/91197630
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52123087
has text: Nope, codereview is strictly for working code. I realize this is borderline too open ended for SO, but thought I'd try my luck.

http://stackoverflow.com/comment/91594591
type: Comment
comment on: http://stackoverflow.com/a/52239463
has text: @shodanshok it is version related. Python2 doesn't have the new bytes type. See my edit.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52210028
accepted answer: http://stackoverflow.com/a/52210290
has comment: http://stackoverflow.com/comment/91369932
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91370017
type: Question
has comment: http://stackoverflow.com/comment/91369958
has answer: http://stackoverflow.com/a/52210290
score: 0
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/91375943
has title: pandas groupby with agg not working on multiple columns
answer count: 1
has body: I'm trying to merge multiple columns, each into a list based on a group by in pandas. Below is the code I'm using grouped_df = df.groupby(['d_id', 'time']).agg({'d_name': lambda x: tuple(x)}, {'ver': lambda x: tuple(x)}, {'f_name': lambda x: tuple(x)}) This only gives me the first column (d_name) in a list with d_id and time in grouped_df. The other two columns do not show as lists. I tried using list earlier but found out that list has an issue with agg function so I resorted to tuple. Let me know if I'm doing something wrong here. Thanks to RafaelC for the answer to this. Now I am trying to add these list columns to the original dataframe as grouped_df. When I see the columns in grouped_df they come out as Index([u'ver', u'f_name', u'd_name'], dtype='object') But when I do a head, I get ver \ d_id time 1 2018-06-01 (ver1, ver2, ver3..... 2 2018-06-01 (ver1, ver2, ver3..... 3 2018-06-01 (ver1, ver2, ver3..... f_name \ d_id time 1 2018-06-01 (f_name1, f_name2, f_name2..... 2 2018-06-01 (f_name1, f_name2, f_name2..... 3 2018-06-01 (f_name1, f_name2, f_name2..... d_name d_id time 1 2018-06-01 (d_name1, dname2, d_name3... 2 2018-06-01 (d_name1, dname2, d_name3... 3 2018-06-01 (d_name1, dname2, d_name3... How do I get the following d_id time ver d_name f_name where ver, d_name and f_name are lists. Hope this is clear.

http://stackoverflow.com/q/52247468
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3964681
has comment: http://stackoverflow.com/comment/91443425
type: Question
has comment: http://stackoverflow.com/comment/91443239
has answer: http://stackoverflow.com/a/52247762
has title: Open and Read : Multiple xml files from the Folder python
has comment: http://stackoverflow.com/comment/91443300
tagged with: beautifulsoup
score: 0
tagged with: lxml
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52247762
has body: I have stored about 150+ XML files in one folder. I want to open and read those XML files from that folder (about 150+ XML files); after that, I do the next analysis. What do I need to change in the below code to open/read the multiple XML files from that folder? from bs4 import BeautifulSoup import lxml import pandas as pd infile = open("F:\\itprocess\\xmltest.xml","r") contents = infile.read()

http://stackoverflow.com/comment/91259786
type: Comment
has text: Nope. No change.
comment on: http://stackoverflow.com/q/52154728
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91308801
has text: This answers your first question.
score: 0
comment on: http://stackoverflow.com/a/52179264
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91325578
type: Comment
comment on: http://stackoverflow.com/q/52179181
score: 0
has text: Unfortunately, I still have the same output missing buttons ">" and "<".Here it is: &nbsp; 1 / 3,577 &nbsp;
type: QuestionComment

http://stackoverflow.com/q/52118765
favorite count: 0
accepted answer: http://stackoverflow.com/a/52118860
tagged with: python
tagged with: unit-testing
type: AnsweredQuestion
tagged with: python-mock
upvote count: 5
tagged with: python-unittest
has title: mock a method located in the __init__.py
has answer: http://stackoverflow.com/a/52118860
type: Question
score: 5
answer count: 1
downvote count: 0
has body: I would like to mock a method which is in the init.py, but actually it is not working. There is an example to demonstrate the issue and how I tried to write the unit test: The code under test: src.main.myfile: from src.main.utils import a_plus_b def method_under_test(): a_plus_b() The a_plus_b is in the __init__.py in the src.main.utils module: def a_plus_b(): print("a + b") The unittest: import src.main.utils import unittest from mock import patch from src.main.myfile import method_under_test class my_Test(unittest.TestCase): def a_plus_b_side_effect(): print("a_plus_b_side_effect") @patch.object(utils, 'a_plus_b') def test(self, mock_a_plus_b): mock_a_plus_b.side_effect = self.a_plus_b_side_effect method_under_test() The unit test prints the "a + b", and not the side effect. Could anyone help me out what I did wrong?

http://stackoverflow.com/q/52168051
has comment: http://stackoverflow.com/comment/91308707
downvote count: 0
type: UnansweredQuestion
tagged with: scikit-learn
tagged with: python
score: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/52168191
upvote count: 1
tagged with: machine-learning
answer count: 1
has comment: http://stackoverflow.com/comment/91286658
tagged with: tensorflow
has title: Automatic feature selection - Sklearn.feature_selection
has body: I have two datasets a train and test data. train.shape = (307511, 122) and test.shape = (48744, 121). both these data sets contain these dtype: int32, float64 and object. I did hot encoding to convert objects to either float or int dtype. train = pd.get_dummies(train) test = pd.get_dummies(test) print('Train dummies shape: {}'.format(train.shape)) print('Test dummies shape: {}'.format(test.shape)) I got these results from the code above: Train dummies shape: (307511, 246) Test dummies shape: (48744, 242) The shape has changed thus HotEncoding has succeeded. But now the problem I am facing is that When I try to train and test my data i get this error: ValueError: Input contains NaN, infinity or a value too large for dtype('float32') These are my imports: from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.feature_selection import SelectFromModel from sklearn.ensemble import ExtraTreesClassifier Please help
has comment: http://stackoverflow.com/comment/91308724

http://stackoverflow.com/q/52168023
type: AnsweredQuestion
has body: I've written code for a programming mission 2 on hackthissite, just some fun and to practice coding etc. I have completed the mission, but I was unable to get Python to login using the requests library and upload my code to the form automatically. Here is a snippet from my code with the code that is not working and still says "you need to login" in page content: def upload_code(key): login_url = 'https://www.hackthissite.org/user/login' btn_submit = 'Login' username = 'example_username' password = 'example_password' login = { 'btn_submit': btn_submit, 'password': password, 'username': username, } session = requests.session() header_auth = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko', 'referer': 'www.hackthissite.org/user/login' } auth = session.post(login_url, headers=header_auth, data=login) challange_url = 'https://www.hackthissite.org/missions/prog/2/index.php' header = {'referer': 'www.hackthissite.org/missions/prog/2/index.php'} data = {'solution': key} r = session.post(challange_url, headers=header, data=data, verify=True) print(r.content) If anyone can tell me what I'm doing wrong, I would be very appreciative.
downvote count: 0
score: 1
tagged with: authentication
has answer: http://stackoverflow.com/a/52190138
tagged with: python-requests
type: Question
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52190138
has title: Login and send form not working with requests

http://stackoverflow.com/a/52243439
type: Answer
answers question: http://stackoverflow.com/q/52243385
score: 0
has body: Use of 'latitude=-?\d+\.\d+|longitude=-?\d+\.\d+' pattern with findall yields you a list of what is desired: import re req = "&lt;Request 'http://127.0.0.1:5000/findrisk?latitude=32.7766642&amp;longitude=-96.79698789999998' [GET]&gt;" print(re.findall('latitude=-?\d+\.\d+|longitude=-?\d+\.\d+', req)) # ['latitude=32.7766642', 'longitude=-96.79698789999998']

http://stackoverflow.com/comment/91202592
score: 0
type: Comment
has text: actually I will try to pursue this myself for a while. I don't want to ask you to "please fix this tutorial from 2012" (unless you are so inclined) ;-)
comment on: http://stackoverflow.com/a/52125788
type: AnswerComment

http://stackoverflow.com/comment/91254742
comment on: http://stackoverflow.com/q/52151673
type: Comment
has text: @pic0 any other solution? I am not sudo to do that!
score: 0
type: QuestionComment

http://stackoverflow.com/a/52114348
accepted answer of: http://stackoverflow.com/q/52114247
has comment: http://stackoverflow.com/comment/91179234
has body: Use: list(zip(*[df[col] for col in df])) OP's request to start from second column: list(zip(*[df[col] for col in df.iloc[:,1:]])) Or list(zip(*[df[col] for col in df.columns[1:]]))
answers question: http://stackoverflow.com/q/52114247
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91179373
has comment: http://stackoverflow.com/comment/91179208
score: 6
type: Answer
has comment: http://stackoverflow.com/comment/91179310
downvote count: 0
upvote count: 6

http://stackoverflow.com/a/57736414
upvote count: 3
downvote count: 3
has comment: http://stackoverflow.com/comment/120123881
score: 0
type: Answer
has body: Just enter the precise image format. .jpg instead of .jpeg.
answers question: http://stackoverflow.com/q/52162004

http://stackoverflow.com/comment/91205246
comment on: http://stackoverflow.com/a/52126359
has text: Can you try now, I tested on someone else's computer also and it is working
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52139518
tagged with: scipy
has answer: http://stackoverflow.com/a/52139598
accepted answer: http://stackoverflow.com/a/52139598
linked to: http://stackoverflow.com/q/52135891
type: Question
has comment: http://stackoverflow.com/comment/91228729
upvote count: 2
tagged with: numpy
tagged with: arrays
downvote count: 0
answer count: 1
tagged with: iteration
favorite count: 0
has comment: http://stackoverflow.com/comment/91228905
tagged with: python
score: 2
type: AnsweredQuestion
has title: AttributeError: __enter__ when using numpy nditer inside the with statement
has body: I am trying to iterate over a numpy array and change some values inside it. Here's my code, it's literally copied from the documentation (numpy nditer docs): import numpy as np a = np.arange(6).reshape(2,3) print(a) with np.nditer(a, op_flags=['readwrite']) as it: for x in it: x[...] = 2 * x print(a) But I keep getting the following traceback: Traceback (most recent call last): File "text.py", line 5, in &lt;module&gt; with np.nditer(a, op_flags=['readwrite']) as it: AttributeError: __enter__ Am I doing something incorrectly, or is there a mistake in the docs (is the usage of nditer inside with deprecated)?

http://stackoverflow.com/a/52264271
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52252122
answers question: http://stackoverflow.com/q/52252122
has body: I think your socket didn't get the message. Add the following listener to your js file. socket.onmessage = function(event) { alert(event.data); };
type: Answer
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/52188699
type: Answer
upvote count: 4
has body: I am not sure if I understand right. But unlike you, while I was getting reference I was using basic vector math: AB = AC - BC A and B are the markers, C is the camera. so if I invert reference tvec&amp;rvec, add to first markers, I got the relative point. To that, I wrote two functions: def inversePerspective(rvec, tvec): """ Applies perspective transform for given rvec and tvec. """ R, _ = cv2.Rodrigues(rvec) R = np.matrix(R).T invTvec = np.dot(R, np.matrix(-tvec)) invRvec, _ = cv2.Rodrigues(R) return invRvec, invTvec def relativePosition(rvec1, tvec1, rvec2, tvec2): """ Get relative position for rvec2 &amp; tvec2. Compose the returned rvec &amp; tvec to use composeRT with rvec2 &amp; tvec2 """ rvec1, tvec1 = rvec1.reshape((3, 1)), tvec1.reshape((3, 1)) rvec2, tvec2 = rvec2.reshape((3, 1)), tvec2.reshape((3, 1)) # Inverse the second marker, the right one in the image invRvec, invTvec = inversePerspective(rvec2, tvec2) info = cv2.composeRT(rvec1, tvec1, invRvec, invTvec) composedRvec, composedTvec = info[0], info[1] composedRvec = composedRvec.reshape((3, 1)) composedTvec = composedTvec.reshape((3, 1)) return composedRvec, composedTvec I basically used to refer a point. I was using one of the markers rotation in that case but maybe it can help you. I actually wrote it in my blog but it is in turkish. Sorry , I didn't have time to write an english one: My blog post And also you can see my source code for that, I hope it can help you: My source code. Sorry if I misunderstand your problem in there. I didn't test my code for accurate angle reference, I tested it for the translation.
answers question: http://stackoverflow.com/q/52119190
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/138082149

http://stackoverflow.com/comment/91249231
score: 0
type: AnswerComment
has text: Yes, I get a quite huge dataframe. However, why does `np.any(np.isnan(df)` gives True ? I am confused about this...
comment on: http://stackoverflow.com/a/52149388
type: Comment

opencv
tags question: http://stackoverflow.com/q/52223767
type: Tag
tags question: http://stackoverflow.com/q/52141987
tags question: http://stackoverflow.com/q/52195622
tags question: http://stackoverflow.com/q/52227237
tags question: http://stackoverflow.com/q/52154496
tags question: http://stackoverflow.com/q/52233448
tags question: http://stackoverflow.com/q/52122916
tags question: http://stackoverflow.com/q/52264941
tags question: http://stackoverflow.com/q/52247001
tags question: http://stackoverflow.com/q/52266842
tags question: http://stackoverflow.com/q/52247821
tags question: http://stackoverflow.com/q/52220609
tags question: http://stackoverflow.com/q/52212239
tags question: http://stackoverflow.com/q/52255191
tags question: http://stackoverflow.com/q/52197918
tags question: http://stackoverflow.com/q/52241361
tags question: http://stackoverflow.com/q/52165335
tags question: http://stackoverflow.com/q/52237657
tags question: http://stackoverflow.com/q/52221651
tags question: http://stackoverflow.com/q/52225026
tags question: http://stackoverflow.com/q/52116007
tags question: http://stackoverflow.com/q/52155404
tags question: http://stackoverflow.com/q/52199530
tags question: http://stackoverflow.com/q/52175245
tags question: http://stackoverflow.com/q/52242473
tags question: http://stackoverflow.com/q/52125573
tags question: http://stackoverflow.com/q/52153979
tags question: http://stackoverflow.com/q/52206407
tags question: http://stackoverflow.com/q/52144364
tag name: opencv
tags question: http://stackoverflow.com/q/52270275
tags question: http://stackoverflow.com/q/52236276
tags question: http://stackoverflow.com/q/52222864
tags question: http://stackoverflow.com/q/52247440
tags question: http://stackoverflow.com/q/52119190
tags question: http://stackoverflow.com/q/52122152
tags question: http://stackoverflow.com/q/52246874
tags question: http://stackoverflow.com/q/52136449
tags question: http://stackoverflow.com/q/52192049
tags question: http://stackoverflow.com/q/52216412
tags question: http://stackoverflow.com/q/52225466
tags question: http://stackoverflow.com/q/52114338
tags question: http://stackoverflow.com/q/52168491
tags question: http://stackoverflow.com/q/52249947
tags question: http://stackoverflow.com/q/52199132
tags question: http://stackoverflow.com/q/52171097
tags question: http://stackoverflow.com/q/52132298
tags question: http://stackoverflow.com/q/52162004
tags question: http://stackoverflow.com/q/52158553
tags question: http://stackoverflow.com/q/52253095
tags question: http://stackoverflow.com/q/52235092
tags question: http://stackoverflow.com/q/52187913
tags question: http://stackoverflow.com/q/52232165
tags question: http://stackoverflow.com/q/52208482
tags question: http://stackoverflow.com/q/52197693
tags question: http://stackoverflow.com/q/52251534
tags question: http://stackoverflow.com/q/52174391
tags question: http://stackoverflow.com/q/52141240
tags question: http://stackoverflow.com/q/52239183
tags question: http://stackoverflow.com/q/52166578
tags question: http://stackoverflow.com/q/52251232
tags question: http://stackoverflow.com/q/52239740
tags question: http://stackoverflow.com/q/52196231
tags question: http://stackoverflow.com/q/52232871
tags question: http://stackoverflow.com/q/52227224
tags question: http://stackoverflow.com/q/52189203
tags question: http://stackoverflow.com/q/52245570
tags question: http://stackoverflow.com/q/52245231
tags question: http://stackoverflow.com/q/52204156
tags question: http://stackoverflow.com/q/52193545
tags question: http://stackoverflow.com/q/52210867

http://stackoverflow.com/a/52169311
has comment: http://stackoverflow.com/comment/91289052
upvote count: 1
answers question: http://stackoverflow.com/q/52167807
has body: Using category s[s.astype('category').cat.codes&lt;4] Out[153]: 0 1 1 3 2 3 3 5 4 5 6 1 7 4 dtype: int64
downvote count: 0
has comment: http://stackoverflow.com/comment/91289120
type: Answer
score: 1

http://stackoverflow.com/a/65173442
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52128075
score: 1
upvote count: 1
has body: Profiling my small lambda code (outside of lambda) I got these results that you may find interesting. Times in milliseconds # Initially 3 calls to DB, 1350 ms 1st call (read) 1074 ms 2nd call (write) 1051 ms 3rd call (read) # After doing this outside the DB calls and providing it to each one dynamodb = boto3.resource('dynamodb',region_name=REGION_NAME) 12 ms executing the line above 1324 ms 1st call (read) 285 ms 2nd call (write) 270 ms 3rd call (read) # seeing that reusing was producing savings I did the same with tableusers = dynamodb.Table(TABLE_USERS) 12 create dynamodb handler 3 create table handler 1078 read reusing dynamodb and table 280 write reusing dynamodb and table 270 read reusing dynamodb (not table) So initially it took 3.4 seconds, now ~1.6 seconds for just adding 2 lines of code. I got these results using %lprun on jupyter / Colab # The -u 0.001 sets the time unit at 1ms (default is 1 microsecond) %lprun -u 0.001 -f lambdaquick lambdaquick() If you only do 1 DB request and nothing else with the DB, try to put the 2 DB handlers outside the lambda handler as amittn recommends. Disclaimer: I just learned all this, including deep profiling. So all this may be nonsense. Note: "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. -- Donald Knuth" from https://jakevdp.github.io/PythonDataScienceHandbook/01.07-timing-and-profiling.html https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/best-practices.html https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Python.03.html

http://stackoverflow.com/a/52238456
has body: Complexity is O(a+b+c) but that will work: from random import shuffle a = 3 b = 4 c = 5 letters = [] for i in range(a): letters.append('a') for i in range(b): letters.append('b') for i in range(c): letters.append('c') shuffle(letters) print(''.join(letters))
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52238322

http://stackoverflow.com/comment/91447324
comment on: http://stackoverflow.com/q/52248614
has text: @PunterVicky - I would edit your question with the complete code (before solution) and then post your own answer identifying the problem section. I think that some people will benefit from this question.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52121069
score: 6
has comment: http://stackoverflow.com/comment/91193431
tagged with: android
has comment: http://stackoverflow.com/comment/91193520
has body: Can I use Cython to compile an existing Python application for use on Android? I have a Python 3 application with an extensive data model written in Python 3. I would like to have the data model somehow interacted with on Android, even if I have to write a thin "connecting" interface in between the two languages. I'm thinking of using the Android NDK (C++ API) to call into the Python3 objects compiled via Cython, and rewrite the view in Kotlin/Java. I presume I'd have to embed Python into the Android device too. Is this feasible? What would this path look like? Who (or what app) has done this?
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 7
downvote count: 1
has comment: http://stackoverflow.com/comment/91193477
has comment: http://stackoverflow.com/comment/100312122
tagged with: cython
type: Question
has comment: http://stackoverflow.com/comment/91195759
has comment: http://stackoverflow.com/comment/91193337
has title: Cython on Android?
has comment: http://stackoverflow.com/comment/100362547

http://stackoverflow.com/q/52211793
type: Question
has title: Python: Pandas does not separate columns when reading tabular text file
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91373156
tagged with: pandas
has body: I have a text file like this: PERSONAL INFORMATION First Name: Michael Last Name: Junior Birth Date: May 17, 1999 Location: Whitehurst Hall 301. City: Stillwater. State: OK Taken on July 8, 2000 10:50:30 AM MST WORK EXPERIENCE Work type select Part-time ID number 10124 Company name ABCDFG Inc. Positions Software Engineer/Research Scientist Data Analyst/Scientist As you could see the first column is feature names and the second column values. I read it using this code: import pandas as pd import numpy as np import scipy as sp df=pd.read_table('personal.txt',skiprows=1) pd.set_option('display.max_colwidth',10000) pd.set_option('display.max_rows',1000) df But it merges columns and outputs: PERSONAL INFORMATION 0 First Name: Michael 1 Last Name: Junior 2 Birth Date: May 17, 1999 3 Location: Whitehurst Hall 301. City: Stillwater. State: OK 4 Taken on July 8, 2000 10:50:30 AM MST 5 WORK EXPERIENCE 6 Work type select Part-time 7 ID number 10124 8 Company name Google Inc. 9 Positions Software Engineer/Research Scientist 10 Data Analyst/Scientist I should escape from those titles PERSONAL INFORMATION and WORK EXPERIENCE as well. How can I read in a way that it gives me results appropriately in two columns?
has comment: http://stackoverflow.com/comment/91373882
tagged with: multiple-columns
has comment: http://stackoverflow.com/comment/91374052
has comment: http://stackoverflow.com/comment/91373065
has comment: http://stackoverflow.com/comment/91373310
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 0

http://stackoverflow.com/a/52123317
type: Answer
score: -1
answers question: http://stackoverflow.com/q/52123234
downvote count: 1
has body: The portion: int(iinventory.getCarrots()) += number Translates to: int(0) += number # (0 is the current value) int(0) is a function call and it is illegal to assign to it. So instead what you should do is remove the getWhatever methods and use this instead: iinventory.carrots_num += 1 Since your functions return the named attribute, you can just directly access the attributes themselves. Also, you don't need to use int() since it's already an integer
has comment: http://stackoverflow.com/comment/91197918
upvote count: 0

http://stackoverflow.com/q/52195838
tagged with: matplotlib
upvote count: 1
linked to: http://stackoverflow.com/q/1616427
duplicate of: http://stackoverflow.com/q/44049132
tagged with: dataframe
has answer: http://stackoverflow.com/a/52200874
accepted answer: http://stackoverflow.com/a/52195960
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/52200874
favorite count: 0
has body: Hi I'm trying to put two plots side by side with plt and have tried the recommendations here: Trying to position subplots next to each other however I am plotting using the default capabilities from pandas by doing myDataFrame.plot(kind='scatter' x='xcol', y='ycol') so i can't do plt.subplot(2, 1, 2) as in myDataFrame.subplot(2,1,2) (obviously) and doing plt.subplot(1, 2, 1) myDataFrame.plot(kind='scatter' x='xcol', y='ycol') plt.subplot(1, 2, 2) myDataFrame.plot(kind='scatter' x='xcol', y='ycol') just adds two plots before the plot i want any ideas how i can still use myDataframe.plot(kind='scatter') and put two of them side by side
type: Question
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52195960
has title: Matplotlib pyplot putting two plots side by side
linked to: http://stackoverflow.com/q/44049132

http://stackoverflow.com/q/52247301
has answer: http://stackoverflow.com/a/52248861
type: Question
tagged with: heroku
tagged with: discord.py
linked to: http://stackoverflow.com/q/39873920
has comment: http://stackoverflow.com/comment/91445479
answer count: 2
has title: How do I host my discord.py bot on heroku?
has body: I am currently trying to get my discord bot on to Heroku and host it 24/7 but I am having problems. I uploaded my bot to github https://github.com/zemocode/flankebot/tree/master I have created the two main files I needed I clicked deploy branch on Heroku and I'm getting this error. ! No default language could be detected for this app. HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. See https://devcenter.heroku.com/articles/buildpacks ! Push failed I have followed tutorials but everyone else has node.js and I so mine doesn't work.
downvote count: 0
tagged with: discord
has comment: http://stackoverflow.com/comment/122723494
possible better answer: http://stackoverflow.com/a/52248861
favorite count: 0
linked to: http://stackoverflow.com/q/9794413
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52254616
accepted answer: http://stackoverflow.com/a/52254616
upvote count: 2
has comment: http://stackoverflow.com/comment/101334653
tagged with: python
has comment: http://stackoverflow.com/comment/91443074
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/52177570
has answer: http://stackoverflow.com/a/52177665
downvote count: 0
has comment: http://stackoverflow.com/comment/91305312
has body: I am doing python exercises from 'w3resource'. The exercise is 'Write a Python function to find a distinct pair of numbers whose product is odd from a sequence of integer values.'. The code is shown as followed. I don't understand the whole block of "if product &amp; 1". The sign '&amp;' seems set.intersection but not sure. Meanwhile, why do both 'return True' and 'return False' appear? Can anyone explain? Thanks. def product(lst): for i in range(len(lst)): for j in range(len(lst)): if i != j: product = lst[i] * lst[j] if product &amp; 1: return True return False print(product([2, 4, 6, 8])) print(product([1, 6, 4, 7, 8]))
type: Question
has title: Don't understand 'if product & 1'
upvote count: 2
has comment: http://stackoverflow.com/comment/91329630
answer count: 1
has comment: http://stackoverflow.com/comment/91305255
favorite count: 0
accepted answer: http://stackoverflow.com/a/52177665
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/52147130
tagged with: correlation
answer count: 0
has comment: http://stackoverflow.com/comment/91266977
has body: I have one dataframe as below: combination qmin qmax mean median 0 003-124 0.014039 0.309451 0.165592 0.169842 0 014-017 0.992299 0.998932 0.996361 0.997515 0 014-018 0.798309 0.966721 0.903433 0.932848 0 014-019 0.798313 0.966721 0.903433 0.932848 ....................................................... This means the factor003 and factor124 correlation coefficient is 0.165592(column mean),etc. Now I want to get the big correlation matrix,inculding all the factors. How can I get this? Thanks.
type: Question
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91243998
score: 0
has comment: http://stackoverflow.com/comment/91244444
linked to: http://stackoverflow.com/q/29432629
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91244164
tagged with: python
has title: python make correlation matrix

http://stackoverflow.com/q/52252529
tagged with: parallel-processing
has body: Keep getting this error when attempting parallel process in python: An error has occured during the function import Traceback (most recent call last): File "/home/runner/.site-packages/ppft/__main__.py", line 100, in run six.exec_(__fobj) File "&lt;string&gt;", line 46, in &lt;module&gt; ModuleNotFoundError: No module named 'ppft.exceptions' A fatal error has occured during the function execution Traceback (most recent call last): File "/home/runner/.site-packages/ppft/__main__.py", line 109, in run __f = locals()[ppc.str_(__fname)] KeyError: 'run_test' Here is the jist of my code: from pathos.pools import ParallelPool as Pool urls = ["https://www.baidu.com", "https://google.com/"] def run_test(url): #getting and storing a bunch of JSON data from urls in here #content here did not produce errors when doing single process pool = Pool(4) print(pool.map(run_test, urls)) pool.close() pool.join() Please can someone help me understand the error/issue?
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91452738
type: Question
tagged with: parallel-python
has title: Pathos Parallel processing in python Error
downvote count: 0
has comment: http://stackoverflow.com/comment/91454481
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91455221

http://stackoverflow.com/q/52195107
downvote count: 0
has answer: http://stackoverflow.com/a/52199793
favorite count: 0
has title: Why is my plotly graph plotting datetime on x axis as exponents?
possible better answer: http://stackoverflow.com/a/52209270
has answer: http://stackoverflow.com/a/52209270
tagged with: datetime
tagged with: python
has body: I am trying to plot a graph with dates (pandas datetime) on the x axis. However, they are plotting in numerical format instead (showing up as exponents). Example of dates: 0 2014-05-01 1 2014-05-02 2 2014-05-03 3 2014-05-04 4 2014-05-05 Name: date, dtype: datetime64[ns] Code for plotly: trace1 = go.Scatter(x = df_iso_h.date, y=del18_f_hum, mode = 'markers') data = [trace1] py.iplot(data) My x-axis: Not sure how to fix this??
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: plotly
accepted answer: http://stackoverflow.com/a/52199793
type: Question
has answer: http://stackoverflow.com/a/52349321
answer count: 3
tagged with: pandas

http://stackoverflow.com/comment/91222667
type: QuestionComment
has text: I don't use python but an output pipe can block waiting for the other end to start reading.
comment on: http://stackoverflow.com/q/52136385
score: 0
type: Comment

http://stackoverflow.com/comment/91381536
type: QuestionComment
has text: BTW, the whole file reading code could be: `with open("information.txt","r+") as f: p.name, p.last_name = f.read().split(' ', 1)` if there is always a space.
score: 0
comment on: http://stackoverflow.com/q/52216271
type: Comment

http://stackoverflow.com/a/52129602
type: Answer
score: 0
has body: This is an interesting mechanism for creating a list to be used for housing the board state of a tic tac toe game. I'll start off by answering your third question, and build from there. 3) i is short for 'index' when used in the classical for-loop structure. In python, index-based loops are typically used when you need to access the actual index itself (e.g. you have something where you need to perform an action on array_member[i]). You could write the loop as for index in range() if that is more explicit/makes better sense; it doesn't matter to the language what name you choose for the index variable. 2) Building on what we covered in #3, the purpose of the variable square in this context, is to act as the index for the list board over which we are iterating. The naming convention of square is more commonly seen when using a for-each loop, where presumably you would already have a list of squares that you were iterating over: for square in list_of_squares: if square == 'X': # Do something, etc. 1) Based on all of this, the square variable starts off with 0 assigned to it. After the first iteration of the loop, it becomes 1, then 2, etc... until it reaches the limit specified by the range (in this case NUM_SQARES, or 9). It's worth noting that the range function is non-inclusive of the boundary specified, so this loop will execute from 0 to 8, which yields a total of 9 'squares' within the array.
answers question: http://stackoverflow.com/q/52128868

http://stackoverflow.com/q/52239692
has answer: http://stackoverflow.com/a/52239777
tagged with: python
has body: Pretty new to Python here. I am running selenium web driver in order to query some info from a website (only accessible from my organization, yes SQL queries would be much better but this is what I have working at the moment). I am using Selenium's .text method to retrieve text from a table and I print(XXX.text), this returns something like this. XXX.pdf [Remove] XXX.pdf [Remove] etc... The question is I would like to remove, the [Remove] so that I am left with something like: XXX.pdf XXX.pdf or even better XXX.pdf, XXX.pdf This is what I have tried so far which has not worked. dataElement = driver.find_element_by_css_selector('''blah blah blah''') datasheets = str(dataElement.text) datasheets.replace('[Remove]','') print(datasheets) Python 3.5 Selenium 2 Thanks for any help. :)
answer count: 4
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: selenium
type: Question
has answer: http://stackoverflow.com/a/52239763
accepted answer: http://stackoverflow.com/a/52239763
tagged with: replace
upvote count: 1
tagged with: string
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52239777
has answer: http://stackoverflow.com/a/52239958
has answer: http://stackoverflow.com/a/52240041
has title: Editing Multiline Strings in Python

http://stackoverflow.com/a/52168038
score: 1
upvote count: 1
has body: To begin with, this is not a trigonometric polynomial. Trigonometric polynomials have constant coefficients in front of cosines and sines. With expr.coeff(x) you can get the terms that have x as a factor: that is sin(y) + cos(z). But if the expression was x**3*sin(y) + y*cos(x) + x*cos(z) then only cos(z) would be returned. Maybe this is what you want. But if the desired result for this example is x**3*sin(y) + x*cos(z), then use Add(*[v for v in expr.args if v.is_polynomial(x) and v.has(x)]) The logic is to filter the tuple of summands expr.args by the conditions that a term is a polynomial in x, and is a nonconstant polynomial. (Assuming you don't want to include constants).
downvote count: 0
answers question: http://stackoverflow.com/q/52161391
type: Answer

http://stackoverflow.com/q/52189126
type: Question
duplicate of: http://stackoverflow.com/q/42391165
score: 10
duplicate of: http://stackoverflow.com/q/45312377
has title: How to elegantly one hot encode a series of lists in pandas
accepted answer: http://stackoverflow.com/a/52189233
tagged with: python-2.7
tagged with: pandas
duplicate of: http://stackoverflow.com/q/46674157
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91328329
tagged with: python
upvote count: 11
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52189233
has body: So I have the following data: &gt;&gt;&gt; test = pd.Series([['a', 'b', 'e'], ['c', 'a'], ['d'], ['d'], ['e']]) &gt;&gt;&gt; test 0 [a, b, e] 1 [c, a] 2 [d] 3 [d] 4 [e] I am trying to one-hot-encode all of the data in the lists back into my dataframe. To look like this: &gt;&gt;&gt; pd.DataFrame([[1, 1, 0, 0, 1], [1, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]], columns = ['a', 'b', 'c', 'd', 'e']) a b c d e 0 1 1 0 0 1 1 1 0 1 0 0 2 0 0 0 1 0 3 0 0 0 1 0 4 0 0 0 0 1 I have tried researching and I've found similar problems but none like this. I have attempted: test.apply(pd.Series) But that doesn't quite accomplish the one-hot aspect. That simply unpacks my lists in an arbitrary order. I'm sure I could figure out a lengthly solution but I'd be glad to hear if there's a more elegant way to perform this. Thanks! EDIT: I am aware that I can iterate through my test series, then create a column for each unique value found, then go back and iterate through test again, flagging said columns for unique values. But that doesn't seem very pandorable to me and I'm sure there's a more elegant way to do this.
linked to: http://stackoverflow.com/q/42391165
downvote count: 1
duplicate of: http://stackoverflow.com/q/46942847

http://stackoverflow.com/a/52194260
has body: Here's a solution that uses AbstractEventLoop.create_task to create a Task object that you can then Task.cancel at any time. bot = commands.Bot(command_prefix="!") counter_channel = None task = None async def ex(message): global counter_channel if counter_channel is not None: await bot.send_message( message.channel, embed=discord.Embed("There is a counter in {}".format(counter_channel.mention), color=discord.Color.red() )) return counter_channel = message.channel # reduced waits for easy testing await bot.send_message(message.channel, "5 Minutes") await asyncio.sleep(5) await bot.send_message(message.channel, "4 Minutes") await asyncio.sleep(5) await bot.send_message(message.channel, "3 Minutes") await asyncio.sleep(5) await bot.send_message(message.channel, "2 Minutes") await asyncio.sleep(5) counter_channel = None @bot.command(pass_context=True) async def timer(ctx): global task task = bot.loop.create_task(ex(ctx.message)) @bot.command(pass_context=True) async def cancel(ctx): global task, counter_channel task.cancel() task = None counter_channel = None
type: Answer
answers question: http://stackoverflow.com/q/52190862
score: 0

http://stackoverflow.com/q/52195449
type: Question
has answer: http://stackoverflow.com/a/52195646
answer count: 2
tagged with: for-loop
tagged with: dictionary-comprehension
downvote count: 0
has body: I have a dictionary with values that are Pandas DataFrames. I would like to create new columns in each of the DataFrames. I could easily use a for loop, but I'd like a more pythonic way of doing it. Dictionary comprehensions seem like an ideal way to do it. How would this be done using dictionary comprehension? df1 = pd.DataFrame(data =[['2013',98],['2014',100],['2015',110], ['2016',110],['2017',115]], columns = ['Year','Value']) df2 = pd.DataFrame(data =[['2013',85],['2014',90],['2015',95], ['2016',97],['2017',99]], columns = ['Year','Value']) df3 = pd.DataFrame(data =[['2013',30],['2014',28],['2015',25], ['2016',28],['2017',32]], columns = ['Year','Value']) d1 = {} d1['df1'] = df1 d1['df2'] = df2 d1['df3'] = df3 for k in d1.keys(): d1[k]['shifted'] = d1[k]['Value'].shift(2)
has title: Dictionary Comprehension to Create New Columns in Stored DataFrames
tagged with: pandas
has answer: http://stackoverflow.com/a/52195613
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52195613
score: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91340742
possible better answer: http://stackoverflow.com/a/52195646

http://stackoverflow.com/a/67515955
answers question: http://stackoverflow.com/q/52269797
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/120034814
upvote count: 2
has body: In case anyone who meet the same problem from flask import current_app def context_wrap(fn): app_context = current_app.app_context() def wrapper(*args, **kwargs): with app_context: return fn(*args, **kwargs) return wrapper #Then In this case: future_to_track = { executor.submit(context_wrap(build_cache)): 'TRACKER DONE'} #OR In your case: context_wrap(any_func_need_context)
has comment: http://stackoverflow.com/comment/129613077
type: Answer

http://stackoverflow.com/comment/91335289
type: Comment
comment on: http://stackoverflow.com/q/52192635
score: 0
type: QuestionComment
has text: For now you can read the Getting Started Guide (by the link from readme.md). It still requires some efforts.

http://stackoverflow.com/comment/91517181
type: Comment
comment on: http://stackoverflow.com/a/52240807
score: 0
type: AnswerComment
has text: I'm interested in the reason this attracted a downvote?

http://stackoverflow.com/a/52139215
type: Answer
has body: Please note, the following explanation is a little simplified: Your variables are stored in the RAM of your computer as long as your program is running. As soon as you restart it, the changes will be lost! Let's see why: Your program is basically a text file that is taken by the python interpreter and read. For every variable python will allocate a small chunk of RAM memory. As long as your program is running, python can read or write that chunk of memory. That happens if you access the variable. As soon as python is "done" with your code it will free all the RAM it allocated. That way, other processes can use the RAM. Your variables will be lost. You shouldn't change that process. The fact that your variables are lost is intended. But there are still ways to store your data. There are several ways to do this. Read the Python documentation on how to write into a file. You can build a class that writes down all these values when your program terminates and reads them when you start it up again. A simple text file might do or you could search for packages that will do that for you. Pickle might be a start, but there might be better ways to do this. Alternatively you can build a function that saves your values whenever they change. This can generate a lot of write/read accesses to your hard drive so be careful when you do this. If you want to make sure that your game is safe from cheating you can think about encoding your stats so you can't edit them with a text editor. Also, I recommend that you should read more about classes. Currently you use the class Gas within the class Ore. Does that makes sense? Is a Gas an Ore? Also, do you want to write down every item in the game? How about a dictionary to count your ores? Also check out pygames. It is a little dated but they have tutorials that might help you.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52138966
upvote count: 1

http://stackoverflow.com/comment/91466608
comment on: http://stackoverflow.com/a/52256856
score: 0
type: Comment
has text: I respect your opinion (-: However, the reason I like it is that it is an easy way to generate several dataframes at one time. The value is up to the user.
type: AnswerComment

http://stackoverflow.com/comment/91206694
type: Comment
has text: If you substitute `CMD ["python", "flask_app.py", "--host", "0.0.0.0"]` by `CMD ["env"]` you might see if the environment is ok, and if the problem happens due to docker or something flask related
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52127513

http://stackoverflow.com/q/52128744
has body: I am new to PyTorch and have been doing some tutorial on CIFAR10, specifically with Google Colab since I personally do not have a GPU to experiment on it yet. I have successfully trained my neural network but I'm not sure whether my code is using the GPU from Colab, because the training time taken with Colab is not significantly faster than my 2014 MacBook Pro (without GPU). I checked and my notebook is indeed running Tesla K80 but somehow the training speed is slow. So I think perhaps my code is not equipped with GPU syntax but I couldn't figure out which part is that. # install PyTorch from os import path from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag platform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag()) accelerator = 'cu80' if path.exists('/opt/bin/nvidia-smi') else 'cpu' !pip install -q http://download.pytorch.org/whl/{accelerator}/torch-0.4.0-{platform}-linux_x86_64.whl torchvision import torch import torch.nn as nn from torch.optim import Adam from torchvision import transforms from torch.autograd import Variable import torchvision.datasets as datasets from torch.utils.data import DataLoader, TensorDataset import matplotlib.pyplot as plt device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print(device) # hyperparameters n_epochs = 50 n_batch_size = 200 n_display_step = 200 n_learning_rate = 1e-3 n_download_cifar = True # import cifar # more about cifar https://www.cs.toronto.edu/~kriz/cifar.html transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) train_dataset = datasets.CIFAR10( root="../datasets/cifar", train=True, transform=transform, download=n_download_cifar) test_dataset = datasets.CIFAR10( root="../datasets/cifar", train=False, transform=transform) # create data loader train_loader = DataLoader(train_dataset, batch_size=n_batch_size, shuffle=True, num_workers=2) test_loader = DataLoader(test_dataset, batch_size=n_batch_size, shuf…
tagged with: google-colaboratory
tagged with: gpu
has title: How to ensure all PyTorch code fully utilises GPU on Google Colab
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52134636
has comment: http://stackoverflow.com/comment/91217418
tagged with: python
accepted answer: http://stackoverflow.com/a/52134636
linked to: http://stackoverflow.com/q/48750199
type: AnsweredQuestion
tagged with: pytorch
score: 7
upvote count: 7
type: Question

http://stackoverflow.com/a/52259329
has comment: http://stackoverflow.com/comment/91466548
downvote count: 0
answers question: http://stackoverflow.com/q/52259001
has comment: http://stackoverflow.com/comment/91468987
type: Answer
score: 1
upvote count: 1
has body: If I'm reading this correctly the error seems to come from trying to use a version of NumPy built for running on python 2.6 while your app is running using Python3. Try removing NumPy using; "sudo pip uninstall numpy" and then use "pip -H install Numpy" to try reinstalling it and seeing if it correctly finds the Python3 version of Numpy

http://stackoverflow.com/q/52212512
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91398716
downvote count: 0
has comment: http://stackoverflow.com/comment/91375653
has comment: http://stackoverflow.com/comment/91374611
has comment: http://stackoverflow.com/comment/91374490
has comment: http://stackoverflow.com/comment/91374648
favorite count: 0
has comment: http://stackoverflow.com/comment/91375576
has body: I am new to multicore programming with Python. So first this is an example code, that shows my problem: numpyarray = np.zero((100, 100)) def myMainFunction(x, y, t, data): global numpyarray x += t numpyarray[x][y]+=data for line in myDict: x = myDict[line]['pos']['x'] y = myDict[line]['pos']['y'] digit = 0 for data in FD[line]['data']: digit += 1 t = otherFunction(digit) myMainFunction(x, y, t, data) So my two main problems are, that I have a global variable, the numpy array, that i want to fill parallel and that i have more than variable for the myMainFunction that i wanna run parallel. Anyone an Idea how tu run this parallel, because the code takes a lot of time..
type: UnansweredQuestion
tagged with: python
has title: Can you Fill a global Numpy Array with multiple cores in Python?
has comment: http://stackoverflow.com/comment/91403575
answer count: 0
has comment: http://stackoverflow.com/comment/91374663
score: 1
upvote count: 1

http://stackoverflow.com/comment/91432965
comment on: http://stackoverflow.com/q/52242293
has text: So you want to sort by the two digits in each string, is that it? Can there ever be more than a single digit?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91473144
type: QuestionComment
has text: Where is `numberofmonths` defined?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52262667

http://stackoverflow.com/q/52261948
score: 1
tagged with: scikit-learn
favorite count: 0
tagged with: python-3.x
tagged with: metrics
tagged with: python
has body: I'm trying to do a score between two files. The two have the same data but not the same label. Labels from train data are corrects and the labels from test data not necessarily... and I would like to know the accuracy, recall and f-score. import pandas import numpy as np import pandas as pd from sklearn import metrics from sklearn import cross_validation from sklearn.linear_model import LogisticRegression from sklearn.metrics import precision_recall_fscore_support as score from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics import precision_score, recall_score, confusion_matrix, classification_report, accuracy_score, f1_score df_train = pd.read_csv('train.csv', sep = ',') df_test = pd.read_csv('teste.csv', sep = ',') vec_train = TfidfVectorizer() X_train = vec_train.fit_transform(df_train['text']) y_train = df_train['label'] vec_test = TfidfVectorizer() X_test = vec_test.fit_transform(df_train['text']) y_test = df_test['label'] clf = LogisticRegression(penalty='l2', multi_class = 'multinomial',solver ='newton-cg') y_pred = clf.predict(X_test) print ("Accuracy on training set:") print (clf.score(X_train, y_train)) print ("Accuracy on testing set:") print (clf.score(X_test, y_test)) print ("Classification Report:") print (metrics.classification_report(y_test, y_pred)) A stupid example of the data: TRAIN text,label dogs are cool,animal flowers are beautifil,plants pen is mine,objet beyonce is an artist,person TEST text,label dogs are cool,objet flowers are beautifil,plants pen is mine,person beyonce is an artist,animal Error: Traceback (most recent call last): File "accuracy.py", line 30, in y_pred = clf.predict(X_test) File "/usr/lib/python3/dist-packages/sklearn/linear_model/base.py", line 324, in predict scores = self.decision_function(X) File "/usr/lib/python3/dist-packages/sklearn/linear_model/base.py", line 298, in decision_function "yet" % {'name': type(self).name}) sklearn.exceptions.NotFittedError: This LogisticRegression instance …
type: AnsweredQuestion
tagged with: machine-learning
upvote count: 1
has answer: http://stackoverflow.com/a/52262676
type: Question
has answer: http://stackoverflow.com/a/52262509
has title: Classification_report between two files
possible better answer: http://stackoverflow.com/a/52262509
has comment: http://stackoverflow.com/comment/91473842
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/52262676

http://stackoverflow.com/comment/91508971
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52267375
type: Comment
has text: I did but it is the SLURM cluster, and it did not show anything relevant I think

http://stackoverflow.com/a/52137850
has comment: http://stackoverflow.com/comment/91225799
has comment: http://stackoverflow.com/comment/91227567
type: Answer
has comment: http://stackoverflow.com/comment/91227658
downvote count: 1
score: -1
has comment: http://stackoverflow.com/comment/91225768
has comment: http://stackoverflow.com/comment/91228456
upvote count: 0
has comment: http://stackoverflow.com/comment/91228527
accepted answer of: http://stackoverflow.com/q/52137832
has body: Using list comprehension. Please note that a(1) is not the way to access elements in python. Also, the index starts from 0. You can now print a[0], a[1] and so on. a=[i.reshape((2,2)).T for i in a] # Update after your comment Output [array([[11, 13], [12, 14]]), array([[15, 17], [16, 18]]), array([[19, 21], [20, 22]])]
answers question: http://stackoverflow.com/q/52137832
type: AcceptedAnswer

http://stackoverflow.com/comment/92384394
has text: Another comment: This doesn't work because here the embeddings are not saved. In Graph mode, the embeddings are saved as part of the graph (in the checkpoint). In the above code, you provide the variable name for the embeddings, and the metadata. The name is useless without a graph that has variables.
type: QuestionComment
comment on: http://stackoverflow.com/q/52115445
score: 0
type: Comment

http://stackoverflow.com/q/52181539
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91315927
has title: Microsoft.Scripting.SyntaxErrorException: "unexpected token ','" how to fix?
has comment: http://stackoverflow.com/comment/91314615
type: Question
has comment: http://stackoverflow.com/comment/91314422
tagged with: python
has comment: http://stackoverflow.com/comment/91314471
score: 0
tagged with: ironpython
tagged with: c#
has body: I'm new in programming on c# and python I'm using IronPython library for visual studio I have this problem: Microsoft.Scripting.SyntaxErrorException: "unexpected token ','" , when i run c# code. I want to get "var" of .py func; My C# code ScriptEngine engine = Python.CreateEngine(); ScriptScope scope = engine.CreateScope(); var searchPaths = engine.GetSearchPaths(); searchPaths.Add(@"C:/Program Files (x86)/Microsoft Visual Studio/Shared/Python36_64/Lib/site-packages/"); searchPaths.Add(@"C:/Program Files (x86)/Microsoft Visual Studio/Shared/Python36_64/Lib/"); engine.SetSearchPaths(searchPaths); engine.ExecuteFile(@"C:/Users/VYashunin/source/repos/PythonApplication1/PythonApplication1/PythonApplication1.py", scope); dynamic min = scope.GetVariable("minValue"); Console.WriteLine(min); And my .py code # -*- coding: utf-8 -*- from pyzabbix import ZabbixAPI import sys import os sys.path.append(r"c:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\Lib") requestToZabbix = ZabbixAPI(url='http://192.168.1.22/zabbix/', user='admin', password='zabbix') minValue = None avgValue = None maxValue = None print("Подключение к Zabbix успешно. API Version %s" % requestToZabbix.api_version()) response = requestToZabbix.history.get(itemids=30171, time_from=1530403200, time_till=1532995199, history=0) vals = [float(x['value']) for x in response] minValue = min(vals) print(minValue) avgValue = round(sum(vals)/len(vals)) print(avgValue) maxValue = max(vals) print(maxValue) What is this and how to fix this problem? Sorry for my eng :)
has comment: http://stackoverflow.com/comment/91313592
answer count: 0
tagged with: .net
has comment: http://stackoverflow.com/comment/91313421

http://stackoverflow.com/a/52231992
score: 5
type: Answer
answers question: http://stackoverflow.com/q/52231294
has body: First of all, Django does not require this specific folder structure for templates to work, it is just a stablished pattern to do so. And, of course, it has a rationale, as pointed in the official doc: Template namespacing Now we might be able to get away with putting our templates directly in polls/templates (rather than creating another polls subdirectory), but it would actually be a bad idea. Django will choose the first template it finds whose name matches, and if you had a template with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the easiest way to ensure this is by namespacing them. That is, by putting those templates inside another directory named for the application itself. You can reference to this question or that another for concrete cases. In a nutshell, by following this pattern you can have your templates organized in 2 groups: templates related to your specific site or project can live inside the directory pointed by the TEMPLATES['DIRS'] setting; templates related to a specific app, that could be served as is if you make your app pluggable, should live inside './appname/templates/appname/' (and TEMPLATES['APP_DIRS'] must be True). This way you avoid name conflicts between files inside this folder anf files from outside.
upvote count: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52231294

http://stackoverflow.com/comment/91470412
type: Comment
comment on: http://stackoverflow.com/q/52260968
has text: @tgikal, sorry, seem like not valid syntax for python string concatenate.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91363571
comment on: http://stackoverflow.com/q/52207104
type: QuestionComment
has text: Yes, the results are in the same order but teams that are tied need to have the same position on the log. See FC Awesome and Snakes. They are both tied for third place.
score: 0
type: Comment

http://stackoverflow.com/comment/91210081
type: QuestionComment
has text: You will not be able to run python like you doing. If you are writing some server side code, checkout python flask framework or similar.
type: Comment
comment on: http://stackoverflow.com/q/52129856
score: 0

http://stackoverflow.com/comment/91366437
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52206272
has text: Python can be embedded into a C++ application, further broadening this question. Or are we talking strictly about _interpriter environments_?

http://stackoverflow.com/a/52234595
upvote count: 1
answers question: http://stackoverflow.com/q/52234407
type: Answer
downvote count: 0
score: 1
has body: Considered dataframe Date 546451991 2018-07-31 00:00:00 546451991 2018-08-02 00:00:00 5441440119 2018-08-13 00:00:00 5441440119 2018-08-13 00:00:00 5441440119 2018-08-14 00:00:00 5344265358 2018-07-13 00:00:00 5344265358 2018-07-15 00:00:00 5441438884 2018-07-19 00:00:00 extracting the day of dataframe df['day'] = pd.to_datetime(df['Date']).dt.day_name() df Out: Date day 546451991 2018-07-31 00:00:00 Tuesday 546451991 2018-08-02 00:00:00 Thursday 5441440119 2018-08-13 00:00:00 Monday 5441440119 2018-08-13 00:00:00 Monday 5441440119 2018-08-14 00:00:00 Tuesday 5344265358 2018-07-13 00:00:00 Friday 5344265358 2018-07-15 00:00:00 Sunday 5441438884 2018-07-19 00:00:00 Thursday Please go through the Pandas documentation for more information about pandas function. Pandas Documentation

http://stackoverflow.com/comment/91237806
score: 0
type: Comment
type: QuestionComment
has text: Apparently there is no `0001_initial` migration in your `account` app.
comment on: http://stackoverflow.com/q/52138664

http://stackoverflow.com/q/52118485
answer count: 1
has comment: http://stackoverflow.com/comment/91188172
favorite count: 0
tagged with: numba
has title: CUDA Function Won't Execute For Loop on Python with Numba
tagged with: python
tagged with: cuda
has comment: http://stackoverflow.com/comment/91188054
type: AnsweredQuestion
has body: I'm trying to run a simple update loop of a simulation on the GPU. Basically there are a bunch of "creatures" represented by circles that in each update loop will move and then there will be a check of whether any of them intersect. import numpy as np import math from numba import cuda @cuda.jit('void(float32[:], float32[:], float32[:], uint8[:], float32[:], float32[:], float32, uint32, uint32)') def update(p_x, p_y, radii, types, velocities, max_velocities, acceleration, num_creatures, cycles): for c in range(cycles): for i in range(num_creatures): velocities[i] = velocities[i] + acceleration if velocities[i] &gt; max_velocities[i]: velocities[i] = max_velocities[i] p_x[i] = p_x[i] + (math.cos(1.0) * velocities[i]) p_y[i] = p_y[i] + (math.sin(1.0) * velocities[i]) for i in range(num_creatures): for j in range(i, num_creatures): delta_x = p_x[j] - p_x[i] delta_y = p_y[j] - p_y[i] distance_squared = (delta_x * delta_x) + (delta_y * delta_y) sum_of_radii = radii[types[i]] + radii[types[i]] if distance_squared &lt; sum_of_radii * sum_of_radii: pass acceleration = .1 creature_radius = 10 spacing = 20 food_radius = 3 max_num_creatures = 1500 num_creatures = 0 max_num_food = 500 num_food = 0 max_num_entities = max_num_creatures + max_num_food num_entities = 0 cycles = 1 p_x = np.empty((max_num_entities, 1), dtype=np.float32) p_y = np.empty((max_num_entities, 1), dtype=np.float32) radii = np.array([creature_radius, creature_radius, food_radius], dtype=np.float32) types = np.empty((max_num_entities, 1), dtype=np.uint8) velocities = np.empty((max_num_creatures, 1), dtype=np.float32) max_velocities = np.empty((max_num_creatures, 1), dtype=np.float32) # types: # male - 0 # female - 1 # food - 2 for x in range(1, 800 // spacing): for y in range(1, 600 // spacing): if num_creatures % 2 == 0: types[num_creatures] = 0 else: types[num_creatures] = 1 p_x[num_creatures] = x * spacing p_y[num_creatures] = y * spacing max_velocities[num_creatures] = 5 num_creatures += 1 device_p_x = cu…
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52123275
score: -1
upvote count: 0
accepted answer: http://stackoverflow.com/a/52123275

http://stackoverflow.com/comment/91264972
has text: Updated the same. Hope this will work. If it does kindly upvote the post, this will keep me motivated.
score: 0
comment on: http://stackoverflow.com/a/52149678
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/91456266
type: AnswerComment
score: 0
type: Comment
has text: thank you sir... i confused when i looking logs for follow and my programs, now it's working! thanks
comment on: http://stackoverflow.com/a/52254075

http://stackoverflow.com/comment/91355157
has text: Hi Charlie, I edited the original question as my answer is too long for posting as comment. Thanks again.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52147687

http://stackoverflow.com/q/52234202
type: UnansweredQuestion
has title: Serial communication between python and arduino
type: Question
has answer: http://stackoverflow.com/a/52238589
tagged with: serial-port
tagged with: python
answer count: 1
score: 0
tagged with: arduino
has body: I am working on object tracking robot. I am using python and OpenCV to detect the object and send the proper data to the arduino that controls two servo motors. The data which should be sent to the arduino are servo motors angles ranging between 0-180. I am using sample codes to understand how python and arduino communicate using serial bus.When I send a single digit, the arduino receives it and work as intended, but when I send more than one digit nothing happens. This is the arduino code: #include &lt;Servo.h&gt; int data; Servo myservo; // create servo object to control a servo // twelve servo objects can be created on most boards int pos = 0; // variable to store the servo position void setup() { Serial.begin(9600); //initialize serial COM at 9600 baudrate pinMode(LED_BUILTIN, OUTPUT); //make the LED pin (13) as output digitalWrite (LED_BUILTIN, LOW); myservo.attach(9); Serial.println("Hi!, I am Arduino"); } void loop() { while (Serial.available()){ //to receive more than one character char buffer[] = {' ',' ',' ',' ',' ',' ',' '}; // Receive up to 7 bytes while (!Serial.available()); // Wait for characters Serial.readBytesUntil('n', buffer, 7); data = atoi(buffer); } myservo.write(data); } And here is the python code: import serial import time # Required to use delay functions arduinoSerialData = serial.Serial('com14', 9600) # Create Serial port object called arduinoSerialData time.sleep(2) # wait for 2 secounds for the communication to get established print arduinoSerialData.readline() # read the serial data and print it as line print ("Enter 1 to turn ON LED and 0 to turn OFF LED") while 1: # Do this forever var = raw_input() # get input from user print "you entered", var # print the intput for confirmation arduinoSerialData.write(var)

http://stackoverflow.com/a/52118883
type: Answer
answers question: http://stackoverflow.com/q/52116762
downvote count: 0
score: 1
has body: If you don't want to use regex expression, then I have made a code. Its a bit complex but if you look carefully into it then you will understand. def addd(llist,word,word2): xx1 = sum([[i, word] for i in llist], [])[:-1] try:iii = xx1.index(word2);del xx1[iii] except:pass return xx1 a,output = addd("AAAGQWERTYUIOPAGCTHJKLAAAGZXCVBNMAGCT".split("AAAG"),"St4rT",""),[] for i,x in enumerate(a): if "AGCT" in x: output.append(addd(x.split("AGCT"),"3nD.","")) else:output.append(x) total = [] for i in output: if isinstance(i,list):total+=i elif isinstance(i,str):total.append(i) output,typ = [],0 for x,i in enumerate(total): if typ == 0 and i == "St4rT": try:output.append(total[x+1]);typ = 1 except:pass elif typ == 1 and i == "3nD.":typ = 0 print(output) Output: ['QWERTYUIOP', 'ZXCVBNM']
upvote count: 1

http://stackoverflow.com/q/52129192
accepted answer: http://stackoverflow.com/a/52171825
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52131095
has comment: http://stackoverflow.com/comment/91213261
has answer: http://stackoverflow.com/a/52131095
type: Question
has title: How do I automate data extract from Hive to Windows desktop?
has comment: http://stackoverflow.com/comment/91215296
has comment: http://stackoverflow.com/comment/91212216
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91215309
has body: I have to login to bastion Linux host then run kinit and beeline using pbrun, then sftp csv file to Windows. Query sample: "SELECT * FROM db.table WHERE id > 100" Is there a Python script or tool to automate this?
tagged with: python
has answer: http://stackoverflow.com/a/52171825
tagged with: hive

http://stackoverflow.com/comment/91208770
score: 0
type: Comment
type: QuestionComment
has text: So you want *one* message, the last one that is send or received? I find it a bit strange that you here use two messages.
comment on: http://stackoverflow.com/q/52127072

http://stackoverflow.com/a/52164764
has body: I am pretty sure it is not faster, but I find it at least more elegant mydict = {x: some_function(x) for x in animallist}
downvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/52164721
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52164721
type: Answer
upvote count: 2

http://stackoverflow.com/a/52159863
has comment: http://stackoverflow.com/comment/91274118
has comment: http://stackoverflow.com/comment/91284851
has body: like so. model.save_weights('my_model_weights.h5') model.get_weights() can also be used to get the weights of the model, then manually save them to use later model.get_weights() see Link.
answers question: http://stackoverflow.com/q/52159838
score: 0
type: Answer

http://stackoverflow.com/a/52174693
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52157974
type: Answer
score: 1
upvote count: 1
has body: Your index URL isn't correct, see here for how to configure pip to work with Nexus Repo 3: https://help.sonatype.com/display/NXRM3/PyPI+Repositories#PyPIRepositories-ConfiguringPyPIClientTools
answers question: http://stackoverflow.com/q/52157974

http://stackoverflow.com/q/52255898
has comment: http://stackoverflow.com/comment/91488286
has comment: http://stackoverflow.com/comment/91459865
has comment: http://stackoverflow.com/comment/91459524
has comment: http://stackoverflow.com/comment/91460012
favorite count: 0
has body: I'm trying hard to write a Python regex code for extracting German address as show below. Abc Gmbh Ensisheimer Straße 6-8 79346 Endingen Def Gmbh Keltenstr . 16 77971 Kippenheim Deutschland Ghi Deutschland Gmbh 53169 Bonn Jkl Gmbh Ensisheimer Str . 6 -8 79346 Endingen I wrote the below code for extracting individual address components and also put them together as a single regex but still unable to detect the above addresses. Can anyone please help me with it? # TEST COMPANY NAME string = 'Telekom Deutschland Gmbh 53169 Bonn Datum' result = re.findall(r'([a-zA-Zäöüß]+\s*?[A-Za-zäöüß]+\s*?[A-Za-zäöüß]?)',string,re.MULTILINE) print(result) # TEST STREET NAME result = re.findall(r'([a-zA-Zäöüß]+\s*\.)',string) print(result) # TEST STREET NUMBER result = re.findall(r'(\d{1,3}\s*[a-zA-Z]?[+|-]?\s*[\d{1,3}]?)',string) print(result) # TEST POSTAL CODE result = re.findall(r'(\d{5})',string) print(result) # TEST CITY NAME result = re.findall(r'([A-Za-z]+)?',string) print(result) # TEST COMBINED ADDRESS COMPONENTS GROUP result = re.findall(r'([a-zA-Zäöüß]+\s+?[A-Za-zäöüß]+\s+?[A-Za-zäöüß]+\s+([a-zA-Zäöüß]+\s*\.)+?\s+(\d{1,3}\s*[a-zA-Z]?[+|-]?\s*[\d{1,3}]?)+\s+(\d{5})+\s+([A-Za-z]+))',string) print(result) Please note that my objective is that if any of these addresses are present in a huge paragraph of text then the regex should extract and print only the addresses. Can someone please help me?
has comment: http://stackoverflow.com/comment/91459647
has comment: http://stackoverflow.com/comment/91488434
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91459582
has comment: http://stackoverflow.com/comment/91459466
has comment: http://stackoverflow.com/comment/91460503
tagged with: street-address
tagged with: python
has comment: http://stackoverflow.com/comment/91459713
has comment: http://stackoverflow.com/comment/91462053
tagged with: regex
tagged with: regular-language
has comment: http://stackoverflow.com/comment/91459430
has comment: http://stackoverflow.com/comment/91488326
score: 1
has title: Python regex solution for extracting German address format
has comment: http://stackoverflow.com/comment/91459358
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91459277
has comment: http://stackoverflow.com/comment/91488223
linked to: http://stackoverflow.com/q/9863630
has answer: http://stackoverflow.com/a/57449322
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91460608

http://stackoverflow.com/q/52168241
tagged with: selenium
type: Question
has title: Python Store chained methods
tagged with: inheritance
score: 0
has comment: http://stackoverflow.com/comment/91289045
has body: We do have defined tests for apium/selenium like this: def click_start(self): self.log.logEvent("Click on start") return IntroPage1(self.log, self.device) def click_skip(self): self.log.logEvent("Click skip") return Overview(self.log, self.device) etc.. We now have defined following test flow: page.click_start().click_skip().clickPlus().click_HyperCar().click_Continue().editTireAmount(4).editCarName("Koenigsegg") Above technique gives us autocompletion. We need to store this method chain as a shorthand in order to re-use the test at other places. Is there a more elegant way than to do: reUseTest = eval("page.click_start().click_skip().clickPlus().click_SportsCar().click_Continue().editGoalAmount("60000").editGoalName("Moderate")")
has comment: http://stackoverflow.com/comment/91286763
has comment: http://stackoverflow.com/comment/91287252
has comment: http://stackoverflow.com/comment/91288243
has comment: http://stackoverflow.com/comment/91286592
has comment: http://stackoverflow.com/comment/91289372
has comment: http://stackoverflow.com/comment/91289425
type: UnansweredQuestion
tagged with: python
tagged with: oop
has comment: http://stackoverflow.com/comment/91286666
answer count: 0

http://stackoverflow.com/a/52190099
type: Answer
has body: Ok I solved the problem myself. It worked when I passed the model to the softmax-function BEFORE training and trained the network with the returned model of the softmax.
answers question: http://stackoverflow.com/q/52186821
score: 0

http://stackoverflow.com/q/52157840
has answer: http://stackoverflow.com/a/52158010
tagged with: radix
tagged with: python
has title: Function converting a float, base to float
has body: Trying to create function to calculate a float, from a float and base. How do we go about that? Here is what I have done def frac(s, base): import math exp = range(math.log(s, base), -1, -1) for e in exp: d = (s // (base ** e)) s -= d * (base ** e) yield d try to target something like (100.101, base=2) = 4.625
downvote count: 0
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52158010
type: Question
upvote count: 1
tagged with: function
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/91297182
comment on: http://stackoverflow.com/q/52172202
has text: @theGuy added the iframe HTML code above
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52159306
upvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52158930
score: -1
has comment: http://stackoverflow.com/comment/91281828
has comment: http://stackoverflow.com/comment/91280331
downvote count: 1
has body: The file path will be taken relative to your python script (.py file) current working directory. You need to either keep your file.txt in the same directory as your .py file cwd or use the absolute path of your file.txt for open() function like open('/path/to/your/file.txt') (assuming you're running Linux) or open('C:\\path\\to\\your\\file.txt') (windows).

http://stackoverflow.com/comment/103504087
type: Comment
type: QuestionComment
has text: There is no inbuilt solution from the library, but I believe this can be solved with Pandas concat ?!
comment on: http://stackoverflow.com/q/52234696
score: 0

http://stackoverflow.com/comment/105226478
type: AnswerComment
comment on: http://stackoverflow.com/a/52390914
type: Comment
has text: where is "cList" defined? should it be "cuList"?
score: 0

http://stackoverflow.com/q/52183321
tagged with: combinations
tagged with: python-itertools
has answer: http://stackoverflow.com/a/52183757
answer count: 2
has body: I have a list which length is 1442. Every element of the list is a list each contains 10 data points. I have to calculate the correlation of every possible 2 long combinations, and then find groups that correlate the most. Data is available here: import pandas as pd import numpy as np import datetime import math import itertools import matplotlib.pyplot as plt pd.set_option('display.max_rows', 50) pd.set_option('display.max_columns', 50) df_15m = pd.read_csv(r'.../USDT_BTC 15-Minute.csv') df_15m.head() df_15m['date'] = df_15m['date'].apply(lambda x: datetime.datetime.fromtimestamp(x).strftime('%Y-%m-%d %H:%M:%S')) df_15m['day'] = df_15m['date'].apply(lambda x: datetime.datetime.strptime(x,'%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d')) df_15m.set_index('date',inplace=True) df_15m.index = pd.to_datetime(df_15m.index) del df_15m.index.name t = [0] for i in range(len(df_15m)-1): p1 = df_15m.iloc[i+1]['weightedAverage'] p0 = df_15m.iloc[i]['weightedAverage'] t.append(math.log(p1/p0)) df_15m['BVOL15M_INDEX'] = t by_day_vol = pd.DataFrame(df_15m['BVOL15M_INDEX'].resample('H').std()*math.sqrt(24)) by_day_price = pd.DataFrame(df_15m['weightedAverage'].resample('H').mean()) res = pd.merge(by_day_price, by_day_vol, left_index=True, right_index=True) #creating subsets with 10 data points df_ = res[:-6] n = 10 list_df = [df_['BVOL15M_INDEX'][i:i+n] for i in range(0, df_.shape[0], n)] l = [] for subset in itertools.combinations(list_df, 2): corrcoef = np.corrcoef(subset[0], subset[1])[1,0] l.append(corrcoef) l contains the correlations for all possible combinations. I'd like to create a matrix, which ixj position contains the correlation for corresponding groups from list_df. For the final result, i should be able to group periods which are correlating. Can someone please help me, or provide me an easier solution? Thank you!
tagged with: matrix
downvote count: 0
has answer: http://stackoverflow.com/a/52185366
favorite count: 0
type: UnansweredQuestion
has title: Create a matrix of possible combinations with itertools
tagged with: python
tagged with: correlation
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/q/52143951
type: AnsweredQuestion
tagged with: matplotlib
type: Question
has title: How do I plot with x-axis scaled down by a fixed quantity?
answer count: 1
score: 0
tagged with: data-visualization
has body: Say I have the following code: import random import matplotlib.pyplot as plt lis = random.sample(range(1, 5000), 4000) plt.plot(lis) This plots the following: The x-axis is printed from 0 to 4000 with a step size of 1. But I want it to be 0 to 4 with a step size of 0.0001. I tried this: import random import numpy as np import matplotlib.pyplot as plt lis = random.sample(range(1, 5000), 4000) plt.plot(lis) plt.xlabel(np.linspace(0, 4, num=40001)) But this does not do the job: How do I do this?
tagged with: axis-labels
tagged with: python
has answer: http://stackoverflow.com/a/52144423
accepted answer: http://stackoverflow.com/a/52144423
tagged with: plot

http://stackoverflow.com/comment/91310264
has text: That would be true if the include was in a child template, but here it's in the base template.
comment on: http://stackoverflow.com/a/52179760
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52171034
type: Answer
answers question: http://stackoverflow.com/q/52170668
has body: You're updating far too late in your process: note that your update can happen only when you've traversed the entire string, and are back at the top level of the dict. Any time the root matches, you replace the entire tree. You need to start at the tree's root results and traverse downward until you detect the need to update, a difference in the existing structure versus the current string. Then you parse the remaining string and build the sub-tree to add, updating when you've reached the end of the string. Is that sufficient hint for you to do the coding?
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91292999
has comment: http://stackoverflow.com/comment/91293067
upvote count: 1

http://stackoverflow.com/comment/91483703
comment on: http://stackoverflow.com/q/52267901
score: 1
has text: This is unclear. Do you mean that for row 1000, you want to find all rows from 0 to 1000 that are between ClosePrice_low and ClosePrice_high on row 1000? Or all rows where ClosePrice is between ClosePrice_low and ClosePrice_high for each respective row?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91204077
comment on: http://stackoverflow.com/a/52126444
type: AnswerComment
has text: Thank you very much for the helpful answer!
score: 0
type: Comment

http://stackoverflow.com/comment/91368799
has text: A small piece of code, like `(COV_b+J_22)*COV_b+COV_b `, is fine in a comment (between backticks). I slightly updated the function so it now handles this expression too.
score: 1
comment on: http://stackoverflow.com/a/52196005
type: AnswerComment
type: Comment

microblaze
type: Tag
tags question: http://stackoverflow.com/q/52175994
tag name: microblaze

http://stackoverflow.com/a/52147977
has body: You are not treating your data as numbers. You are instead passing the whole file content (a very large string) to nlargest(), which can't do anything but give you the last characters in lexicographical order. The character '9' sorts after the character '8' in this case. You need to a) read your input line by line, not as one big string, and b) convert your data to integers so they are compared by numeric values: from heapq import nlargest def as_numbers(it): for line in it: try: yield int(line) except ValueError: # not a line with a number, skip continue with open('number.txt') as data: five_largest = nlargest(5, as_numbers(data)) print(five_largest) I've used a generator function to convert lines to integers here, because that'll make it easier to keep using heapq.nlargest() (which is absolutely the right tool to use for this job, as it can efficiently keep the top-n values available in O(NlogK) time, so for a fixed K=5 items that's basically linear and only proportional to the number of integer values in the file). The generator function takes care of conversion to int(), skipping any lines that can't be converted. Note also the use of with with the opened file object; at the end of the with block the file is automatically closed for you, no need to call data.close() explicitly here. This will even if there was an exception too! Demo: &gt;&gt;&gt; from heapq import nlargest &gt;&gt;&gt; from io import StringIO &gt;&gt;&gt; random_data = '\n'.join([str(random.randrange(10**6)) for _ in range(10000)]) # 10k lines of random numbers between 0 and 1 million &gt;&gt;&gt; random_data.splitlines(True)[1042:1045] # a few sample lines ['39909\n', '15068\n', '420171\n'] &gt;&gt;&gt; sample_file = StringIO(random_data) # make it a file object &gt;&gt;&gt; def as_numbers(it): ... for line in it: ... try: ... yield int(line) ... except ValueError: ... # not a line with a number, skip ... continue ... &gt;&gt;&gt; nlargest(5, as_numbers(sample_file)) [999873, 999713, 999638, 99…
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/91245780
has comment: http://stackoverflow.com/comment/91245946
type: Answer
has comment: http://stackoverflow.com/comment/91245887
answers question: http://stackoverflow.com/q/52147871
upvote count: 4

http://stackoverflow.com/comment/91374076
has text: I think you are doing it a good way. Anything much simpler would be built in, but I don't think there is anything built in.
score: 1
comment on: http://stackoverflow.com/q/52212326
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91393654
type: Comment
comment on: http://stackoverflow.com/a/52218911
score: 0
type: AnswerComment
has text: I have modified my answer accordingly

http://stackoverflow.com/comment/91385542
type: Comment
type: QuestionComment
has text: But the problem is happening in project_details.html, so you need to show the project_detail view. And the model code is still not valid.
comment on: http://stackoverflow.com/q/52218461
score: 0

http://stackoverflow.com/q/52144543
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/52144610
has comment: http://stackoverflow.com/comment/91246562
favorite count: 0
linked to: http://stackoverflow.com/q/4909691
has answer: http://stackoverflow.com/a/52144610
has title: Python re not extracting matched text based on regex while using boundary
tagged with: regex
downvote count: 0
tagged with: python
tagged with: regex-group
type: AnsweredQuestion
score: 1
duplicate of: http://stackoverflow.com/q/4909691
has body: I am extracting this text from regex, I matched required string in the text but while using python re to extract those matched text, its not extracting . Here is the code I am using. import re PRICE = '\b(price|rs)?\s*(\d+[\s\d.]*\s*?(pkg|k|m| (?:la(?:c|kh|k)|crore|cr)s?|l)\b\.?)' content ='This should matchprice 5.6 lacincluding price(i.e price 5.6 lac) and rs 56 m. including rs (i.e rs 56 k rs 56 m) . It will match normally if there is no price or rs written for example or 56 k or 8.8 crs. are correct matching. It should not match5.6 lac (Should not match eitherrs 6 lac asas there is no spaces before 5.6' for m in re.finditer(PRICE,content,pat.FLAG): matched = m.group().strip() print ("In matched "+ matched)` Above code is not going inside the for loop. Any leads highly appreciated . Thanks.
type: Question

http://stackoverflow.com/a/52127949
answers question: http://stackoverflow.com/q/52126659
has comment: http://stackoverflow.com/comment/91206489
type: Answer
has body: If you are working in a jupyter notebook, then you can use the HTML display to show the images. # Some imports import base64 import pandas as pd from PIL import Image from io import BytesIO from IPython.display import HTML pd.set_option('display.max_colwidth', -1) def get_thumbnail(path): """ Output a 150x150 sized PIL Image """ i = Image.open(path) i.thumbnail((150, 150), Image.LANCZOS) return i def image_base64(im): """ Convert to base64 to be given as the src field of img in HTML """ if isinstance(im, str): im = get_thumbnail(im) with BytesIO() as buffer: im.save(buffer, 'jpeg') return base64.b64encode(buffer.getvalue()).decode() def image_formatter(im): return f'&lt;img src="data:image/jpeg;base64,{image_base64(im)}"&gt;' # Skipping some of your code image_paths = [] for val in q2['nz']: #... Do somethings here x = plt.savefig("value" + str(y) + ".png", bbox_inches='tight') plt.close() image_paths.append("value" + str(y) + ".png") y = y + 1 q2["images_paths"] = pd.Series(image_paths).values q2["image"] = q2.image_paths.map(lambda f: get_thumbnail(f)) # Display PIL Images embedded in the dataframe HTML(q2.to_html(formatters={"image": image_formatter}, escape=False))
has comment: http://stackoverflow.com/comment/91206701
has comment: http://stackoverflow.com/comment/91206579
has comment: http://stackoverflow.com/comment/91206382
has comment: http://stackoverflow.com/comment/91206345
score: 0

http://stackoverflow.com/comment/91190203
score: 0
comment on: http://stackoverflow.com/q/52119429
type: Comment
has text: @ImportanceOfBeingErnest. It works now. but Still not be able add the APPL as my label
type: QuestionComment

http://stackoverflow.com/comment/91463770
has text: Can you also post how you are importing them?
comment on: http://stackoverflow.com/q/52253791
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/91261304
comment on: http://stackoverflow.com/q/52150412
score: 0
type: Comment
has text: "I suspect this is due to the fact that the output variable is very imbalanced" Is there a reason you suspect this is the case? It may be the case that your features do not have enough predictive power. Or maybe, with 146 input features, a first layer with 20 neurons is too small. In my experience, the shape of the output is not a hindrance to learning, provided there is enough information in the features.
type: QuestionComment

http://stackoverflow.com/q/52211482
answer count: 1
accepted answer: http://stackoverflow.com/a/52211483
favorite count: 0
tagged with: python
score: 13
tagged with: julia
downvote count: 1
type: AnsweredQuestion
upvote count: 14
has answer: http://stackoverflow.com/a/52211483
type: Question
has body: In Python it is easy to create a string of n characters: &gt;&gt;&gt; '=' * 40 '========================================' However, in Julia the above does not work. What is the Julia equivalent to the Python code above?
has title: In Julia, how do I repeat a character n times creating a string like in Python?

http://stackoverflow.com/comment/91178777
comment on: http://stackoverflow.com/q/52114168
has text: what is the result of running this code? what did you expect to get?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52137546
has comment: http://stackoverflow.com/comment/91251177
has comment: http://stackoverflow.com/comment/91250679
has comment: http://stackoverflow.com/comment/91228626
has comment: http://stackoverflow.com/comment/91251659
accepted answer of: http://stackoverflow.com/q/52136997
score: 0
has body: If I understood your answer correctly you want that little Tkinter-window to either just show if something changed or to just change its text, right? So for me, the way with less code would be the second one. Therefor I would start up that window in first place and just configure it by label.config(text=&lt;text&gt;). So to make it more clear for you - this should work: import sys import urllib import bs4 as bs from tkinter import * from tkinter import ttk import threading gm = 'ADMINS' root=Tk(className='Status') label=ttk.Label(root,text='-') label.pack() def repeat(): threading.Timer(10, repeat).start() link = 'https://www.daemu.cz/zebricky/online/' request = urllib.request.Request(link, headers={'User-Agent': 'Mozilla/5.0'}) source = urllib.request.urlopen(request).read() #pocet_na_webpage = re.search('je online (.+?) ', str(source)).group(1) #df_table = pd.read_html(source)[0] soup = bs.BeautifulSoup(source, "lxml") table = soup.table #filtering = df_table.filter(items=[0,1,3,6]) table_rows = table.find_all('tr') for tr in table_rows: td = tr.find_all('td') row = [i.text for i in td] #print(row) if gm in row and label.cget('text')=='-': label.config(text='GM je ONLINE!') elif gm not in row and label.cget('text')=='GM je ONLINE!': label.config(text='-') repeat() root.mainloop()
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91258754
answers question: http://stackoverflow.com/q/52136997
has comment: http://stackoverflow.com/comment/91258140
has comment: http://stackoverflow.com/comment/91259046
type: Answer
has comment: http://stackoverflow.com/comment/91258233

http://stackoverflow.com/q/52206251
tagged with: gmail
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91498190
has comment: http://stackoverflow.com/comment/91670283
has comment: http://stackoverflow.com/comment/91711963
has body: In order to round-trip test mail sending code in our GCP backend I am sending an email to a GMail inbox and attempting to verify its arrival. The current mechanism for authentication to the GMail API is fairly standard, pasted from the GMail API documentation and embedded in a function: def authenticate(): """Authenticates to the Gmail API using data in credentials.json, returning the service instance for use in queries etc.""" store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets(CRED_FILE_PATH, SCOPES) creds = tools.run_flow(flow, store) service = build('gmail', 'v1', http=creds.authorize(Http())) return service CRED_FILE_PATH points to a downloaded credentials file for the service. The absence of the token.json file triggers its re-creation after an authentication interaction via a browser window, as does the token's expiry. This is an integration test that must run headless (i.e. with no interaction whatsoever). When re-authentication is required the test currently raises an exception when the authentication flow starts to access sys.argv, which means it sees the arguments to pytest! I've been trying to find out how to authenticate reliably using a mechanism that does not require user interaction (such as an API key). Nothing in the documentation or on Stackoverflow seems to answer this question. A more recent effort uses the keyfile from a service account with GMail delegation to avoid the interactive Oauth2 flows. def authenticate(): """Authenticates to the Gmail API using data in g_suite_access.json, returning the service instance for use in queries etc.""" main_cred = service_account.Credentials.from_service_account_file( CRED_FILE_PATH, scopes=SCOPES) # Establish limited credential to minimise any damage. credentials = main_cred.with_subject(GMAIL_USER) service = build('gmail', 'v1', credentials=credentials) return service On trying to use this service with response = service.users().mess…
has comment: http://stackoverflow.com/comment/91539403
tagged with: authentication
type: Question
has comment: http://stackoverflow.com/comment/91655641
has comment: http://stackoverflow.com/comment/91616872
downvote count: 0
has title: GCP Authentication: RefreshError
score: 4
tagged with: authorization
has comment: http://stackoverflow.com/comment/91487012
has comment: http://stackoverflow.com/comment/91446507
has comment: http://stackoverflow.com/comment/91701207
tagged with: google-cloud-platform
answer count: 1
has comment: http://stackoverflow.com/comment/91649864
linked to: http://stackoverflow.com/q/25413301
has comment: http://stackoverflow.com/comment/91555706
favorite count: 0
has comment: http://stackoverflow.com/comment/91430527
linked to: http://stackoverflow.com/q/42784640
has comment: http://stackoverflow.com/comment/91436706
tagged with: python
has answer: http://stackoverflow.com/a/52342020
accepted answer: http://stackoverflow.com/a/52342020
has comment: http://stackoverflow.com/comment/91478615
upvote count: 4
has comment: http://stackoverflow.com/comment/91443092
linked to: http://stackoverflow.com/q/26736062

http://stackoverflow.com/q/52192877
has comment: http://stackoverflow.com/comment/91335878
has title: Why does inspect return different line for class inheriting from superclass?
type: Question
has comment: http://stackoverflow.com/comment/91335962
has comment: http://stackoverflow.com/comment/91336144
has comment: http://stackoverflow.com/comment/91335701
upvote count: 6
has body: While trying to figure out if a function is called with the @decorator syntax, we realized that inspect has a different behaviour when looking at a decorated class that inherits from a superclass. The following behaviour was found with CPython 3.6.2 under Windows. It was also reproduced in CPython 3.7.0 under Linux. import inspect def decorate(f): lines = inspect.stack()[1].code_context print(f.__name__, lines) return f @decorate class Foo: pass @decorate class Bar(dict): pass Output Foo ['@decorate\n'] Bar ['class Bar(dict):\n'] Why does inheritance change the behaviour of inspect?
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/91335787
tagged with: inspect
has comment: http://stackoverflow.com/comment/91336208
has comment: http://stackoverflow.com/comment/91335772
has comment: http://stackoverflow.com/comment/91335766
has comment: http://stackoverflow.com/comment/91335931
answer count: 1
tagged with: decorator
tagged with: python-decorators
has comment: http://stackoverflow.com/comment/91336130
favorite count: 0
has comment: http://stackoverflow.com/comment/91336179
linked to: http://stackoverflow.com/q/52191968
has comment: http://stackoverflow.com/comment/91335736
has comment: http://stackoverflow.com/comment/91336100
score: 6
has comment: http://stackoverflow.com/comment/91336034
tagged with: python
has comment: http://stackoverflow.com/comment/91336136
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91335926
downvote count: 0
has answer: http://stackoverflow.com/a/52193338
accepted answer: http://stackoverflow.com/a/52193338
has comment: http://stackoverflow.com/comment/91336224

event-handling
tag name: event-handling
type: Tag
tags question: http://stackoverflow.com/q/52269334

http://stackoverflow.com/a/52143950
has comment: http://stackoverflow.com/comment/91237802
has comment: http://stackoverflow.com/comment/91237712
type: Answer
has comment: http://stackoverflow.com/comment/91237763
has comment: http://stackoverflow.com/comment/91237646
answers question: http://stackoverflow.com/q/52143854
has body: Even tho it's really similar to @jezrael's answer but, this is also much better, (it's just using .str accessor for get_dummies: print(df.join(df['Hour'].astype(str).str.get_dummies().add_prefix('HE'))) Output: Date Hour HE1 HE2 HE3 HE4 0 2005-01-01 1 1 0 0 0 1 2005-01-01 2 0 1 0 0 2 2005-01-01 3 0 0 1 0 3 2005-01-01 4 0 0 0 1
has comment: http://stackoverflow.com/comment/91237622
has comment: http://stackoverflow.com/comment/91237698
has comment: http://stackoverflow.com/comment/91237617
has comment: http://stackoverflow.com/comment/91237740
has comment: http://stackoverflow.com/comment/91237774
score: 0
has comment: http://stackoverflow.com/comment/91237770
has comment: http://stackoverflow.com/comment/91237662

http://stackoverflow.com/a/52150757
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52150705
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52150705
has body: You don't need the dot in the format format='csv' This should also work spark.read\ .option("header", "true")\ .csv("some_input_file.csv")
upvote count: 2

http://stackoverflow.com/q/52117513
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/52118882
has comment: http://stackoverflow.com/comment/91186379
downvote count: 0
tagged with: pandas
has body: I'm trying to split an array in a data-frame column and append the individual entries to a new data frame. I managed to write a function that seems to be able to iterate over the individual entries. But when I try to append them to another data frame, the data frame stays empty. Can I even edit a data frame from within a function? import pandas as pd # Original data frame series1 = pd.Series([['cat', 'dog', 'rabbit'], ['frog', 'moose', 'fly']]) oldDF = pd.DataFrame(series1) # New data frame where I want to populate all values in the old series2 = pd.Series([]) newDF = pd.DataFrame(series2) # Define function to iterate over each array def appendItems(x, df): for item in x: for i in item: # Trying to append entries to new dataframe df.append(pd.Series([i]), ignore_index=True) print(pd.Series([i])) # Apply above function to dataframe oldDF.apply(appendItems,args=[newDF]) # Result-&gt; empty data frame :-( print("Checking result") newDF.head()
possible better answer: http://stackoverflow.com/a/52117791
tagged with: python
has answer: http://stackoverflow.com/a/52117791
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/91186445
has answer: http://stackoverflow.com/a/52118882
type: AnsweredQuestion
score: 2
has title: How to pass and editing data frame as an argument in Pandas

http://stackoverflow.com/comment/91499937
comment on: http://stackoverflow.com/a/52258468
score: 0
type: AnswerComment
has text: it asked me "write the name of the file: " and when i key in "Jinni" , it throwing error " name 'Jinni' is not defined "
type: Comment

http://stackoverflow.com/a/52262592
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52262533
has body: This is what I found looking online, I'm sorry but i think that what you are lookin at isn't possible. From WireShark Q&amp;A: What you're looking at are probably neighbor discovery packets, which are sent to a special multicast address called "solicited node multicast". It's basically the replacement mechanism for ARP, which is not used for IPv6 anymore. Usually, if you need to find out where something is coming from you should try to determine the MAC address of the source, and then log in to your switches to find the port where that MAC address is connected. There should be a command that will show you the MAC address table of the switch. If you can find a port where only the MAC address in question is listed you need to follow the cable from that port to the device. If you have more than one MAC address listed for a port it is usually a connection to another switch. In that case you need to log in to the switch it connects to and repeat your search.

http://stackoverflow.com/q/52208627
has comment: http://stackoverflow.com/comment/91367214
answer count: 3
has comment: http://stackoverflow.com/comment/91367243
has comment: http://stackoverflow.com/comment/91366894
has comment: http://stackoverflow.com/comment/91366825
tagged with: readfile
has comment: http://stackoverflow.com/comment/91367733
possible better answer: http://stackoverflow.com/a/52208857
has comment: http://stackoverflow.com/comment/91367618
has answer: http://stackoverflow.com/a/52208857
tagged with: python
tagged with: valueerror
type: AnsweredQuestion
tagged with: command-line
tagged with: compiler-errors
has comment: http://stackoverflow.com/comment/91367475
type: Question
has answer: http://stackoverflow.com/a/52209071
has comment: http://stackoverflow.com/comment/91366827
has comment: http://stackoverflow.com/comment/91367047
has title: In Python, I have a Value Error in my line with .split(), returns 1 expected 2. Adding white space doesn't help. Issue with data.txt?
has comment: http://stackoverflow.com/comment/91366923
has comment: http://stackoverflow.com/comment/91366798
has answer: http://stackoverflow.com/a/52209846
has comment: http://stackoverflow.com/comment/91366645
accepted answer: http://stackoverflow.com/a/52209071
has body: Apologies if that title was vague. First I'd like to say that I have read through every forum I can find on the Value Error in python, I've implemented them but my program still can not get past line 22. There is more explanation at the bottom but first I'll give you the "DL" haha. I am writing a program that reads a data.txt file and displays the output. Here is the goal of the project Your output should look like: Reading vertices for a polygon with 5 vertices... Vertex 1 has coordinates at (1.70, 4.90) Vertex 2 has coordinates at (6.10, 6.20) Vertex 5 has coordinates at (1.50, 1.40) Reading vertices for a rectangle having, (of course), 4 vertices... Vertex 1 has coordinates at (7.00, 5.00) ... Your program only needs to echo check the data; there is no requirement during this lab to construct polygon objects, rectangle objects, to do transformations, to undo transformations, or to find and print perimeter. The error from my command line is: Reading vertices for polygon with 5 vertices... Vertex 1 has coordinates at (1.7, 4) Vertex 2 has coordinates at (.9, 6.1) Vertex 3 has coordinates at (6.2, 7.0) Vertex 4 has coordinates at (2.8, 4.8) Vertex 5 has coordinates at (0.1, 1.) Reading vertices for polygon with 1 vertices... Traceback (most recent call last): File "Read.py", line 22, in &lt;module&gt; x, y = file.read(8).split( ) ValueError: too many values to unpack (expected 2) The code I have written is: file = open("data.txt") line = file.read(1).strip() while line != 'Q': numVertices = file.read(3).strip() numVertices = int(numVertices) if numVertices != 4: print("Reading vertices for polygon with " + str(numVertices) + " vertices...") else: print("Reading vertices for rectangle having " + str(numVertices) + " vertices...") for i in range(int(numVertices)): x, y = file.read(8).split( ) print("Vertex " + str(i + 1) + " has coordinates at (" + x + ", " + y + ")") line = file.read(1).strip() file.close() And the data.txt file contains: P 5 1.7 4.9 6.1 6.2 7.0 2.8 …
has comment: http://stackoverflow.com/comment/91367133
score: 0

http://stackoverflow.com/comment/91323985
has text: ABM models are not trained, and they (normally) do not take data as an input...
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52181092
type: QuestionComment

http://stackoverflow.com/a/52237453
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52229942
has comment: http://stackoverflow.com/comment/91487227
score: 1
answers question: http://stackoverflow.com/q/52229942
type: AcceptedAnswer
downvote count: 0
has body: You can get refined information by using srun to start the python scripts: srun python $NORM_SCRIPT -data $file -path $OUTPUT_DIR Slurm will then create one 'step' per instance of your python script, and report information (errors, return codes, memory used, etc.) for each step independently in the accounting, which you can interrogate with the sacct command. If configured by the administrators, use the --profile option to get a timeline of the memory usage of each step. In your python script you can use the memory_profile module to get a feedback on the memory usage of your scripts.
has comment: http://stackoverflow.com/comment/91476197
has comment: http://stackoverflow.com/comment/91479745

http://stackoverflow.com/comment/91341397
has text: @Zephyr No, in that case just sum your columns. I updated my answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52195972
type: Comment

http://stackoverflow.com/a/52133610
has comment: http://stackoverflow.com/comment/139471657
score: 0
has body: I look into the website and found that there you can put 3 types of values i.e USDOT Number ,MC/MX Number ,Name using radio buttons.Name gives data in GET from like https://safer.fmcsa.dot.gov/keywordx.asp?searchstring=%2A{name_search}%2A&amp;SEARCHTYPE=ANY which you can easily get by requesting this url just by replacing {name_search} with your search name . While USDOT and MC/MX are requesting in POST format form sending to https://safer.fmcsa.dot.gov/query.asp like searchtype=ANY&amp;query_type=queryCarrierSnapshot&amp;query_param={USDOT/MC_MX}&amp;query_string={your_number} for which you have to make a program for getting it for sending this data to the server. import requests url = 'https://safer.fmcsa.dot.gov/query.asp' data = {'searchtype':'ANY','query_type':'queryCarrierSnapshot', 'query_param':'USDOT','query_string':'529136'} r = requests.post(url = url,data = data) print(r.text)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91343002
type: Answer
has comment: http://stackoverflow.com/comment/91343366
answers question: http://stackoverflow.com/q/52122834
has comment: http://stackoverflow.com/comment/91508960
accepted answer of: http://stackoverflow.com/q/52122834
has comment: http://stackoverflow.com/comment/91484814
has comment: http://stackoverflow.com/comment/91296803

http://stackoverflow.com/comment/91189013
type: AnswerComment
type: Comment
has text: @JonClements Indeed. I have added a comment in my answer to account for that.
comment on: http://stackoverflow.com/a/52118584
score: 0

http://stackoverflow.com/q/52172738
tagged with: nested-lists
has comment: http://stackoverflow.com/comment/91296229
has title: Iteration for iteration in a list
tagged with: python
type: AnsweredQuestion
tagged with: list
downvote count: 1
has answer: http://stackoverflow.com/a/52172779
type: Question
tagged with: if-statement
has body: Let's say I have 2 lists and a variable: Name = "Siler City" List1 = ["Frank", "Beth", "Jose" "Pieter"] List2 = ["Red", "Green", "Blue", "Purple"] This is a simple illustration of a complex problem and there is a reason I don't want to create a dictionary. These must be 2 separate list. What I want is to iterate through List1[0] and List2[0], etc... at the same time. So my desired results would be "The Red house is owned by Frank", "The Green house is owned by Beth", "The Blue house is owned by Jose," etc...Why won't the below work and what is a better strategy? for item in List1: if Name == "Siler City": for color in List2: print("The {} house is owned by {}".format(color, item))
score: -1
tagged with: python-3.6
linked to: http://stackoverflow.com/q/1663807
answer count: 2
has answer: http://stackoverflow.com/a/52172782
upvote count: 0
accepted answer: http://stackoverflow.com/a/52172779
duplicate of: http://stackoverflow.com/q/1663807
favorite count: 0
possible better answer: http://stackoverflow.com/a/52172782

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/52123648
type: Tag

list
tags question: http://stackoverflow.com/q/52124961
tags question: http://stackoverflow.com/q/52194145
tags question: http://stackoverflow.com/q/52213265
tags question: http://stackoverflow.com/q/52236217
tags question: http://stackoverflow.com/q/52175248
type: Tag
tags question: http://stackoverflow.com/q/52204308
tags question: http://stackoverflow.com/q/52176882
tags question: http://stackoverflow.com/q/52230596
tags question: http://stackoverflow.com/q/52195635
tags question: http://stackoverflow.com/q/52134327
tags question: http://stackoverflow.com/q/52122948
tags question: http://stackoverflow.com/q/52244850
tags question: http://stackoverflow.com/q/52208981
tags question: http://stackoverflow.com/q/52130222
tags question: http://stackoverflow.com/q/52223756
tags question: http://stackoverflow.com/q/52247828
tags question: http://stackoverflow.com/q/52183330
tags question: http://stackoverflow.com/q/52132465
tags question: http://stackoverflow.com/q/52143330
tags question: http://stackoverflow.com/q/52221346
tags question: http://stackoverflow.com/q/52254319
tags question: http://stackoverflow.com/q/52253988
tags question: http://stackoverflow.com/q/52139141
tags question: http://stackoverflow.com/q/52174095
tags question: http://stackoverflow.com/q/52122876
tags question: http://stackoverflow.com/q/52203775
tags question: http://stackoverflow.com/q/52156496
tags question: http://stackoverflow.com/q/52246499
tags question: http://stackoverflow.com/q/52156828
tags question: http://stackoverflow.com/q/52255060
tags question: http://stackoverflow.com/q/52239110
tags question: http://stackoverflow.com/q/52207645
tags question: http://stackoverflow.com/q/52141529
tags question: http://stackoverflow.com/q/52266397
tags question: http://stackoverflow.com/q/52218251
tags question: http://stackoverflow.com/q/52264041
tags question: http://stackoverflow.com/q/52217032
tags question: http://stackoverflow.com/q/52262119
tags question: http://stackoverflow.com/q/52212220
tags question: http://stackoverflow.com/q/52136002
tags question: http://stackoverflow.com/q/52218717
tags question: http://stackoverflow.com/q/52176002
tags question: http://stackoverflow.com/q/52132537
tags question: http://stackoverflow.com/q/52161941
tags question: http://stackoverflow.com/q/52249484
tags question: http://stackoverflow.com/q/52183039
tags question: http://stackoverflow.com/q/52230276
tag name: list
tags question: http://stackoverflow.com/q/52197289
tags question: http://stackoverflow.com/q/52241126
tags question: http://stackoverflow.com/q/52240343
tags question: http://stackoverflow.com/q/52195456
tags question: http://stackoverflow.com/q/52207120
tags question: http://stackoverflow.com/q/52267850
tags question: http://stackoverflow.com/q/52163200
tags question: http://stackoverflow.com/q/52165025
tags question: http://stackoverflow.com/q/52178627
tags question: http://stackoverflow.com/q/52240981
tags question: http://stackoverflow.com/q/52186918
tags question: http://stackoverflow.com/q/52171427
tags question: http://stackoverflow.com/q/52220462
tags question: http://stackoverflow.com/q/52261561
tags question: http://stackoverflow.com/q/52207140
tags question: http://stackoverflow.com/q/52213794
tags question: http://stackoverflow.com/q/52186737
tags question: http://stackoverflow.com/q/52255960
tags question: http://stackoverflow.com/q/52250038
tags question: http://stackoverflow.com/q/52183862
tags question: http://stackoverflow.com/q/52263695
tags question: http://stackoverflow.com/q/52242489
tags question: http://stackoverflow.com/q/52230938
tags question: http://stackoverflow.com/q/52152815
tags question: http://stackoverflow.com/q/52112805
tags question: http://stackoverflow.com/q/52266350
tags question: http://stackoverflow.com/q/52135161
tags question: http://stackoverflow.com/q/52250375
tags question: http://stackoverflow.com/q/52266424
tags question: http://stackoverflow.com/q/52176923
tags question: http://stackoverflow.com/q/52206550

http://stackoverflow.com/a/52125555
has body: Below I've merged your game with this short example of how to move a segmented snake around the screen that I wrote earlier -- I'm surprised your search of SO didn't turn this up. I've also made some other changes to accomodate this motion. Your snake changes from a turtle to a list of turtles, with the final turtle in the list being the head of the snake. The keyboard arrow handlers no longer change the snake's direction directly, they merely set a new direction variable for when the next turtle movement occurs -- this prevents conflicts in adjusting the turtle. Your while True: has no place in an event-driven world like turtle so it's been replaced with an ontimer() event -- otherwise you potentially lock out events: from random import randint from turtle import Turtle, Screen # force object-oriented turtle SCORE_FONT = ("Calibri", 40, "bold") MESSAGE_FONT = ("Calibri", 24, "bold") SEGMENT_SIZE = 20 def outsidewindow(): (x, y) = snake[-1].pos() # Ask the snake head for its current position return not (leftwall &lt; x &lt; rightwall and bottomwall &lt; y &lt; topwall) def gameover(): for segment in snake: segment.hideturtle() fruit.hideturtle() writeturtle.write("Your snake crawled into the garden! Game over!", align="center", font=MESSAGE_FONT) def showscore(currentscore): scoreturtledude.undo() # Clear the previous score scoreturtledude.write(currentscore, align="right", font=SCORE_FONT) def placefruit(): fruit.hideturtle() fruit.setposition(randint(-200, 200), randint(-200, 200)) fruit.showturtle() def startgame(): screen.onkey(None, "space") # So this doesn't run a second time writeturtle.clear() # Clear the text from the screen showscore(score) for segment in snake: # Show the snake segment.showturtle() placefruit() rungame() def rungame(): global score, snakelength segment = snake[-1].clone() if len(snake) &lt; snakelength else snake.pop(0) screen.tracer(False) # segment.hideturtle() segment.setposition(snake[-1].position()) segment.setheading(snake[-1].headi…
downvote count: 0
answers question: http://stackoverflow.com/q/52124530
has comment: http://stackoverflow.com/comment/91267522
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/52270428
accepted answer: http://stackoverflow.com/a/52270752
linked to: http://stackoverflow.com/q/52266003
answer count: 1
has comment: http://stackoverflow.com/comment/91489183
downvote count: 0
tagged with: sparse-matrix
favorite count: 0
has comment: http://stackoverflow.com/comment/91494345
has comment: http://stackoverflow.com/comment/91494292
has comment: http://stackoverflow.com/comment/91488880
tagged with: python
has comment: http://stackoverflow.com/comment/91494329
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/52270752
has comment: http://stackoverflow.com/comment/91507966
tagged with: scipy
has title: `np.any` returns an object from an object array instead of boolean?
type: Question
tagged with: numpy
score: 3
has body: Ok, in trying to answer this question I came across something very strange. matrix = np.zeros(10000) matrix[np.random.choice(10000, 100)] = np.random.rand(100) matrix = matrix.reshape(10, 1000) from scipy.sparse import lil_matrix l = lil_matrix(matrix.T) l.rows Out: array([[], [], [], ..., [], [], []], dtype=object) Ok, so I want to know which rows have data, so I tried: np.any(l.rows) Out: [8] . . . what? out = np.any(l.rows) type(out) Out: list It's a list. With an 8 in it. Which seems . . . random. What is going on? After playing around it seems it returns the first object in the array that's not []. np.random.seed(9) matrix = np.zeros(10000) matrix[np.random.choice(10000, 100)] = np.random.rand(100) matrix = matrix.reshape(10, 1000) from scipy.sparse import lil_matrix l = lil_matrix(matrix.T) l.rows Out: array([[], [], [5], ..., [], [], []], dtype=object) np.any(l.rows) Out: [5] But considering np.any is only supposed to output boolean or np.array of boolean, this is a very strange result. Does anyone know why this happens?
has comment: http://stackoverflow.com/comment/91488239
has comment: http://stackoverflow.com/comment/91494613

http://stackoverflow.com/comment/91237576
type: Comment
type: QuestionComment
has text: Your code isn't really related to what you're actually asking.
comment on: http://stackoverflow.com/q/52143842
score: 0

http://stackoverflow.com/q/52260806
tagged with: difference
has title: Difference between set of strings doesn't work
has comment: http://stackoverflow.com/comment/91469178
has comment: http://stackoverflow.com/comment/91469251
score: 0
has answer: http://stackoverflow.com/a/52261172
has body: First of all thanks for the help, I'm trying to fix this problem for days. File myStopWords.txt: è ad più a b c 17 My code: stopWord = set(open("&lt;...&gt;/myStopwords.txt").read().split("\n")) oldWords = set(["a","b","ad", "è", "più","17","horse"]) print( oldWords.difference(stopWord) ) Results: {'horse', 'ad', 'più', 'è'} Why aren't "ad", "è", "più" subtracted from the set? The result should be {horse}.
has comment: http://stackoverflow.com/comment/91469277
answer count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/91469325
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91469217
has comment: http://stackoverflow.com/comment/91469230
has comment: http://stackoverflow.com/comment/91469392
tagged with: set
type: Question

http://stackoverflow.com/comment/91332242
type: Comment
score: 1
has text: Your question doesn't fit here particularly well, but is a worthy question. Please check ["Which site?"](https://meta.stackexchange.com/questions/129598/which-computer-science-programming-stack-exchange-do-i-post-in) for general issues and ["Code Review or not?"](https://codereview.meta.stackexchange.com/questions/5777/a-guide-to-code-review-for-stack-overflow-users/5778#5778)
comment on: http://stackoverflow.com/q/52191144
type: QuestionComment

http://stackoverflow.com/a/52246107
answers question: http://stackoverflow.com/q/52240363
has comment: http://stackoverflow.com/comment/91445887
has comment: http://stackoverflow.com/comment/91445768
score: 2
type: AcceptedAnswer
downvote count: 0
has body: To trigger a selection on an aggregated value, the best approach is to use an aggregate transform to define that quantity so that it is available to the entire chart. Here is an example: import altair as alt from altair.expr import datum, if_ from vega_datasets import data interval = alt.selection_interval(encodings=['x', 'y']) base = alt.Chart(data.population.url).transform_filter( filter = datum.year == 2000 ).transform_calculate( "sex", if_(datum.sex == 2, 'Female', 'Male') ).transform_aggregate( population="sum(people)", groupby=['age', 'sex'] ) scatter = base.mark_point().encode( alt.X('age:O', title=''), y='population:Q', color=alt.condition(interval, 'sex:N', alt.value('lightgrey')) ).properties( selection=interval ) bar = base.mark_bar(opacity=0.7).encode( alt.X('age:O', scale=alt.Scale(rangeStep=17)), alt.Y('population:Q'), color=alt.condition(interval, 'sex:N', alt.value('lightgrey')), ).properties(height=100, width=400) scatter &amp; bar Note that I took away the filtering by the interval selection on the lower plot, because that's not the behavior you described.
type: Answer
accepted answer of: http://stackoverflow.com/q/52240363
upvote count: 2

http://stackoverflow.com/comment/91468780
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52248668
has text: "without any overhead at all" isn't possible. Even a simple serial cable requires start and stop bits... You seem to be forgetting Ethernet and IP overhead. UDP overhead just adds 8 bytes and you can't really go with much less...

http://stackoverflow.com/a/52186310
accepted answer of: http://stackoverflow.com/q/52184455
answers question: http://stackoverflow.com/q/52184455
type: Answer
has body: We can check if the class is 'academicsHead' and if it is just check if the text is BACHELOR if not break the loop. Something like this would work: disciplines = soup.findAll('ul',attrs={'class':re.compile(r'academics+(.)+')}) for i in disciplines: if i['class'][0] == 'academicsHead': if i.find('li').text.strip() != 'BACHELOR': break else: print(i.find('li').text.strip())
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/52180079
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/91310110
has body: \ud83d\ude04 is the utf16 representation of the character SMILING FACE WITH OPEN MOUTH AND SMILING EYES (U+1F604) You will need to decode it into a character then convert the code point of the character into a hex string. I don't know enough Python to tell you how to do this.
type: Answer
answers question: http://stackoverflow.com/q/52179465
downvote count: 1

python-3.6
tags question: http://stackoverflow.com/q/52143468
tags question: http://stackoverflow.com/q/52249755
tags question: http://stackoverflow.com/q/52153879
tags question: http://stackoverflow.com/q/52142842
tags question: http://stackoverflow.com/q/52252054
tags question: http://stackoverflow.com/q/52187510
tags question: http://stackoverflow.com/q/52130073
tags question: http://stackoverflow.com/q/52219836
type: Tag
tags question: http://stackoverflow.com/q/52248061
tags question: http://stackoverflow.com/q/52145057
tags question: http://stackoverflow.com/q/52191518
tags question: http://stackoverflow.com/q/52122146
tags question: http://stackoverflow.com/q/52131706
tags question: http://stackoverflow.com/q/52231601
tags question: http://stackoverflow.com/q/52162549
tags question: http://stackoverflow.com/q/52119981
tags question: http://stackoverflow.com/q/52192877
tags question: http://stackoverflow.com/q/52268914
tags question: http://stackoverflow.com/q/52155370
tags question: http://stackoverflow.com/q/52172738
tag name: python-3.6
tags question: http://stackoverflow.com/q/52221036
tags question: http://stackoverflow.com/q/52194612
tags question: http://stackoverflow.com/q/52113140
tags question: http://stackoverflow.com/q/52130635

http://stackoverflow.com/a/52134264
answers question: http://stackoverflow.com/q/52130358
has body: The xpath for bathrooms and for lift are the same, therefore you get the same results in these columns. Try to find another way to identify and distinguish between them. You can probably use an index, though if there's another way it's usually preferred.
score: 0
type: Answer

http://stackoverflow.com/a/52156595
answers question: http://stackoverflow.com/q/52156492
has body: Try this: import numpy as np def RVs(): #s = 0 s = 1 f = 0 while s!=0 or f==0: #will always run it the first time z = np.random.random() if z&lt;=0.5: x = -1 else: x = 1 s = s + x f = f + 1 return(f) RVs()
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/91482911
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52267106
has text: What do you mean by 'valid and related'?
score: 0

http://stackoverflow.com/comment/91263865
comment on: http://stackoverflow.com/q/52156423
score: 0
type: Comment
type: QuestionComment
has text: `pd.DataFrame` expects a list of lists or list of dictionaries. What you have is a nested list of dataframes. Trye `print(global_dict['abc'])` (not sure where `alc` comes from) if this isn't clear.

http://stackoverflow.com/comment/91482802
type: QuestionComment
comment on: http://stackoverflow.com/q/52211142
has text: Thanks @DanielRoseman for your help. I didn't quite understand what you were saying without example code, but my error was in the general area of what you mentioned. I added an update with code of what worked. I'm still not sure how to keep 2 separate urls.py files. Thanks again :)
score: 0
type: Comment

http://stackoverflow.com/q/52193985
has body: I created a model manager that should delete the entry. I always receive the error delete() takes 1 positional argument but 2 were given. Can anyone explain to me why I get this message? view.py ReservedItem.objects.delete(order_reference) models.py class ReservedItemManager(models.Manager): def delete(order_reference): super().get_queryset().filter(order_reference=order_reference).delete()
answer count: 1
has title: Django: ModelManager
has answer: http://stackoverflow.com/a/52194026
type: UnansweredQuestion
tagged with: django
tagged with: python
type: Question
score: 0

http://stackoverflow.com/comment/91317685
comment on: http://stackoverflow.com/q/52171155
has text: Because you have a dataset with known a,b,c values, would you please test that dataset on my posted nonlinear fitting code and report the results?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91219167
type: AnswerComment
has text: How do you use pip to install to a conda venv?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52134146

http://stackoverflow.com/a/52256033
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91523087
has comment: http://stackoverflow.com/comment/91628773
type: Answer
score: 2
downvote count: 0
has body: The problem lies in the order of arguments in your polyval. z is your array of linear fit coefficients and xx is the refined mesh for plotting the fit. You have used: z = np.polynomial.polynomial.polyfit(x,y,1) yy = np.polynomial.polynomial.polyval(xx, z) You should use: z = np.polyfit(x,y,1) yy = np.polyval(z, xx) For more details, refer to the official docs here.
accepted answer of: http://stackoverflow.com/q/52255824
answers question: http://stackoverflow.com/q/52255824
has comment: http://stackoverflow.com/comment/91527559
has comment: http://stackoverflow.com/comment/91481276
has comment: http://stackoverflow.com/comment/91493331
upvote count: 2

http://stackoverflow.com/q/52261106
score: 1
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/52259270
has answer: http://stackoverflow.com/a/52261215
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52261215
has title: pandas.series.apply with self bultt function doesn't work
tagged with: python
type: AnsweredQuestion
has body: I try to convert a series of strings to a series of mixed types, including strings and floats, with pandas.Series.apply function. However, it does't work. Can anyone give me a hint? import pandas as pd series_a = ['a', '2', 'b', '3'] def value_to_float(value): try: value = float(value) except: pass return value series_a.apply(value_to_float) series[1] Out[14]: '2'

http://stackoverflow.com/comment/91184982
score: 1
has text: Sounds like a perfect task for a cron job.
type: Comment
comment on: http://stackoverflow.com/q/52117056
type: QuestionComment

http://stackoverflow.com/a/52205163
has comment: http://stackoverflow.com/comment/91359620
has comment: http://stackoverflow.com/comment/91359528
answers question: http://stackoverflow.com/q/52205084
has body: This should help. with open(filename, 'r') as f: for line in f: #Iterate each line val = line.strip() #Strip leading and trailing space. if val.startswith('address'): #Check for value var1 = val print('address:', var1) if val.startswith('netmask'): var2 = val print('netmask:', var2) if val.startswith('gateway'): var3 = val print('gateway:', var3) if val.startswith('dns'): var4 = val print('dns:', var4) Output: ('address:', 'address 125.222.2222') ('netmask:', 'netmask 455.225.222.22') ('gateway:', 'gateway 236.256.222.22') ('dns:', 'dns-nameserver 123.256.223.22')
has comment: http://stackoverflow.com/comment/91360305
type: Answer
score: 0

http://stackoverflow.com/a/52160849
accepted answer of: http://stackoverflow.com/q/52160596
score: 5
type: AcceptedAnswer
has body: If you want to in python: nameList = [c for x in df.rdd.collect() for c in x['name']] or If you want to do it in spark: from pyspark.sql import functions as F df.withColumn('name', F.split(F.col('name'), '')).show() Result: +---+--------------+-----+----------+--------+ | id| name|class|start_data|end_date| +---+--------------+-----+----------+--------+ | 1|[j, o, h, n, ]| xii| 20170909|20210909| +---+--------------+-----+----------+--------+
upvote count: 5
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52160596

http://stackoverflow.com/q/52185656
type: Question
tagged with: qtablewidget
has title: PyQt5: why am I only able to use two colours for QTableWidget cells?
has answer: http://stackoverflow.com/a/52186668
score: 0
tagged with: pyqt
answer count: 1
accepted answer: http://stackoverflow.com/a/52186668
tagged with: python
type: AnsweredQuestion
has body: So I am trying to colour my QTableWidget QTableWidgetItems depending on the item.text(). This is my code: from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * import sys class Table(QTableWidget): def __init__(self, parent): super(Table, self).__init__(parent) self.setColumnCount(9) self.setRowCount(1) self.setItem(0, 0, QTableWidgetItem('A')) self.setItem(0, 1, QTableWidgetItem('B')) self.setItem(0, 2, QTableWidgetItem('C')) self.setItem(0, 3, QTableWidgetItem('D')) self.setItem(0, 4, QTableWidgetItem('E')) self.setItem(0, 5, QTableWidgetItem('F')) self.setItem(0, 6, QTableWidgetItem('A')) self.setItem(0, 7, QTableWidgetItem('C')) self.setItem(0, 8, QTableWidgetItem('D')) for r in range(self.rowCount()): for c in range(self.columnCount()): item = QTableWidgetItem() self.item(r, c).setBackground(self.colour(self.item(r, c).text())) def colour(self, letter): if letter == 'A': colour = QColor(233, 12, 24) if letter == 'B': colour = QColor(12, 45, 67) if letter in ['C', 'E']: colour = QColor(23, 57, 188) if letter == 'F': colour = QColor(45, 116, 75) else: colour = QColor(233, 244, 12) return colour def main(): app = QApplication(sys.argv) window = QWidget() window.setGeometry(200,200,1200,400) tw = Table(window) twLayout = QVBoxLayout() twLayout.addWidget(tw) window.setLayout(twLayout) window.show() sys.exit(app.exec_()) if __name__ == '__main__': main() When I run it, only two colours end up in my table, and the rest get ignored. How can I fix it and how can I make sure that each cell gets its individual colour based on its contents?
tagged with: pyqt5

http://stackoverflow.com/comment/91510414
has text: Okay so instead of inserting you want to replace the entire line as in `text:"",` will become `text:"some_text"`,? instead of adding to the already blank entry `"",` and that goes for all three variables you described
type: Comment
comment on: http://stackoverflow.com/a/52277979
score: 0
type: AnswerComment

http://stackoverflow.com/q/52150122
accepted answer: http://stackoverflow.com/a/52150925
upvote count: 2
has answer: http://stackoverflow.com/a/52150925
favorite count: 0
has title: Expand a python dictionary to express shared list values
has comment: http://stackoverflow.com/comment/91250655
possible better answer: http://stackoverflow.com/a/52150434
tagged with: python
has comment: http://stackoverflow.com/comment/91250409
tagged with: dictionary
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91250213
has comment: http://stackoverflow.com/comment/91250641
type: Question
has body: Let's say I have the following simple dictionary in Python3.x: example = {1:[4, 5, 6], 2:[7, 8, 9]} I would like a way to expand the dictionary as follows: expanded_example = {1:[4, 5, 6], 2:[7, 8, 9], 4:[5, 6], 5:[4, 6], 6:[4, 5], 7:[8, 9], 8:[7, 9], 9:[7, 8]} This becomes quite complicated by values shared by multiple keys. As an example, example2 = {1:[4, 5, 6], 2:[4, 7, 8, 9]} Here 4 is a value in the lists associated with 1 and 2. There are two approaches if there are "repeat" value elements: (1) Only keep values immediately associated with a certain key: {1:[4, 5, 6], 2:[4, 7, 8, 9], 4:[5, 6], 5:[4, 6], 6:[4, 5], 7:[8, 9], 8:[7, 9], 9:[7, 8]} (2) Keep all associated values (as '4' is shared between keys '1' and '2'): {1:[4, 5, 6], 2:[4, 7, 8, 9], 4:[5, 6, 7, 8, 9], 5:[4, 6], 6:[4, 5], 7:[4, 8, 9], 8:[4, 7, 9], 9:[4, 7, 8]} EDITED: My thought for this task was to use collections.defaultdict: from collections import defaultdict dict1 = {1:[4, 5, 6], 2:[4, 7, 8, 9]} d_dict = defaultdict(list) for k,l in dict1.items(): for v in l: d_dict[v].append(l) print(d_dict) ## defaultdict(&lt;class 'list'&gt;, {4: [[4, 5, 6], [4, 7, 8, 9]], 5: [[4, 5, 6]], 6: [[4, 5, 6]], 7: [[4, 7, 8, 9]], 8: [[4, 7, 8, 9]], 9: [[4, 7, 8, 9]]}) This gets me some of the way, but there are repeat elements in lists of lists...
answer count: 2
has answer: http://stackoverflow.com/a/52150434

http://stackoverflow.com/comment/91529974
score: 0
type: Comment
type: QuestionComment
has text: Could you please explain a bit more how it can be done? for example a small algorithm. The file necessarily doesn't have to be Geotiff, i can use any drone imagery, Geotiff is only an option. The point is to extract the GPS coordinates of the path I'm drawing on the file. I'll be using these coordinates for navigation of vehicles along same path.
comment on: http://stackoverflow.com/q/52219574

http://stackoverflow.com/comment/91445692
comment on: http://stackoverflow.com/q/52248806
type: QuestionComment
has text: When you are doing `number == primes` you are testing if your number is equal to the primes variable. When you want to do is to check if your number belong to the prime array. This is done with the `in` operator
type: Comment
score: 2

http://stackoverflow.com/comment/91192989
has text: Thanks, I think that link will help a lot. I want an obejct, that behaves like a dataframe and has private members, some of which are again dataframes (or subclasses of dataframe). Is this conceptually bad style?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52119158
score: 0

http://stackoverflow.com/comment/91296890
comment on: http://stackoverflow.com/q/52172532
type: Comment
type: QuestionComment
score: 1
has text: See [**`fileinput`**](https://docs.python.org/3/library/fileinput.html#fileinput.input) for in-place editing of files.

http://stackoverflow.com/comment/121600069
type: QuestionComment
has text: ***Your answer is here:*** https://stackoverflow.com/questions/47357090/tkinter-error-couldnt-recognize-data-in-image-file/68805933#68805933
comment on: http://stackoverflow.com/q/52175943
score: 0
type: Comment

http://stackoverflow.com/comment/91413400
comment on: http://stackoverflow.com/a/52226549
type: AnswerComment
has text: Why I cannot hide it completely...?
score: 0
type: Comment

subshell
tags question: http://stackoverflow.com/q/52254868
tag name: subshell
type: Tag

http://stackoverflow.com/comment/91804010
type: QuestionComment
type: Comment
has text: What web server are you using to host your python script? It sounds like you're just putting file://path/to/my/python_script.py in a web browser and expecting it to run. You need to have a server that can interpret python for it to actually run your code.
score: 0
comment on: http://stackoverflow.com/q/52227749

http://stackoverflow.com/q/52116906
type: AnsweredQuestion
has title: Python C API - How to assign a value to eval expression?
tagged with: http://stackoverflow.com/tag/c
has answer: http://stackoverflow.com/a/52128709
type: Question
score: 0
answer count: 2
has body: Is it possible to assign a value to an "eval expression" without manipulating the evaluation string? Example: The user writes the expression "globalPythonArray[10]" which would evaluate to the current value of item 10 of globalPythonArray. But the goal is, to set the value of item 10 to a new value instead of getting the old value. A dirty workaround would be, to define a temporary variable "newValue" and extend the evaluation string to "globalPythonArray[10] = newValue" and compile and evaluate that modified string. Are there some low level Python C API functions that I can use such that I don't have to manipulate the evaluation string?
tagged with: eval
accepted answer: http://stackoverflow.com/a/52128709
tagged with: python
has answer: http://stackoverflow.com/a/52117009
tagged with: python-c-api
possible better answer: http://stackoverflow.com/a/52117009

http://stackoverflow.com/a/52205976
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52205398
has body: Please see Mike Scotty for solution regarding os.system. If you use subprocess, please use a list of string for your command instead of a single string: subprocess.call(['explorer', '\\\\srv\\teams\\dir 1']) Note that I use subprocess.call instead of subprocess.Popen since this is a simple call, no need to overkill
accepted answer of: http://stackoverflow.com/q/52205398
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/52248532
has comment: http://stackoverflow.com/comment/91445096
has comment: http://stackoverflow.com/comment/91445157
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91445583
favorite count: 0
has comment: http://stackoverflow.com/comment/91445222
has comment: http://stackoverflow.com/comment/91445088
has comment: http://stackoverflow.com/comment/91445100
has comment: http://stackoverflow.com/comment/91445244
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52248664
tagged with: python
linked to: http://stackoverflow.com/q/13299427
tagged with: recursive-backtracking
score: -1
tagged with: recursion
has title: Changing a boolean value recursively in python
duplicate of: http://stackoverflow.com/q/13299427
downvote count: 1
type: Question
has body: For some context, this is the interview question I'm working on (taken from https://leetcode.com/problems/path-sum/description/). I now realize that its cleaner to just return a boolean value from each recursive function, but I still don't understand why this doesn't work: class Solution: def hasPathSum(self, root, sum): result = None self.recurse(result, root, root.val, sum) return result def recurse(self, result, node, sub_sum, target): if sub_sum &gt; target: return if sub_sum == target: result = True return if node.left: self.recurse(result, node.left, sub_sum+node.left.val, target) if node.right: self.recurse(result, node.right, sub_sum+node.right.val, target) The value being returned (regardless of the tree depth) is None. Why isn't this value being changed? Isn't it passed by reference?
has comment: http://stackoverflow.com/comment/91445249

http://stackoverflow.com/comment/91470154
has text: mail.SendUsingAccount = "hello5@abcd.com", tried this but it sends from madanraj.c@abcd.com only..
comment on: http://stackoverflow.com/a/52207308
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52123388
downvote count: 0
type: UnansweredQuestion
score: 6
type: Question
has answer: http://stackoverflow.com/a/52123640
tagged with: dataframe
tagged with: numpy
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/52123970
upvote count: 6
favorite count: 0
has title: Masking a pandas DataFrame with a numpy array vs DataFrame
tagged with: python
has body: I want to use a 2D boolean mask to selectively alter some cells in a pandas DataFrame. I noticed that I cannot use a numpy array (successfully) as the mask, but I can use a DataFrame. More frustrating, however, is that I don't get an error with the numpy approach. For example, df = pd.DataFrame({'A':[1,2,3,4], 'B':[10,20,30,40]}) mask_np = np.array([[True,True], [False,False], [True,False], [False,True]]) mask_pd = pd.DataFrame(mask_np, columns=['A','B']) I would think either mask would return the values from df wherever the mask was True. But instead, df[mask_np] produces A B 0 1 10 0 1 10 2 3 30 3 4 40 which is not what I expect, nor can I explain. On the other hand, df[mask_pd] produces A B 0 1.0 10.0 1 NaN NaN 2 3.0 NaN 3 NaN 40.0 which is what I expect and want. Why can't I use the numpy mask? My internet search turned up nothing relevant. Any explanation behind this difference would be greatly appreciated! [pandas version 0.20.3; Python 3.6.3]

http://stackoverflow.com/comment/91286775
type: QuestionComment
comment on: http://stackoverflow.com/q/52167706
type: Comment
has text: @Tobey, No I only wants user_id
score: 0

http://stackoverflow.com/comment/91469410
type: Comment
has text: @kww You were right, buddy !! Do edit your answer so that I can upvote it.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52231208

http://stackoverflow.com/a/52219617
downvote count: 0
has body: Assign 4 empty lists: col1List = list() col2List = list() col3List = list() col4List = list() First, let's get the column 4 values: trs = table.find_all('tr')[1] tds = trs.find_all('a') for i in range(len(tds)): col4List.append(tds[i].get_text()) This gives: ['Ballard Partners', 'Advanced Roofing Inc', 'Africell Holding',....] Now, let us extract the values for first 3 columns from href: hrefVal = trs.find_all('a') for i in hrefVal: hVal = i.get('href') col11 = hVal.split('.php?id=', 1) col1 = col11[0] col1List.append(col1) col22 = col11[1].split('&amp;', 1) col2 = col22[0] col2List.append(col2) col33 = col22[1].split('=', 1) col3 = col33[1] col3List.append(col3) Now, let us put all the lists in a dataframe to make it look neat: import pandas as pd df = pd.DataFrame() df['Col1'] = col1List df['Col2'] = col2List df['Col3'] = col3List df['Col4'] = col4List If I output the first few rows, it will look like how you want it: Col1 Col2 Col3 Col4 firmsum D000037635 2018 Ballard Partners clientsum F203227 2018 Advanced Roofing Inc clientsum F214670 2018 Africell Holding clientsum D000023883 2018 Amazon.com clientsum D000000192 2018 American Health Care Assn clientsum D000021839 2018 American Road &amp; Transport Builders Assn
type: Answer
has comment: http://stackoverflow.com/comment/91411861
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/52212754
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52212754

http://stackoverflow.com/comment/91328927
comment on: http://stackoverflow.com/q/52171610
has text: You should've corrected that. Everyone seems to think your code issues are indentation problems. Adding space before code is simply to make sure it formats properly on the site (4 spaces minimum).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91360332
type: AnswerComment
comment on: http://stackoverflow.com/a/52201937
score: 0
type: Comment
has text: Is there a way to change the values of the lower or x-axis in the figure? Can we give our own range for that?

http://stackoverflow.com/a/52249844
has body: Filter returns an array. If you use Drama.objects.filter(name='The Office')[0] your code will work
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91465836
has comment: http://stackoverflow.com/comment/91448221
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91448385
accepted answer of: http://stackoverflow.com/q/52249831
answers question: http://stackoverflow.com/q/52249831
has comment: http://stackoverflow.com/comment/91448511
has comment: http://stackoverflow.com/comment/91448389

http://stackoverflow.com/q/52194981
favorite count: 0
score: 6
accepted answer: http://stackoverflow.com/a/52196005
upvote count: 6
has title: Simplifying a matrix expression with a MatrixSymbol in Python
has comment: http://stackoverflow.com/comment/91339606
type: AnsweredQuestion
type: Question
tagged with: sympy
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52196005
tagged with: python
has body: I am using SymPy for symbolic matrix calculations, however, certain statements are very big. It seems there is a way to simplify them further. I have used simplify() but I have not been successful in getting what I want. For example the image below is a matrix, which has been obtained as result of execution of long list of previous matrix calculations. The output of series of matrix calculations, which requires further simplification The final statement has two additions and one matrix multiplication. I wonder if there is any way to also execute the matrix multiplication on the right so we can simply end up with 3 matrix summations? I understand this can be done by doing certain algebraic manipulations by hand but I am more interested in a command to execute, such that the command takes the whole statement as the input and does all the simplifications including any multiplications and additions and outputs what I need. This should all be done using sympy. In other words, if an addition or a multiplication can be done then I want it done and not being left undone. This is MCVE, which mimics my problem from sympy import * init_printing() J_22 = MatrixSymbol('J_22', 3, 3) COV_b=Matrix([[2,1,1],[1,2,1],[1,1,2]]) (COV_b+J_22)*COV_b The output of this code is However, I would like to have this as the output I understand that in this simple example I could simply fix the problem by the following code from sympy import * init_printing() J_22 = MatrixSymbol('J_22', 3, 3) COV_b=Matrix([[2,1,1],[1,2,1],[1,1,2]]) (COV_b*COV_b+J_22*COV_b) However, this is just a simple example, in the actual problem this cannot be seen before the output is generated. Hence, I would like to be able to use a command, which takes the output of the first provided code as input and outputs the desired output. UPDATE:@WelcometoStackOverflow provided a function, which simplifies things a lot but still leaves the matrix addition undone. from sympy import * init_printing() J_22 = MatrixSymbol('J_22', 3, …

http://stackoverflow.com/a/52434834
upvote count: 4
score: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52248925
answers question: http://stackoverflow.com/q/52248925
type: Answer
has body: Turns out my problem was due to testing not using the same context, so my solution is similar to what is described here and here. tests/test_a.py now looks like: from flask_login import current_user from my_app.tests.base import BaseTest class MyTests(BaseTest): def test_a(self): with self.app: print current_user Strangely, app.config['LOGIN_DISABLED'] = False and app.login_manager._login_disabled = False don't matter after this change - both can be removed.

color-depth
type: Tag
tag name: color-depth
tags question: http://stackoverflow.com/q/52249114

http://stackoverflow.com/comment/91441488
type: QuestionComment
type: Comment
has text: Check you mysql db name and client, as well as your Mysql installation on the server, they to run Django shell and see if you are able to import django.db.backends.mysql
comment on: http://stackoverflow.com/q/52246667
score: 0

http://stackoverflow.com/comment/91255468
type: QuestionComment
comment on: http://stackoverflow.com/q/52152482
has text: @VishalSingh: why? shouldn't he use an index??
score: 0
type: Comment

http://stackoverflow.com/comment/139764613
type: AnswerComment
comment on: http://stackoverflow.com/a/69095066
score: 0
type: Comment
has text: This will only connect to SSH, but use host python environments.

http://stackoverflow.com/q/52171013
has comment: http://stackoverflow.com/comment/91299950
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91293072
has comment: http://stackoverflow.com/comment/91293349
upvote count: 4
has comment: http://stackoverflow.com/comment/91293873
answer count: 2
tagged with: pandas
score: 3
has comment: http://stackoverflow.com/comment/91292654
has comment: http://stackoverflow.com/comment/91293208
favorite count: 0
has answer: http://stackoverflow.com/a/52175285
has comment: http://stackoverflow.com/comment/91293569
has comment: http://stackoverflow.com/comment/91293402
has answer: http://stackoverflow.com/a/52174275
has comment: http://stackoverflow.com/comment/91299126
tagged with: python
has comment: http://stackoverflow.com/comment/91293782
has comment: http://stackoverflow.com/comment/91293969
has comment: http://stackoverflow.com/comment/91293848
has body: Summary It's important in many scientific applications to keep track of different kinds of missing value. Is a value for 'weekly income from main job' missing because the person doesn't have a job, or because they have a job but refused to answer? Storing all missing values as NA or NaN loses this information. Storing missing value labels (e.g., 'missing because no job', 'missing because refused to answer') in a separate column means the researcher must keep track of two columns for every operation she performs – such as groupby, renaming, and so on. This creates endless opportunities for mistakes and errors. Storing missing value labels within the same column (e.g., as negative numbers, as in the example below, or very large numbers like 99999) means the researcher must manually keep track of how missing value labels are encoded for every column, and creates many other opportunities for mistakes (e.g., forgetting that a column includes missing values and taking a raw mean instead of using the correct mask). It is very easy to handle this problem in Stata (see below), by using a data type that stores both numeric values and missing value labels, and with functions that know how to handle this data type. This is highly performant (data type remains numeric, not string or mixed – think of NumPy's data types, except instead of having just NaN we have NaN1, NaN2, etc.) What is the best way of achieving something like this in pandas? Note: I'm an economist, but this is also an incredibly common workflow for political scientists, epidemiologists, etc. – anyone who deals with survey data. In this context, the analyst knows what the missing values are via a codebook, really cares about keeping track of them, and has hundreds or thousands of columns to deal with – so, indeed, needs an automated way of keeping track of them. Motivation/context It's extremely common when dealing with any kind of survey data to have multiple kinds of missing data. Here is a minimal example from…
has comment: http://stackoverflow.com/comment/91293377
has title: How to keep track of different types of missing values in pandas?
has comment: http://stackoverflow.com/comment/91293105
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91293122
has comment: http://stackoverflow.com/comment/91292931
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91299964
has comment: http://stackoverflow.com/comment/91293758
has comment: http://stackoverflow.com/comment/91293576

http://stackoverflow.com/comment/91262893
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52153966
has text: @Lucas Bazingaa's answer solved the problem, and you're right indeed, I needed to transpose my vectors (plus creating a meshgrid). Thank you for your help !
type: QuestionComment

http://stackoverflow.com/q/52251549
has comment: http://stackoverflow.com/comment/91450708
tagged with: wxpython
has body: My SwapImage function works perfectly in 5 areas of my script except for one part. When the 'CompileImages' is called it starts processing images. I want to toggle an image in the line before that call to the function, but it seems to lock up the interface immediately and doesnt toggle it. Is there a way to force it to run the toggle image function before it then moves on (and locks up)? #the button I’m using… genButton = wx.lib.buttons.GenButton(panel2, -1, label='Generate', pos=(8, 66), size=(136, 26)) genButton.Bind(wx.EVT_BUTTON, self.RunCompileFunction) #… calls this function def RunCompileFunction(self, event): self.SwapImage(image_fileprogress) self.CompileImages(self) #this SwapImage function works at every other point EXCEPT in the above function, it seems to skip over it as if it has more important things to do. #Curiously if I comment out the call to CompileImages function it DOES swap the image. def SwapImage(self, imagename): self.bitmap1 = wx.StaticBitmap(panel1, -1, imagename, (0, 0)) backgroundimage = imagename #This function just starts processing images and causes the interface lockup def CompileImages(self, event): if len(MyFrame.filenames) &gt; 8 and len(MyFrame.maskfiles) &lt;= 2: print("Ensure you've dropped your mask files too!") #myCursor = wx.StockCursor(wx.CURSOR_WAIT) #frame.SetCursor(myCursor) global coloralphareq global opacityalphareq # get first image size and save to variable getsize = Image.open(MyFrame.filenames[0]) mwidth, mheight = getsize.size # get its .extension format # imgformat = str(x)[-3:] # imgformat = (str(MyFrame.filenames[0].format)) # print(imgformat) # for each image in the list... for map in maptypes: # print(map) # files = any file with the current mapname in it files = [s for s in MyFrame.filenames if map in s] # print(files) if len(files) &gt; 0: map = map[:-1] # remove names that are clashing if map == "Normal": self.RemoveFiles(files, "Normal_OpenGL.") if map == "Normal_OpenGL": self.RemoveFiles(files, "Normal.…
has comment: http://stackoverflow.com/comment/91481783
has comment: http://stackoverflow.com/comment/91453268
score: 0
answer count: 0
tagged with: time
type: UnansweredQuestion
tagged with: interface
tagged with: python
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/91450677
has comment: http://stackoverflow.com/comment/91453334
has title: wxpython skips over a call to my function, and jumps directly to the next line. Why?
type: Question

http://stackoverflow.com/q/52155603
upvote count: 1
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/52155649
has answer: http://stackoverflow.com/a/52155769
has answer: http://stackoverflow.com/a/52155649
tagged with: arrays
has comment: http://stackoverflow.com/comment/91261466
has title: Python : What is a string array?
score: 0
answer count: 2
tagged with: string
favorite count: 0
accepted answer: http://stackoverflow.com/a/52155769
tagged with: python
has body: So I'm doing this coding challenge in Python and the problem says that the input is a string array. I downloaded a sample input, and the .txt file is like this: 13 Alice;START Bob;START Bob;1 Carson;START Alice;15 Carson;6 David;START David;24 Evil;START Evil;24 Evil;START Evil;18 Fiona;START Honestly, I don't know how to process that input to obtain individual rows from it as pairs of items, so I failed the challenge badly. However, I'm still interested in learning. I tried to process the input using split(";"). Any ideas how to parse this input?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91261407
has comment: http://stackoverflow.com/comment/91261467

http://stackoverflow.com/a/52208499
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52208453
type: Answer
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/52208453
has comment: http://stackoverflow.com/comment/91367724
has body: It brute-force counts the number of prime factors of n, each counted according to its multiplicity. t is the current factor being tested and n % t == 0 only if n is an integer multiple of t. If it's divisible, n is divided and the division is tried again (to account for the multiplicity of that factor); otherwise, the next integer is tried, up to (the original) n. Even if the division by non-primes is tried, it doesn't skew the result because all the lower primes have already been tried, so they won't ever succeed. An obvious optimization would be to compute and memoize the primes up to the number through an efficient algorithm, and just try them.

http://stackoverflow.com/a/52188478
accepted answer of: http://stackoverflow.com/q/52187913
has body: The vast majority of these models require color, i.e. 3-channel images; by converting to grayscale you end up with a single-channel image, and the code crashes. Let's have a quick look to confirm this; the script in the linked blog post is run as python deep_learning_object_detection.py \ --prototxt MobileNetSSD_deploy.prototxt.txt \ --model MobileNetSSD_deploy.caffemodel --image images/example_01.jpg Digging into the MobileNetSSD_deploy.prototxt.txt file of the MobileNet-SSD Github repo (i.e. the implementation used here), we see that the input layer is defined as name: "MobileNet-SSD" input: "data" input_shape { dim: 1 dim: 3 dim: 300 dim: 300 } The second dim argument here is exactly the number of channels expected in the image (3). And it will simply refuse to work for single-channel images, such as grayscale ones. A hack in similar cases, just to keep you playing along (although I have seen it routinely used in medical &amp; satellite imaging, where also the images are often not color ones), is just to replicate your single-channel into 3 identical ones, and combine them to form a "3-channel" image...
answers question: http://stackoverflow.com/q/52187913
has comment: http://stackoverflow.com/comment/91326918
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91326803
upvote count: 6
score: 6

http://stackoverflow.com/comment/91455336
type: Comment
comment on: http://stackoverflow.com/q/52250821
score: 0
type: QuestionComment
has text: @ashgetstazered I just added the dataset and the complete code.Thank you for helping me.

http://stackoverflow.com/a/52156339
score: 3
accepted answer of: http://stackoverflow.com/q/52155783
type: AcceptedAnswer
downvote count: 0
has body: import numpy as np from itertools import permutations n = 3 a = np.arange(n**2).reshape(n, n) for perm in permutations(range(a.shape[0])): b = np.zeros_like(a) b[:, :] = a[perm, :] b[:, :] = b[:, perm] print(b) gives the 6 following matrices: [[0 1 2] [3 4 5] [6 7 8]] [[0 2 1] [6 8 7] [3 5 4]] [[4 3 5] [1 0 2] [7 6 8]] [[4 5 3] [7 8 6] [1 2 0]] [[8 6 7] [2 0 1] [5 3 4]] [[8 7 6] [5 4 3] [2 1 0]] Is this the question?
type: Answer
answers question: http://stackoverflow.com/q/52155783
upvote count: 3

http://stackoverflow.com/comment/91373440
type: Comment
type: QuestionComment
has text: I don't get where DataFrame 4 is coming from when you have only provided 9 rows. Also, this doesn't seem like it's between `index` values, since it *includes* index values
score: 1
comment on: http://stackoverflow.com/q/52211898

http://stackoverflow.com/q/52260423
has answer: http://stackoverflow.com/a/52265613
has comment: http://stackoverflow.com/comment/91479186
type: UnansweredQuestion
tagged with: win32com
has body: when I use win32com to access outlook 2013, my outlook is significantly slow after I run the code. below is my code: outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case, # the inbox. You can change that number to reference # any other folder emails = outlook.GetDefaultFolder(6).Folders['xyz'].Folders['abc'].Items Sometimes I get com_error: (-2146959355, 'Server execution failed', None, None) running the code if outlook is opened beforehand. I would have to restart outlook and reset my python env to be back to normal. Is there any setting in outlook that I need to set or any special python operation I need to do after reading the email? Best regards, Jeremy
type: Question
tagged with: outlook
has comment: http://stackoverflow.com/comment/113557391
answer count: 1
has comment: http://stackoverflow.com/comment/91468587
score: 0
has comment: http://stackoverflow.com/comment/113557403
tagged with: python
has title: Outlook becomes slow after using python win32com package to read emails

http://stackoverflow.com/comment/91212783
type: QuestionComment
has text: Ah, I see. When you call `divide_and_conquer(0, 10)`, you are just creating a generator. Try `print(divide_and_conquer(0, 10))` to see what I mean. You are supposed to iterate through the results in order for something ti happen, so: `for result in divide_and_conquer(0, 10): print(result)` - of course, it does not generate any result, it just prints, which is wrong
comment on: http://stackoverflow.com/q/52131156
score: 0
type: Comment

http://stackoverflow.com/q/52267935
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52267993
duplicate of: http://stackoverflow.com/q/25004917
tagged with: python
has body: class Solution: def addNums(self, a, b): return a + b test1 = Solution() test1.addNums(5, 6) The above is my class! With a simple add method. Essentially, what I'm trying to do is, prepare for Algorithms and Data Structures/Programming Interviews, where I create instance for each input and want to write unit tests for instances.. Here is what I've tried below: import unittest class TestSolution(unittest.TestCase): def test_addNums(self): example = Solution() self.assertEqual(example.addNums(9, 10), 19) if __name__ == '__main__': unittest.main() Not sure how to go about doing this, if I run the above code, I get this error message: ---------------------------------------------------------------------- AttributeError: module '__main__' has no attribute '/Users/abhishekbabuji/Library/Jupyter/runtime/kernel-eb5f1d39-4880-49a7-9355-bbddc95464ff' ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (errors=1) An exception has occurred, use %tb to see the full traceback. SystemExit: True I want to be able to test return values of an instance method of a Solution class, in this case addNums(self, a, b)
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 1
accepted answer: http://stackoverflow.com/a/52267993
tagged with: unit-testing
type: Question
tagged with: oop
score: 1
tagged with: python-unittest
has title: Using Python's unittest module to test return values from instance methods of a class
linked to: http://stackoverflow.com/q/25004917

http://stackoverflow.com/a/52168999
type: Answer
has body: r.hincrby("list:123", "count", 1) Use this page for reference https://redis.io/commands/hincrby
accepted answer of: http://stackoverflow.com/q/52168852
answers question: http://stackoverflow.com/q/52168852
score: -2
type: AcceptedAnswer
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/107369494

http://stackoverflow.com/q/52180175
has comment: http://stackoverflow.com/comment/91314192
upvote count: 3
type: UnansweredQuestion
score: 3
has body: I am automating an Aspen Plus simulation through its ActiveX client. My code looks as follow: import win32com.client as win32 aspen = win32.Dispatch('Apwn.Document') # Stuff to initialize, mapping inputs and run simulation aspen.Save() aspen.Quit() del aspen aspen = None But the process is not killed, still appears in the task manager window. I tried tu use EnsureDispatch(), pythoncom.CoInitialize() and to kill it with subprocess module. Nothing works. When I force to kill it through cmd: taskkill /im AspenPlus.exe /f I get the following error message: ERROR: The process "AspenPlus.exe" could not be terminated with PID 1100. Reason: There is no active instance of the task. The issue is that I want these automation to solve an optimization problem, which means I have to run the simulation several times in a loop and it will amalgamate these "instanceless" processes. Each one takes 117 MB of memory so it will collapse. Any solution to really kill the process inside my Python code? Thanks in avance!
tagged with: win32com
has comment: http://stackoverflow.com/comment/91310893
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/91313135
favorite count: 0
has title: Unable to kill a process started by win32com.client
has comment: http://stackoverflow.com/comment/91311606
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91312807
has comment: http://stackoverflow.com/comment/91310723
answer count: 0

http://stackoverflow.com/q/52189783
answer count: 1
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52190317
tagged with: python
tagged with: regex
upvote count: 6
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/753052
score: 6
tagged with: web-scraping
has title: Get a clean string from HTML, CSS and JavaScript
type: Question
has answer: http://stackoverflow.com/a/52190317
linked to: http://stackoverflow.com/q/3073881
has body: Currently, I'm trying to scrape 10-K submission text files on sec.gov. Here's an example text file: https://www.sec.gov/Archives/edgar/data/320193/000119312515356351/0001193125-15-356351.txt The text document contains things like HTML tags, CSS styles, and JavaScript. Ideally, I'd like to scrape only the content after removing all the tags and styling. First, I tried the obvious get_text() method from BeautifulSoup. That didn't work out. Then I tried using regex to remove everything between &lt; and >. Unfortunately, also this didn't work out entirely. It keeps some tags, styles, and scripts. Does anyone have a clean solution for me to accomplish my goal? Here is my code so far: import requests import re url = 'https://www.sec.gov/Archives/edgar/data/320193/000119312515356351/0001193125-15-356351.txt' response = requests.get(url) text = re.sub('&lt;.*?&gt;', '', response.text) print(text)
downvote count: 0

http://stackoverflow.com/comment/91370465
comment on: http://stackoverflow.com/q/52113158
has text: Yes, text is better than pictures — it's copy/paste-able and searchable. There are a lot of tips at https://stackoverflow.com/help/asking and anti-tips at http://idownvotedbecau.se/
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91618726
comment on: http://stackoverflow.com/q/52225735
type: Comment
type: QuestionComment
has text: Did you see [my answer](https://stackoverflow.com/a/52316209/3832970)? I think it fully answers your question.
score: 0

http://stackoverflow.com/comment/91372969
has text: @user3483203 I did it
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52211715
score: 0

http://stackoverflow.com/comment/91329495
comment on: http://stackoverflow.com/a/52189337
type: AnswerComment
type: Comment
has text: Are you sure it works @Sanjeevkumar? I am getting error when I run your code.
score: 0

http://stackoverflow.com/comment/91473020
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52258202
type: Comment
has text: https://en.wikipedia.org/wiki/Cross_product#Generalizations talks about generalization of the cross product (as implemented by `np.cross`) to higher dimensions. But that's getting into more advanced mathematics, with things like quaternions and exterior products.

http://stackoverflow.com/q/52214458
has body: I am trying to build a dash app in Python to simulate a Q-Learning problem. Before implementing the algorithm I am just focusing on making the table work incrementing randomly the values and waiting 1 sec between each increment. Q is a pandas dataframe here: table = ff.create_table(Q, height_constant=20) table.layout.width=300 def update_Q(Q): for i in range(len(Q)): for j in range(1, len(Q.columns)): Q.iloc[i,j] += np.random.choice([0,1,2]) print(Q) return Q I am able to make it work with that print statement, the value of the table on the console is indeed getting updated. However, in the browser it just get updated the first time, but then it remains static. Here is the code: # Browser visualization app.layout = html.Div([ html.H1(children='Frozen Lake: Q-Learning Demo'), dcc.Graph(id='table', figure=table), dcc.Interval( id='time', interval=1*1000, # in milliseconds n_intervals=0) ] ) @app.callback(Output(component_id = 'table', component_property='figure'), [Input(component_id = 'time', component_property='n_intervals')]) def update_table(n): # Update values new_table = ff.create_table(update_Q(Q)) time.sleep(1) return new_table if __name__ == '__main__': app.run_server() What am I missing?
tagged with: plotly
has title: Updating table values live with Dash and Plotly
type: Question
tagged with: q-learning
tagged with: plotly-dash
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/96987477
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/97318893
score: 3
has answer: http://stackoverflow.com/a/55295358
downvote count: 0

http://stackoverflow.com/q/52145493
tagged with: loops
has body: I am new to coding and i wanted to make a code that could register people and log them back in. while working on my code i wanted to check if the user wanted to login or register so i made this code in python. login_or_register = None while login_or_register != 'login' or login_or_register != 'register': login_register = input('Would you like to login or register?') login_or_register = login_register.lower() login_or_register = login_register While loop doesn't stop even if variable meets the conditions. I tried to remove the second condition and it started to work for some reason. This is probably a dumb question but please be patient I'm a high school student. Would you like to login or register?login Would you like to login or register?register Would you like to login or register?keeps going :( Would you like to login or register? It is suppose to stop the loop when input is login or register. Output is suppose to be changing variable login_or_register = None to the answer.
type: Question
answer count: 2
has title: While loop doesn't stop with multiple conditions
accepted answer: http://stackoverflow.com/a/52145562
tagged with: while-loop
linked to: http://stackoverflow.com/q/6115801
downvote count: 0
score: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/6115801
upvote count: 1
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52145557
has answer: http://stackoverflow.com/a/52145562
has answer: http://stackoverflow.com/a/52145557
has comment: http://stackoverflow.com/comment/91240716

http://stackoverflow.com/q/52126139
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52126175
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91202932
favorite count: 0
has title: how to get desired row and with column names in pandas dataframe?
has answer: http://stackoverflow.com/a/52126175
score: -3
tagged with: python
downvote count: 4
type: AnsweredQuestion
has body: following is a preview of a marketing dataframe. Complete the code to get desired output id views clicks a 1 1000 300 b 2 1200 800 c 3 800 200 output views clicks a 1000 300 what should i change in my code to get this output import pandas as pd market=pd.read_csv("marketing.csv") print(market.iloc[0])
duplicate of: http://stackoverflow.com/q/11285613
type: Question
linked to: http://stackoverflow.com/q/11285613
has comment: http://stackoverflow.com/comment/91203368
has comment: http://stackoverflow.com/comment/91202993

http://stackoverflow.com/comment/91287562
score: 0
type: AnswerComment
has text: More precisely, you need the package azure-mgmt-subscription. See this test: https://github.com/Azure/azure-sdk-for-python/blob/41e37c8a10876db40697a63e828ed7cafc19c7d6/azure-mgmt-subscription/tests/test_mgmt_subscription.py
type: Comment
comment on: http://stackoverflow.com/a/52161369

http://stackoverflow.com/q/52125795
type: Question
has body: I'm writing a program to parse webpages to snatch the title and headers so I can give SEO consultation without manually clicking through all the code. The code works, but only returns a single instance of each tag I'm looking for. If there are, say, 5 h1's in the HTML, I only get the first one. How do I get the rest? I'm thinking a loop but I'm not sure how to go about it. Here's the code: # import libraries from urllib.request import urlopen from bs4 import BeautifulSoup #specify URL quote_page = input('What URL would you like to scrape?') #query website and return HTML to the variable page page = urlopen(quote_page) #parse the HTML with BeautifulSoup and store in variable 'soup' soup = BeautifulSoup(page, 'html.parser') #now we have the HTML as soup, so we need to grab the title and headers title = soup.find('title') h1s = soup.find('h1') h2s = soup.find('h2') h3s = soup.find('h3') metadescription = soup.find('meta name="description"') #print out the data in readable format, including "none" for missing data #types print() print('Title:') print(title) print() print('H1s:') print(h1s) print() print('H2s:') print(h2s) print() print('H3s:') print(h3s) print() print('Description:') print(metadescription)
has title: Parsing HTML with URLlib - How to print more than 1 of each tag?
score: 0
has answer: http://stackoverflow.com/a/52125804
tagged with: http://stackoverflow.com/tag/html
answer count: 1
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python

http://stackoverflow.com/comment/91296826
type: AnswerComment
has text: Hmm, weird, at least I cannot reference an index level with `df[idx]`... Throws a key error, yet you reference index levels in the code above. For the second question: I purposely tried to simplify the original question to maybe get a general solution, but I do have four index levels, only the innermost of which has to have this alternating 0,1,0,1 pattern. So I'd like to preserve the outer index levels, only expanding the one level. And one of the levels carries just auxiliary information about the row in question. So if I were to do a cartesian product, I'd get way more than is wanted.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52136104

http://stackoverflow.com/q/52258378
has answer: http://stackoverflow.com/a/56295474
tagged with: gdb
has title: gdb debugging python (3) process on alpine linux, can't use py-list
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91468419
tagged with: python-3.x
has body: well a python server process is currently crashing regularly (every few days), going high in cpu usage yet not actively processing anything. The process runs in an alpine linux docker. To help finding the problem I'd like to see the exact line on which the process is busy. As the process is already running I believe my only option is to use the generic gdb debugger. Now I tried following this small guide, "adapted" for alpine linux: I noticed gdb was already installed, and the python3 debug symbols are in this package: python3-dbg . Now if I run (after obviously cding to the virtual environment from thwich python is run). gdb python3 -p 135 (where 135 is the python background process in the docker). In the spawned gdb process I tried to list the current python line being executed: py-list. However this returns "undefined command: py-list". Similar for the stack trace: py-bt, also this command is not found. Can I fix this? When I use the more basic bt command I see: #0 0x00007fe3dd7e0c3d in epoll_pwait () from /lib/ld-musl-x86_64.so.1 #1 0x00007fe3dc90c3a0 in signals () from /njs/BackgroundServer/venv/lib/python3.6/site-packages/gevent/libev/corecext.cpython-36m-x86_64-linux-gnu.so #2 0x00007fe3dc90c490 in default_loop_struct () from /njs/BackgroundServer/venv/lib/python3.6/site-packages/gevent/libev/corecext.cpython-36m-x86_64-linux-gnu.so #3 0x00007fe3dc6e57a1 in epoll_poll (loop=0xe95f, timeout=&lt;optimized out&gt;) at /tmp/pip-install-o4b63_go/gevent/deps/libev/ev_epoll.c:153 #4 0x00007fe3dc6eda5c in ev_run (loop=0x7fe3dc90c3a0 &lt;default_loop_struct&gt;, flags=flags@entry=0) at /tmp/pip-install-o4b63_go/gevent/deps/libev/ev.c:3683 #5 0x00007fe3dc6ede88 in __pyx_pf_6gevent_5libev_8corecext_4loop_14run (__pyx_v_self=0x7fe3d8e86840, __pyx_v_once=&lt;optimized out&gt;, __pyx_v_nowait=&lt;optimized out&gt;) at src/gevent/libev/gevent.corecext.c:5575 #6 __pyx_pw_6gevent_5libev_8corecext_4loop_15run (__pyx_v_self=0x7fe3d8e86840, __pyx_args=&lt;optimized out&gt;, __py…
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91466201
score: 1
linked to: http://stackoverflow.com/q/14885328
tagged with: alpine-linux
upvote count: 1
tagged with: gevent
type: Question
has comment: http://stackoverflow.com/comment/91464572

http://stackoverflow.com/q/52250174
has title: I can´t pass the arguments error: unrecognized arguments: Argparse Python3
tagged with: argparse
has comment: http://stackoverflow.com/comment/91448435
has answer: http://stackoverflow.com/a/52250350
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91448935
has answer: http://stackoverflow.com/a/52250220
accepted answer: http://stackoverflow.com/a/52250350
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52250220
upvote count: 5
type: Question
answer count: 2
score: 5
downvote count: 0
has body: I'm using python 3.6 and I'm trying to do a program that requires arguments, but I can not use it because I can't pass the arguments. Another question: I can't understand the dest parameter; is it to create a variable with that name? #!/usr/bin/env python3 import argparse import subprocess parser = argparse.ArgumentParser() parser.add_argument('-m', '--mac', help='Introduce your new MAC' + 'use random as value if you want to have a random mac', action="store_true", required=True) parser.add_argument('-i', '--interface', help='The interface that the MAC will be changed', action="store", required=True) args = parser.parse_args() print(args.mac + args.interface) I´m getting this error, when trying to use it (I use hi and bye as examples) &gt; python '.\test.py' -m hi -i bye usage: test.py [-h] -m -i INTERFACE test.py: error: unrecognized arguments: hi
favorite count: 0

http://stackoverflow.com/comment/132258991
type: Comment
has text: To elaborate, I don't use colab *because of this flaw*--I don't want to have to use flaky and special-purpose `drive.mount` code to access data files, save outputs and figures, etc. I consider their implementation of Jupyter broken because it creates this need for special-casing.
score: 3
comment on: http://stackoverflow.com/a/52119628
type: AnswerComment

http://stackoverflow.com/a/52237068
has body: You can use plt.tight_layout() after plotting all the figures. This avoids manually playing around with the spacing.
accepted answer of: http://stackoverflow.com/q/52236996
type: Answer
upvote count: 15
answers question: http://stackoverflow.com/q/52236996
downvote count: 0
has comment: http://stackoverflow.com/comment/127652111
score: 15
type: AcceptedAnswer

http://stackoverflow.com/q/52114484
has answer: http://stackoverflow.com/a/52121904
tagged with: pyqt
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/52121904
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: pyqt5
type: Question
has title: Hyperlink not opening with ShellExecute failed (error 2)
has body: I have an application developed using PYQT5, in this application I have a row in a QtableWidget with a QLabel hyperlink to a report. The report is saved locally, though in future this may be located in a network share. For the sake of this question, say I have a report on my local drive at this location: C:\my\report\location\report.html However when I click the link to open the report in a web browser I get an error in the console window saying: ShellExecute 'c:%5Cmy%5Creport%5Clocation%5Creport.html' failed (error 2). Obviously the script has issues with the '\' backslash property, but I am unable to find a way to prevent this. Here's my pyqt based code to generate the hyperlink in the QTableWidget: reportLink = " Report "\ .format(url=outcome_dict['report_location']) report_lbl = QtWidgets.QLabel() report_lbl.setText(reportLink) report_lbl.setOpenExternalLinks(True) self.ui.my_table.setCellWidget(self.row, 6, report_lbl) And here's my code snippet when the user clicks the report hyperlink in the QTableWidget: def html_clicked(self, mi): self.column = mi.column() if self.column == 6: try: for ref in self.ui.my_table.selectedIndexes(): self.link = self.ui.my_table.item(int(ref.row()), 6).text() webbrowser.open(self.link) except Exception as e: print(e) else: pass

http://stackoverflow.com/comment/91226747
has text: Welcome to stackoverflow, @NLynn. I trust you found the answer to your problem in the linked "duplicate" question. For the future, know that it makes a better impression if you make the effort to identify the *programming* task in your homework assignment (in this case: How to make multiple sequential string substitutions), and formulate your question around that. Brand names have nothing to do with the programming question here, but searching for "python multiple string substitutions" would have brought you to the solution and saved you the trouble of writing this question.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52133630
score: 0

http://stackoverflow.com/q/52139809
tagged with: discord
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91232148
tagged with: python
has title: Discord Python API wrapper "Send_message" not doing anything?
has comment: http://stackoverflow.com/comment/91231436
linked to: http://stackoverflow.com/q/37512182
type: Question
tagged with: discord.py
has comment: http://stackoverflow.com/comment/91230034
score: 0
has body: So, I made some code that takes events from a google calendar and organizes them then posts them on discord. The main problem is this: client.send_message(client.get_channel('483988804370169857'),"None") When using this code in a @client.event it works fine, the problem begins when i put it in a normal function. I need it in a normal function so that it runs once every 24 hours. No errors, no nothing. The code just goes through the function and doesn't send the message. How can I fix this? from __future__ import print_function import json import datetime import discord from discord.ext import commands from datetime import timedelta import gspread from googleapiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools from discord.ext import commands import threading SCOPES = 'https://www.googleapis.com/auth/calendar.readonly' client = discord.Client() def Hw(): print("HW") now = datetime.datetime.now() run_at = now + timedelta(hours=3) delay = (run_at - now).total_seconds() #Begin Google Calander API store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store) service = build('calendar', 'v3', http=creds.authorize(Http())) now = datetime.datetime.utcnow().isoformat() + 'Z' #Retrieve all Events events_result = service.events().list(calendarId='CENSORED', timeMin=now,maxResults=250, singleEvents=True,orderBy='startTime').execute() events = events_result.get('items', []) #Currentmode stores if searching for tommorow, the week, or other (1,2,3) Currentmode = 0 UMode=1 none = True #Gets end of week dt = datetime.datetime.now() startweek = dt - timedelta(days=dt.weekday()) endweek = startweek + timedelta(days=6) dtstring = str(dt.date()) TheMessages = "**" + dtstring + " Report**" client.send_message(client.get_channel('483988804370169857'),TheMessages) if not events: client.send_message(client.get_channe…
has comment: http://stackoverflow.com/comment/91229363

http://stackoverflow.com/comment/91357941
comment on: http://stackoverflow.com/q/52202847
type: Comment
type: QuestionComment
has text: Where do you get to see what?
score: 0

http://stackoverflow.com/a/52210642
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52210222
has body: Your image2 does in fact appearing in front of your image1. But only for a split second. Immediately after you update the display, you go back to the start of the while loop, which immediately blits another copy of image1 in front of image2. If you wanted these to alternate back and forth every half second, you just need to add another sleep at the end of the loop. If you wanted it to just draw image1, wait, draw image2, and be done with it, just get rid of the while loop.

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/52239610
tag name: countvectorizer

http://stackoverflow.com/comment/91430849
has text: Please clarify what the correct resulting transformation should be for the two samples.
score: 0
comment on: http://stackoverflow.com/q/52241117
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52230276
score: 1
has title: Python check if number is already in list which is a value inside of a dictionary and if it is regenerate until it is different - syntax error
has answer: http://stackoverflow.com/a/52234082
has answer: http://stackoverflow.com/a/52230515
accepted answer: http://stackoverflow.com/a/52230515
type: Question
answer count: 2
tagged with: if-statement
downvote count: 0
has body: I am trying to generate unique coordinates for ships in a battleships game. I tried a lot of things but either I get a syntax error or a out of range. I realised that: my_dict = {key : [1, 2, 3], key2 : [4, 5, 6]} x = 2 print(mydict['key'][x - 1]) Will not give me no1 index. My code snippet is here: EDIT: Added missing things. from random import * board = [] for x in range(0, 10): board.append(["O"] * 10) ships = { 'shiprows': [0], 'shipcols' : [0] } def random_row1(board): return randint(0, len(board) - 1) def random_col1(board): return randint(0, len(board) - 1) vars = 0 temp = 0 for vars in range(0, 5): print(vars) if len(ships['shiprows']) &gt;= 2 and len(ships['shipcols']) &gt;= 2: temp = vars - 1 if ships['shiprows'][temp] in ships['shiprows'] and ships['shipcols'[temp] in ships['shipcols']: print("if loop") ships['shiprows'].append(random_row1(board)) ships['shipcols'].append(random_col1(board)) else: ships['shiprows'].append(random_row1(board)) ships['shipcols'].append(random_col1(board)) vars = vars + 1 print(ships) The code is just in debugging state - I am trying to get the numbers to go into said dodgy if loop and be re-generated until they are unique to their lists. I am a beginner, so if I have made an obvious slip up please don't judge. Thanks
has comment: http://stackoverflow.com/comment/91410304
possible better answer: http://stackoverflow.com/a/52234082
favorite count: 0
has comment: http://stackoverflow.com/comment/91410326
upvote count: 1
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/91345562
type: Comment
has text: the input tensor of t3 must be (1, ) we should transform t3 (or ind) to a specific shape which can help align reduce the dimension
comment on: http://stackoverflow.com/q/52197741
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91314410
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52181991
has text: dont use str, path_exists will be True or False depending upon the existence of path or not. open('uploads', 'r', newline=''), here you are trying to open the whole directory "uploads", please provide filename too, in this directory.
type: AnswerComment

http://stackoverflow.com/q/52137431
tagged with: python
has comment: http://stackoverflow.com/comment/91224527
type: AnsweredQuestion
tagged with: algorithm
has title: Strassen's Algorithm bug in python implementation
tagged with: matrix-multiplication
type: Question
tagged with: strassen
has body: I am getting different outputs of matrix multiplication by Strassen's Algorithm and the naive nested for loop implementation in Python 3. Code: def new_matrix(r, c): """Create a new matrix filled with zeros.""" matrix = [[0 for row in range(r)] for col in range(c)] return matrix def direct_multiply(x, y): if len(x[0]) != len(y): return "Multiplication is not possible!" else: p_matrix = new_matrix(len(x), len(y[0])) for i in range(len(x)): for j in range(len(y[0])): for k in range(len(y)): p_matrix[i][j] += x[i][k] * y[k][i] return p_matrix def split(matrix): """Split matrix into quarters.""" a = b = c = d = matrix while len(a) > len(matrix)/2: a = a[:len(a)//2] b = b[:len(b)//2] c = c[len(c)//2:] d = d[len(d)//2:] while len(a[0]) > len(matrix[0])//2: for i in range(len(a[0])//2): a[i] = a[i][:len(a[i])//2] b[i] = b[i][len(b[i])//2:] c[i] = c[i][:len(c[i])//2] d[i] = d[i][len(d[i])//2:] return a, b, c, d def add_matrix(a, b): if type(a) == int: d = a + b else: d = [] for i in range(len(a)): c = [] for j in range(len(a[0])): c.append(a[i][j] + b[i][j]) d.append(c) return d def subtract_matrix(a, b): if type(a) == int: d = a - b else: d = [] for i in range(len(a)): c = [] for j in range(len(a[0])): c.append(a[i][j] - b[i][j]) d.append(c) return d def strassen(x, y, n): # base case: 1x1 matrix if n == 1: z = [[0]] z[0][0] = x[0][0] * y[0][0] return z else: # split matrices into quarters a, b, c, d = split(x) e, f, g, h = split(y) # p1 = a*(f-h) p1 = strassen(a, subtract_matrix(f, h), n/2) # p2 = (a+b)*h p2 = strassen(add_matrix(a, b), h, n/2) # p3 = (c+d)*e p3 = strassen(add_matrix(c, d), e, n/2) # p4 = d*(g-e) p4 = strassen(d, subtract_matrix(g, e), n/2) # p5 = (a+d)*(e+h) p5 = strassen(add_matrix(a, d), add_matrix(e, h), n/2) # p6 = (b-d)*(g+h) p6 = strassen(subtract_matrix(b, d), add_matrix(g, h), n/2) # p7 = (a-c)*(e+f) p7 = strassen(subtract_matrix(a, c), add_matrix(e, f), n/2) z11 = add_matrix(subtract_matrix(add_matrix(p5, p4), p2), p6) z12 = add_matrix(p1, p2) z…
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52137465
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52137465
has comment: http://stackoverflow.com/comment/91224520

http://stackoverflow.com/q/52136460
upvote count: 2
has comment: http://stackoverflow.com/comment/91222774
has body: Trying to compute a power of a long integer in Python 3.6.5, and I am getting 0. Is it the expected behavior? Then it contradicts the official docs. In [16]: i Out[16]: 16777216 In [17]: i**2 Out[17]: 0 In [18]: float(i)**2 Out[18]: 281474976710656.0
has answer: http://stackoverflow.com/a/52145761
type: Question
has answer: http://stackoverflow.com/a/52137010
downvote count: 5
has comment: http://stackoverflow.com/comment/91222700
has answer: http://stackoverflow.com/a/52137151
answer count: 3
has comment: http://stackoverflow.com/comment/91222591
favorite count: 0
has comment: http://stackoverflow.com/comment/91223256
has comment: http://stackoverflow.com/comment/91222711
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91222807
score: -3
has comment: http://stackoverflow.com/comment/91241229
tagged with: python
has comment: http://stackoverflow.com/comment/91222646
has comment: http://stackoverflow.com/comment/91222627
has title: Power over integer in python 3

http://stackoverflow.com/a/52187321
upvote count: 1
score: 1
has body: note in the documentation you quoted: multiple raw reads may be issued to satisfy the byte count Which means that this loop is useless. The raw read is the read performed by the OS, using read(), which can return less than requested on some input streams. while amount_read &lt; amount: data += file_obj.read(chk_size) (plus the loop isn't updating amount_read so I suspect that it has a bug) Since you're using python file interface (not os.read), python is going to do that internally, with possible errors in the process, if one or many of the internal raw read required to complete the operation fails. You don't control the inside read, so you just need to do: data = file_obj.read(amount) If you don't want to use pyhton interface, then go for os.read with full controls and raw error checking that you'll have to manage.
answers question: http://stackoverflow.com/q/52187121
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52187121

top-n
type: Tag
tags question: http://stackoverflow.com/q/52244850
tags question: http://stackoverflow.com/q/52147871
tag name: top-n

http://stackoverflow.com/q/52133866
has body: I am running into problems using beautifulsoup to strip the html out and only have the text. When I run it I get the error AttributeError: ResultSet object has no attribute 'get_text'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()? Is there anyway to just get the text when I findAll in my divs variable like I have it? My code: import requests from bs4 import BeautifulSoup url = 'https://www.brightscope.com/form-5500/basic-info/107299/Orthopedic-Institute-Of-Pennsylvania/15801790/Orthopedic-Institute-Of-Pennsylvania-401k-Profit-Sharing-Plan/' page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') divs = soup.findAll('span', class_='float-right').get_text() for each in divs: print(each)
favorite count: 0
tagged with: beautifulsoup
tagged with: python
accepted answer: http://stackoverflow.com/a/52133885
downvote count: 0
has title: Using beautifulsoup to get the text.
has answer: http://stackoverflow.com/a/52133885
type: AnsweredQuestion
score: 1
type: Question
upvote count: 1
answer count: 1

http://stackoverflow.com/q/52185760
duplicate of: http://stackoverflow.com/q/35491274
tagged with: python-3.x
has title: Pandas - Convert one column which is having list to different Dataframe
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I have a dataframe having col2's value being list like d = {'col1': [1, 2], 'col2': [['a','b','c'],['d','e','f']]} df = pd.DataFrame(d) df col1 col2 0 1 [a, b, c] 1 2 [d, e, f] I want to convert col2 to a new dataframe I was able to do like this... Dataframe = pd.DataFrame() for i in range(0,df3.shape[0]): dff = pd.DataFrame(df3.col2[i]).T Dataframe = Dataframe.append(dff) Dataframe . 0 1 2 0 a b c 0 d e f But wondering is there any better way/any Function to convert that column to a new datafarme.?
type: Question
has comment: http://stackoverflow.com/comment/91321205
has comment: http://stackoverflow.com/comment/91321224
linked to: http://stackoverflow.com/q/35491274
score: 0
tagged with: pandas

http://stackoverflow.com/comment/91386821
score: 0
type: Comment
type: QuestionComment
has text: `'_'.join(game_data_directory.split('/')[-1].split('_')[1:])`
comment on: http://stackoverflow.com/q/52215651

http://stackoverflow.com/comment/91449850
has text: Before `diffadd = cv2.subtract(Edited2, Original2)` line try: `print Edited2.shape, Edited2.dtype` and `print Original2.shape, Original2.dtype`, to confirm if both the images have same shape and data type.
type: QuestionComment
comment on: http://stackoverflow.com/q/52247440
type: Comment
score: 0

http://stackoverflow.com/comment/91233094
comment on: http://stackoverflow.com/a/52141172
has text: Also; I'm not sure if this is relevant, but how would this apply for PyPy or IronPython, to name a few? Python code is the same, but the `dict` implementation would not.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52145195
tagged with: scope
score: 0
tagged with: python
has body: Suppose you have a decorator function that creates a dict to store already calculated results for performance reasons. E.g.: def memoize(func): cache = dict() def memoized_func(*args, **kwargs): if args in cache: return cache[args] result = func(*args) cache[args] = result return result return memoized_func When I decorate a function with myfunc = memoize(myfunc), I have a hard time understanding why this works. I have initially thought that cache would get lost after returning the memoized function, as it goes out of scope. I would only return a reference to the decorated function. Obviously, this is not the case. Can somebody tell me what is going on behind the scenes?
tagged with: python-decorators
tagged with: python-3.x
has title: Why do these decorator variables not get destroyed?
has comment: http://stackoverflow.com/comment/91240126
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/91240114
duplicate of: http://stackoverflow.com/q/2796855
answer count: 1
has answer: http://stackoverflow.com/a/52145357
tagged with: decorator

http://stackoverflow.com/comment/91230106
comment on: http://stackoverflow.com/a/52139704
has text: I just realized that some of my dictionary keys have 2 characters rather than 3. Is it still possible to do the same thing, but just say 'startswith', so that there is no defined character limit.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91389093
type: Comment
score: 1
has text: Done! Thanks again!
comment on: http://stackoverflow.com/a/52217699
type: AnswerComment

http://stackoverflow.com/q/52121740
type: Question
tagged with: discord.py
accepted answer: http://stackoverflow.com/a/52121782
score: 0
upvote count: 1
has answer: http://stackoverflow.com/a/52121782
has comment: http://stackoverflow.com/comment/91194808
answer count: 1
downvote count: 1
has title: How to respond to wrong user command in discord.py
favorite count: 0
tagged with: python
has body: If user types /foo and that command does not exist, how do I send the message saying "This command does not exist"? This is maybe pretty simple but I'm bit confused. If you need more info please comment. Thanks!
type: AnsweredQuestion

http://stackoverflow.com/q/52230074
upvote count: 2
has comment: http://stackoverflow.com/comment/91410529
answer count: 3
possible better answer: http://stackoverflow.com/a/52230310
downvote count: 1
has answer: http://stackoverflow.com/a/52230645
has body: I already published similar question but this is a DIFFERENT question. I am trying to generate combinations of a 5-character strings consisting of three letters (exactly two are equal and another different letter) and two different digits but I got duplication when I tried to do so. Example for CORRECT combinations: 82ccb b8cc7 7c6dc Example for INCORRECT combinations: 22ddc -&gt; incorrect because the digits are equal and should be different 46ddd -&gt; incorrect because there are more than 2 equal letters 2t4cd -&gt; No 2 equal letters + 2 equal different letters This is the code I am using: LETTERS = 'bcdfghjklmnpqrstvwxz' DIGITS = '2456789' def aab12(letters=LETTERS, digits=DIGITS): """Generate the distinct 5-character strings consisting of three letters (two are equal and a repeated letter) and two digits (each one is different from the other). """ letterdxs = set(range(5)) combs = [] for (d1, d2), (i, j), (l1, l2) in product( permutations(digits, 2), # 2 digits (a repeated). combinations(range(5), 2), # Positions for the 1st and 2nd digits. permutations(letters, 2)): # 2 letters (a repeated). x, y, z = letterdxs.difference((i, j)) s = set((x, y, z)) # Choosing 2 positions for the repeated letters c1 = combinations((x, y, z), 2) for c in c1: result = [] result[i:i] = d1, result[j:j] = d2, result[c[0]:c[0]] = l1, result[c[1]:c[1]] = l1, # Choosing position for the last letter. This is position that was left letter_indx = (s.difference(c)).pop() result[letter_indx:letter_indx] = l2, combs.append(''.join(result)) # Should be 478,800 print(len(combs)) return combs def is_contain_dup(combos): s = set(combos) if len(s) != len(combos): print('found duplicates !') is_contain_dup(aab12()) I have duplication although the length is ok. This function is based on this math: Choosing 2 places for the different digits Choosing 2 places for the repeated letter Choosing different letter from the last letter I am not sure what is causing the duplication but this is probably some…
favorite count: 0
tagged with: combinatorics
tagged with: python
has answer: http://stackoverflow.com/a/52236378
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/52224466
has comment: http://stackoverflow.com/comment/91409953
type: Question
has answer: http://stackoverflow.com/a/52230310
tagged with: math
accepted answer: http://stackoverflow.com/a/52230645
has comment: http://stackoverflow.com/comment/91410481
has title: How to generate 5-character strings combinations (2 different digits, two equal letters and 1 letter) without duplication

http://stackoverflow.com/q/52122674
tagged with: pyarrow
has answer: http://stackoverflow.com/a/63642527
type: Question
upvote count: 27
has answer: http://stackoverflow.com/a/79214328
score: 27
possible better answer: http://stackoverflow.com/a/58978449
has body: I use pyarrow to create and analyse Parquet tables with biological information and I need to store some metadata, e.g. which sample the data comes from, how it was obtained and processed. Parquet seems to support file-wide metadata, but I cannot find how the write it via pyarrow. The closest thing I could find is how to write row-group metadata, but this seems like an overkill, since my metadata is the same for all row groups in the file. Is there any way to write file-wide Parquet metadata with pyarrow?
linked to: http://stackoverflow.com/q/61707170
answer count: 3
downvote count: 0
favorite count: 0
has title: How to write Parquet metadata with pyarrow?
tagged with: python
accepted answer: http://stackoverflow.com/a/63642527
has answer: http://stackoverflow.com/a/58978449
type: AnsweredQuestion
tagged with: parquet

http://stackoverflow.com/comment/91458323
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52252694
type: Comment
has text: yes, i'll also try that with AWS. thank you

http://stackoverflow.com/comment/91470419
type: QuestionComment
has text: use `dataSrc:' ',` in your code.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52261182

lstm
tags question: http://stackoverflow.com/q/52199485
tags question: http://stackoverflow.com/q/52138290
tags question: http://stackoverflow.com/q/52196554
tags question: http://stackoverflow.com/q/52124659
tags question: http://stackoverflow.com/q/52115527
tags question: http://stackoverflow.com/q/52164882
tags question: http://stackoverflow.com/q/52153886
tags question: http://stackoverflow.com/q/52251674
tags question: http://stackoverflow.com/q/52189093
tags question: http://stackoverflow.com/q/52117900
tags question: http://stackoverflow.com/q/52162609
tags question: http://stackoverflow.com/q/52234377
tags question: http://stackoverflow.com/q/52234213
tag name: lstm
tags question: http://stackoverflow.com/q/52216747
tags question: http://stackoverflow.com/q/52265795
tags question: http://stackoverflow.com/q/52154162
tags question: http://stackoverflow.com/q/52113582
tags question: http://stackoverflow.com/q/52145802
tags question: http://stackoverflow.com/q/52155642
tags question: http://stackoverflow.com/q/52118314
tags question: http://stackoverflow.com/q/52170404
tags question: http://stackoverflow.com/q/52193464
tags question: http://stackoverflow.com/q/52241632
tags question: http://stackoverflow.com/q/52187453
tags question: http://stackoverflow.com/q/52197023
tags question: http://stackoverflow.com/q/52202432
type: Tag
tags question: http://stackoverflow.com/q/52200515
tags question: http://stackoverflow.com/q/52117648
tags question: http://stackoverflow.com/q/52201643
tags question: http://stackoverflow.com/q/52254466
tags question: http://stackoverflow.com/q/52142035
tags question: http://stackoverflow.com/q/52182185
tags question: http://stackoverflow.com/q/52152054

http://stackoverflow.com/comment/91207378
score: 1
comment on: http://stackoverflow.com/q/52128445
type: Comment
type: QuestionComment
has text: Post samples of the dataset and needed rsut

http://stackoverflow.com/comment/91244684
type: QuestionComment
has text: *"... caused by the accents"* - I believe they are called *[diacritics](https://en.wikipedia.org/wiki/Diacritic)* (assuming more than just the accent is giving you trouble).
score: 0
comment on: http://stackoverflow.com/q/52144909
type: Comment

http://stackoverflow.com/a/52155195
score: 0
answers question: http://stackoverflow.com/q/52140621
has comment: http://stackoverflow.com/comment/91262479
type: Answer
has body: I have done it by concatenating all the csvs that I read into one then, used to list function. But there is so many other ways to do it. I think its bit longer but here my solution: path =r'C:\KingP\myfolder' # use your path allFiles = glob.glob(path + "/*.csv") frame = pd.DataFrame() list_ = [] for file_ in allFiles: df = pd.read_csv(file_,index_col=None, header=0) list_.append(df) frame = pd.concat(list_) Then transposed the whole lot, and used to the holist function: frame= frame.values.T.tolist()

http://stackoverflow.com/a/52202158
answers question: http://stackoverflow.com/q/52181256
type: Answer
has body: Okay I managed to run the code with 3D input variables and a sin(x) activation function. It seems to work, just needed the right tf function to make A*x and some reshaping. The gradient function is def _my_linear_grad(op, grad): return grad * tf.reshape( tf.cos(tf.tensordot(op.inputs[0], op.inputs[1],1)+op.inputs[2]) * op.inputs[1],(1,3)), grad * tf.convert_to_tensor(np.zeros((3,)).astype(np.float32)), grad * tf.cos(tf.tensordot(op.inputs[0], op.inputs[1],1)+op.inputs[2]) for function def my_linear(a, x, b): return np.sin(np.dot(x,a.T).astype(np.float32) + b.astype(np.float32)) The loss function reaches values under 1e-6 and the obtained weights are correct. Still, the loss computed via the py_func wrapper and the one computed directly with tf_p = tf.sin(tf.tensordot(tf_a,x,1) + tf_b) tf_loss = tf.reduce_mean(tf.square(tf_p - y)) are not the same, I wonder why.
score: 0

http://stackoverflow.com/comment/91177552
comment on: http://stackoverflow.com/q/52113360
type: Comment
type: QuestionComment
score: 0
has text: It is not the same question @jezrael. There were 2 list compared. I am looking for an pandas function which iterates over its array items and checks if that element is inside a list.

http://stackoverflow.com/comment/91346222
type: Comment
has text: You are using threads, is some other one manipulating the same data?
score: 5
comment on: http://stackoverflow.com/q/52198434
type: QuestionComment

http://stackoverflow.com/q/52196940
has comment: http://stackoverflow.com/comment/91343131
score: 2
upvote count: 3
type: UnansweredQuestion
has body: I was reading this research paper fully convolutional network for semantic segmentation and following is quote from this paper The fully connected layers of these nets have ﬁxed dimensions and throw away spatial coordinates. However, these fully connected layers can also be viewed as convolutions with kernels that cover their entire input regions. I didn't understand bold part, but after some researching on internet I have come to conclusion that if I remove last layer(that is fully connected layer) and then convolve last layer(which was second last before removing fully connected layer) with three 1x1 kernels, I will be doing the same thing as the bold part says. Am I correct here? Why three 1x1 kernels? Because in paper they are creating a heatmap in rgb from original input and rgb means three channels, but result of convolution network(without fully connected layer) is having many channels(high dimensional) and therefore convolution with three 1x1 kernels to make it an rbg image. Image from paper
tagged with: python
has answer: http://stackoverflow.com/a/66801915
downvote count: 1
tagged with: conv-neural-network
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/91343185
answer count: 1
favorite count: 0
has title: creating fully convolution network

http://stackoverflow.com/comment/91404278
score: 0
type: Comment
has text: if your variable was named `s`, try `re.search(r"dp\/([A-Za-z0-9]{10})\/", s["href"])`
type: AnswerComment
comment on: http://stackoverflow.com/a/52225235

http://stackoverflow.com/a/52232147
has comment: http://stackoverflow.com/comment/91413685
type: Answer
has comment: http://stackoverflow.com/comment/91413695
accepted answer of: http://stackoverflow.com/q/52232129
has comment: http://stackoverflow.com/comment/91415680
answers question: http://stackoverflow.com/q/52232129
score: 3
upvote count: 3
has body: pandas.factorize and numpy.split i, u = pd.factorize([*df.A, *np.concatenate(df.B)]) l = df.B.str.len()[:-1].cumsum() n = len(df) df.assign(MappedA=i[:n], MappedB=np.split(i[n:], l)) A B MappedA MappedB 0 2f4 [jki, gg4, k6k] 0 [3, 4, 5] 1 1k1 [2f4, gg4, g24] 1 [0, 4, 6] 2 nmk [1k1, g24, 1k1] 2 [1, 6, 1] Explanation factorize all of column 'A' and 'B' together find the length of lists in 'B' because they'll help define where to split the resulting array Take the first n belonging to 'MappedA' Take the rest and split according to calculated lengths. Variable Lengths Assume we had this df instead df = pd.DataFrame(data={'A': ['2f4', '1k1', 'nmk'], 'B': ['x', 'y', 'z']}) df.at[0, 'B'] = ['jki', 'gg4', 'k6k'] df.at[1, 'B'] = ['2f4', 'gg4', 'g24'] df.at[2, 'B'] = ['1k1', 'g24', '1k1', 'pir'] df A B 0 2f4 [jki, gg4, k6k] 1 1k1 [2f4, gg4, g24] 2 nmk [1k1, g24, 1k1, pir] Then the same solution results in i, u = pd.factorize([*df.A, *np.concatenate(df.B)]) l = df.B.str.len()[:-1].cumsum() n = len(df) df.assign(MappedA=i[:n], MappedB=np.split(i[n:], l)) A B MappedA MappedB 0 2f4 [jki, gg4, k6k] 0 [3, 4, 5] 1 1k1 [2f4, gg4, g24] 1 [0, 4, 6] 2 nmk [1k1, g24, 1k1, pir] 2 [1, 6, 1, 7]
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91228947
type: Comment
comment on: http://stackoverflow.com/q/52139568
has text: i've checked and both of them contain `'div', class_='vehicle-browse--result--info'`
type: QuestionComment
score: 0

http://stackoverflow.com/q/52171097
has comment: http://stackoverflow.com/comment/91293738
has comment: http://stackoverflow.com/comment/91299299
score: -1
tagged with: image-processing
has comment: http://stackoverflow.com/comment/91353230
upvote count: 0
answer count: 1
favorite count: 0
has title: Image Cropping using canny edges detection
has answer: http://stackoverflow.com/a/52171382
tagged with: python
has body: I have generated the edges using Canny edge detector now want to crop source image by those edges. Is there any way to get. Left and Top Most 255 pixel location of image. Right and Top Most 255 pixel location of image. Left and Bottom Most 255 pixel location of image. Right and Bottom Most 255 pixel location of image. And crop that image based on that location. Using open cv or any other library using python.
linked to: http://stackoverflow.com/q/34981144
type: UnansweredQuestion
tagged with: canny-operator
has comment: http://stackoverflow.com/comment/91340337
downvote count: 1
duplicate of: http://stackoverflow.com/q/34981144
type: Question
tagged with: opencv

http://stackoverflow.com/comment/91484583
type: QuestionComment
comment on: http://stackoverflow.com/q/52268509
score: 0
has text: ... or you override the models save method but you have to catch the wrong data entry in the view then.
type: Comment

http://stackoverflow.com/a/52158075
score: 7
downvote count: 1
has body: If you want to return error as string: &gt;&gt;&gt; def test(): try: if x['error']:raise except Exception as err: return err &gt;&gt;&gt; test() NameError("name 'x' is not defined",) If you want to an error to occur: &gt;&gt;&gt; def test(): try: if x['error']:raise except: raise &gt;&gt;&gt; test() Traceback (most recent call last): File "&lt;pyshell#20&gt;", line 1, in &lt;module&gt; test() File "&lt;pyshell#19&gt;", line 3, in test if x['error']:raise NameError: name 'x' is not defined
answers question: http://stackoverflow.com/q/52157937
upvote count: 8
type: Answer

http://stackoverflow.com/q/52258617
accepted answer: http://stackoverflow.com/a/52259056
has comment: http://stackoverflow.com/comment/91464698
has title: Mismatch in Python numpy.testing
has body: Is there any chance for storing the value os mismatch in one variable? np.testing.assert_array_almost_equal(x,y,decimal=2) As you see the ouput of the function is a boolean and an assertion error. The mismatch value appears within the message AssertionError: Arrays are not almost equal to 2 decimals (mismatch 57.095709571%) x: array([ 0.01, 0.01, 0.01, ..., -0. , 0.01, 0.01]) y: array([0.02, 0.02, 0.02, ..., 0.02, 0.02, 0.02])
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: numpy
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52259056

http://stackoverflow.com/q/52200102
downvote count: 0
score: 4
has body: I have a large 1-dimensional array x which I've got by concatenation of smaller arrays x_0 ,..., x_m-1 of different length. I also know the list L of the length of each x_i. Given an array a of length m, the goal is to compute a flat array [a[0]*x0, a[1]*x1,...]. For example, if I have x = np.array([1,2,3,4,5]) and a=np.array([2,-1]), L = [2,3], then the result should be np.array([2,4,-3,-4,-5]) Is there any simpler (faster, more pythonic, etc.) way to do this in numpy, than this naive implementation? L.insert(0,0) cs = np.cumsum(L) y = np.empty(x.shape) for i in range(m): y[cs[i]:cs[i+1]] = a[i] * x[cs[i]:cs[i+1]] I can also do this in Numba. m is of order of hundreds, the length of each x_i is around 1e6.
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/52205961
has answer: http://stackoverflow.com/a/52205961
has answer: http://stackoverflow.com/a/52200156
type: AnsweredQuestion
has title: Block scalar-vector multiplication in numpy
type: Question
upvote count: 4
tagged with: numpy
answer count: 2
accepted answer: http://stackoverflow.com/a/52200156
tagged with: arrays

http://stackoverflow.com/comment/91299976
type: Comment
comment on: http://stackoverflow.com/q/52174334
score: 0
type: QuestionComment
has text: Ok, makes sense. Thanks for the explanation!

http://stackoverflow.com/a/52249331
has body: If your tuples are guaranteed to come in order like this—all the (0, x), then all the (1, x), etc.—you can use groupby: &gt;&gt;&gt; xs = [(0, 1), (0, 1), (0, 0), (0, 0), (1, 0), (1, 0), (1, 1), (1, 0), (1, 0), (2, 0), (2, 1), (2, 0), (3, 0), (3, 1), (3, 1), (3, 0), (3, 0), (4, 0), (4, 1), (4, 0), (4, 1), (4, 1), (5, 0), (5, 0), (5, 1), (5, 1)] &gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; groups = groupby(xs, key=itemgetter(0)) &gt;&gt;&gt; ys = [(key, sum(map(itemgetter(1), group))) for key, group in groups] If they aren't, but you can sort them (you have a list, not just an arbitrary iterable, and it isn't so huge that log-linear time will be too expensive): &gt;&gt;&gt; groups = groupby(sorted(xs, key=itemgetter(0)), key=itemgetter(0)) If you can't sort them, you can manually build up the totals as you go: &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; totals = Counter() &gt;&gt;&gt; for k, v in xs: ... totals[k] += v &gt;&gt;&gt; ys = list(totals.items())
upvote count: 3
has comment: http://stackoverflow.com/comment/91454308
has comment: http://stackoverflow.com/comment/91454260
score: 3
has comment: http://stackoverflow.com/comment/91452550
answers question: http://stackoverflow.com/q/52249282
downvote count: 0
type: Answer

http://stackoverflow.com/a/52143762
has comment: http://stackoverflow.com/comment/91237822
has comment: http://stackoverflow.com/comment/91270727
type: AcceptedAnswer
has body: If you want to relate a model to another model then based on relation you can use OneToOneField, ManyToManyField, ForeignKey, etc Here what you have done is that you have a model Leave with Fields employee_ID, name and user Another model History with fields employee_ID, name, user (inherited from Leave) and emp_ID, full_name. This is just extending that model class and creating new model objects. Both will remain unrelated only. (I don't have enough experience to tell you exact/detailed behaviour) So, for you case you can have a OneToOneField(or something else based on your business logic) from history model to leave model something like this. class Leave(models.Model): employee_ID = models.CharField(max_length = 20) name = models.CharField(max_length = 50) user = models.ForeignKey(User, on_delete = models.CASCADE, null =True) class History(models.Model): emp_ID = models.CharField(('employee ID'),max_length = 25) full_name = models.CharField(('Name'),max_length = 40) leave = models.OneToOneField(Leave, on_delete = models.SET_NULL) Then you can save your data as follows : # I am assuming you're inside some view and you want to create leave for the user who is logged in, refactor based on your requirements leave = Leave.objects.create(employee_ID="EMPLOYEEID", name="EMPLOYEENAME", user=request.user) # here pass the leave that we have created previously history = History.objects.create(emp_ID="EMPLOYEEID", full_name="EMPLOYEEFULLNAME", leave=leave) I am assuming you're having leave start and end datetime field also. I think you should also look into why employee ID is repeated in both models. Let me know if you have any doubts/queires. Thanks~
type: Answer
answers question: http://stackoverflow.com/q/52113769
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52113769
downvote count: 0
has comment: http://stackoverflow.com/comment/91303885

http://stackoverflow.com/comment/91564002
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52295162
type: Comment
has text: Interesting and good to know - but this only allow to skip full modules, which is not the same as skipping specific decorators (function or class-based) - it doesn't work if the decorator is in the same module (which is not uncommon) nor if you don't want to skeep other code in the same module as the decorator (which is not uncommon either).

http://stackoverflow.com/q/52258066
linked to: http://stackoverflow.com/q/6499603
has comment: http://stackoverflow.com/comment/91463344
score: 1
has comment: http://stackoverflow.com/comment/91463489
has comment: http://stackoverflow.com/comment/91463952
has comment: http://stackoverflow.com/comment/91463623
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52259647
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91463334
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/91464307
has title: How to get the hostname of the request?
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91463408
favorite count: 0
has body: Sometimes when I scrape a site, it does not return urls with the hostname (e.g /search/en or search/en). How do I get the hostname in scrapy so I can add it before making a request? Currently, I am hardcoding it. def parse_table(self, response): for links in self._parse_xpath(response, 'table'): for link in links: # Annoying part, it's not dynamic and hardcoded, other #functions also need to do this because of incomplete urls. yield Request(url='https://domain.io' + link, callback=self.parse_document_tab)
has answer: http://stackoverflow.com/a/52259647
has comment: http://stackoverflow.com/comment/91463760
has comment: http://stackoverflow.com/comment/91463590

http://stackoverflow.com/a/52152174
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91291753
type: Answer
accepted answer of: http://stackoverflow.com/q/52152053
has body: Errors There are a couple of errors in the application. NameError - Solution Add root.ids.ids.coneVolume_screen.ids. to the arguments. AttributeError After solving the NameError, an AttributeError will occurred. AttributeError: 'NoneType' object has no attribute 'ids'. This is because inner ids are not available yet. Kivy Language » ids Note that the outermost widget applies the kv rules to all its inner widgets before any other rules are applied. This means if an inner widget contains ids, these ids may not be available during the inner widget’s __init__ function. AttributeError: ids - Solutions Give an id to the Label e.g. id: result Add an on_pre_enter event to invoke getConeVolume() method. Replace TextInput object with TextInput's text i.e. replace cone_vol_radius and cone_vol_height with cone_vol_radius.text and cone_vol_height.text respectively. Add int() function to convert TextInput's text/string to integer. Snippet &lt;SolveConeVolumeScreen&gt;: on_pre_enter: root.ids.result.text = app.getConeVolume(int(app.root.ids.coneVolume_screen.ids.cone_vol_radius.text), int(app.root.ids.coneVolume_screen.ids.cone_vol_height.text)) BoxLayout: orientation: 'vertical' Label: id: result Output
answers question: http://stackoverflow.com/q/52152053
has comment: http://stackoverflow.com/comment/91255105

http://stackoverflow.com/a/52250017
score: 0
has body: Solution dict_a = { 'test 1': [1, 2, 3, 4], 'test 2': [2, 2, 3, 4], 'test 3': [1, 2, 4, 5], 'test 4': [6, 2, 3, 4], 'test 5': [7, 2, 3, 4] } answer = [6, 2, 3, 4] for i in dict_a: if answer[0] != dict_a[i][0]: if answer[1:4] == dict_a[i][1:4]: print(dict_a[i]) Store Output answer = [6, 2, 3, 4] store = {} for i in dict_a: if answer[0] != dict_a[i][0]: if answer[1:4] == dict_a[i][1:4]: store[i] = dict_a[i] for k in store: print(f"{k}: {store[k]}") Output (xenial)vash@localhost:~/python/AtBS$ python3.7 list_dict.py [1, 2, 3, 4] [2, 2, 3, 4] [7, 2, 3, 4]
type: Answer
answers question: http://stackoverflow.com/q/52249889

http://stackoverflow.com/q/52268068
has comment: http://stackoverflow.com/comment/91483905
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/52268148
tagged with: datetime
tagged with: python
has body: I want to compare two datetime variables to detect the current time is in weekend time or not. My code is here: def is_weekend_off(weekend_table, trading_timezone): now_trading_timezone = datetime.now(tz=trading_timezone) is_weekend = False for it in weekend_table: condition1 = it[0] &lt;= now_trading_timezone condition2 = now_trading_timezone &lt; it[1] condition3 = condition1 and condition2 print('now = ' + str(now_trading_timezone)) print('it[0] = ' + str(it[0])) print('it[1] = ' + str(it[1])) print('condition1 = ' + str(condition1)) print('condition2 = ' + str(condition2)) time.sleep(60) if condition3: tmp = True else: tmp = False is_weekend = is_weekend or tmp return is_weekend and the result is here: now = 2018-09-10 21:50:59.001475-05:00 it[0] = 2018-09-10 21:00:00-05:51 it[1] = 2018-09-10 22:00:00-05:51 condition1 = False condition2 = True As I know, condition1 should be True, not False. How do I correct this result?
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91483873
type: Question
accepted answer: http://stackoverflow.com/a/52268148
has comment: http://stackoverflow.com/comment/91483879
has title: How to compare two datetime variables correctly?
downvote count: 0
answer count: 1

google-cloud-functions
tag name: google-cloud-functions
tags question: http://stackoverflow.com/q/52226691
tags question: http://stackoverflow.com/q/52231300
type: Tag
tags question: http://stackoverflow.com/q/52129628
tags question: http://stackoverflow.com/q/52239034
tags question: http://stackoverflow.com/q/52265879
tags question: http://stackoverflow.com/q/52249978

http://stackoverflow.com/a/52243379
has comment: http://stackoverflow.com/comment/127942970
has comment: http://stackoverflow.com/comment/91435115
type: Answer
has comment: http://stackoverflow.com/comment/127943160
answers question: http://stackoverflow.com/q/52238803
downvote count: 1
upvote count: 17
accepted answer of: http://stackoverflow.com/q/52238803
has body: You can do it like this. You will get a dataframe with 2 columns. mylist = [ {"type_activity_id":1,"type_activity_name":"xxx"}, {"type_activity_id":2,"type_activity_name":"yyy"}, {"type_activity_id":3,"type_activity_name":"zzz"} ] myJson = sc.parallelize(mylist) myDf = sqlContext.read.json(myJson) Output : +----------------+------------------+ |type_activity_id|type_activity_name| +----------------+------------------+ | 1| xxx| | 2| yyy| | 3| zzz| +----------------+------------------+
type: AcceptedAnswer
score: 16

http://stackoverflow.com/q/52192722
upvote count: 0
has comment: http://stackoverflow.com/comment/91335351
has comment: http://stackoverflow.com/comment/91337448
has answer: http://stackoverflow.com/a/52192786
type: Question
type: AnsweredQuestion
score: -1
has comment: http://stackoverflow.com/comment/91335271
has comment: http://stackoverflow.com/comment/91335450
has comment: http://stackoverflow.com/comment/91335452
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91335540
has comment: http://stackoverflow.com/comment/91335199
has title: How to implement a class in python that can be compared, sorted, etc
has body: I am trying to write a Card class and I want to make sure that I can use comparison operators on it, as well as use max,min,sort of list of my Card objects. I read that to accomplish this I just need to implement __cmp__ but when I did that my unit tests would not pass, so I ended up implementing all of the comparison magic methods __gt__,__lt__,__eq__, etc. I want to get rid of bloat in my code and remove all of comparison methods expect for __cmp__ if possible. I am using Python 3.5 Anaconda distribution. This is my current implementation: __ranks__ = [2,3,4,5,6,7,8,9,10,"J","Q","K","A"] __suites__ = ["Clubs","Diamods","Hearts","Spades"] class Card(): def __init__(self,suite,rank): if suite in __suites__ and rank in __ranks__: self.suite = suite self.rank = rank else: raise ValueError("Cards need to be instansiated with names from __ranks__ and __suites") def __gt__(self,other): return self._compare_cards_(other,-1) def __lt__(self,other): return self._compare_cards_(other,1) def __ge__(self,other): return self._compare_cards_(other,-1) or self.__eq__(other) def __le__(self,other): return self._compare_cards_(other,1) or self.__eq__(other) def __eq__(self,other): return self._compare_cards_(other,0) def __ne__(self,other): return not self.__eq__(other) def _compare_cards_(self,other,expect): rank_comp = self._compare_ranks_(other.rank,self.rank) if rank_comp == 0: return self._compare_suites_(other.suite,self.suite) == expect return rank_comp == expect def _compare_ranks_(self,rank1,rank2): return self._compare_attributes_("rank",rank1,rank2) def _compare_suites_(self,suite1,suite2): return self._compare_attributes_("suite",suite1,suite2) def _compare_attributes_(self,name,attr1,attr2): attr_list = eval("__{}s__".format(name)) if attr_list.index(attr1) &lt; attr_list.index(attr2): return -1 if attr_list.index(attr1) == attr_list.index(attr2): return 0 if attr_list.index(attr1) &gt; attr_list.index(attr2): return 1 Originally instead of all the magic methods that I…
downvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52192786

http://stackoverflow.com/comment/91448974
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52129269
has text: Can you indicate if answers helped in any way?

http://stackoverflow.com/q/52258529
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 1
type: Question
has title: Overwriting files; changing the content but keeping the filename
has body: This'll be a bit long winded but might be best to explain the scenario first... We have a number of BI visualizations that are generated each month for management reporting. Just over 400 images are taken each month and automatically placed in a directory using WKHTMLTOIMAGE. These images are automatically updated in to various PowerPoint presentations and emailed off to the relevant teams. All of this "generally" works fine and has removed much of the tedious manual work. The problem occurs when one of these visualizations fails to update. At the moment there is no way of checking, other than to open up each visualization and compare it to the image that has just been extracted. If 399 of the 400 images work, and the 400th doesn't, PowerPoint would still be populated using the previously loaded (400th) image due to the way the "Link to File" function works in PowerPoint. What I'd like to do is use an example image (check.jpg) to overwrite all of the existing images but still keeping their original file names. That way when the monthly report is run if one of them doesn't work the PowerPoint would have still been updated with this check.jpg image which would stand out as something we would need to rerun manually. I can't seem to find anything along the lines of what I'm looking for. I can list all of the filenames, move them, overwrite them etc but not sure how I'd do it (or even if it's the right way to do it) with the scenario I'm thinking of. If someone could point me in the right direction, that'd be great. Thank you.
has answer: http://stackoverflow.com/a/52258786
upvote count: 1
answer count: 1

http://stackoverflow.com/a/52273758
has body: The expected_output in my opinion should be a simpler dictionary expected_output = {'13':'41.0', '14':'14.0'} next you can proceed like this data = open('...') next(data) # skip headers for line in data: id, val, *_ = [item.strip() for item in line.split(',')] if id in expected_output and val == expected_output[id]: # the observed output is the same as expected ... else: # observed is unexpected ...
score: 0
accepted answer of: http://stackoverflow.com/q/52263399
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52263399
type: Answer

http://stackoverflow.com/a/52241760
has comment: http://stackoverflow.com/comment/91434605
has comment: http://stackoverflow.com/comment/91432128
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/91433875
has comment: http://stackoverflow.com/comment/91433824
downvote count: 0
has comment: http://stackoverflow.com/comment/91433623
has comment: http://stackoverflow.com/comment/91432913
has comment: http://stackoverflow.com/comment/91432354
has body: You can define a custom constructors using a custom yaml.SafeLoader import yaml doc = ''' Conditions: CreateNewSecurityGroup: !Equals [!Ref ExistingSecurityGroup, NONE] ''' class Equals(object): def __init__(self, data): self.data = data def __repr__(self): return "Equals(%s)" % self.data class Ref(object): def __init__(self, data): self.data = data def __repr__(self): return "Ref(%s)" % self.data def create_equals(loader,node): value = loader.construct_sequence(node) return Equals(value) def create_ref(loader,node): value = loader.construct_scalar(node) return Ref(value) class Loader(yaml.SafeLoader): pass yaml.add_constructor(u'!Equals', create_equals, Loader) yaml.add_constructor(u'!Ref', create_ref, Loader) a = yaml.load(doc, Loader) print(a) Outputs: {'Conditions': {'CreateNewSecurityGroup': Equals([Ref(ExistingSecurityGroup), 'NONE'])}}
has comment: http://stackoverflow.com/comment/91434225
has comment: http://stackoverflow.com/comment/91434750
has comment: http://stackoverflow.com/comment/91434443
upvote count: 3
answers question: http://stackoverflow.com/q/52240554
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91432229
accepted answer of: http://stackoverflow.com/q/52240554

http://stackoverflow.com/a/52255256
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52250115
has body: You made one mistake: Y_score is not a of the form [0,0,1,0] from doc: y_score : array, shape = [n_samples] or [n_samples, n_classes] Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). meaning that it is of the following form [[0.33,0.66][0.65,0.35][0.1,0.9]...]. You get the probabilities for each class. Now the threshold is the value from wich you will decide wich class you will assign to every point. For example in the list i gave above with a Threshold of 0.4, if the proba of being 1 is superior to 0.4 then i assigne 1. With this threshold, my vector is now [1,0,1,...] but if the threshold is 0.70 then it's [0,0,1,....]. So with one prediction, you can apply different threshold ans thus compute the average_precision_score. Thre precision and recall are based on the threshold. a good explanation was made a few days ago here: Understanding ROC curve
type: Answer
answers question: http://stackoverflow.com/q/52250115
score: 4

http://stackoverflow.com/a/52152306
score: 1
has body: if you want only the products that ya have in first data_frame you can use this: df_1 Out[11]: id 0 1 1 2 2 4 3 5 df_2 Out[12]: id prod 0 1 a 1 2 b 2 3 c 3 4 d 4 5 e 5 6 f 6 7 g 7 8 h df_3 = df_1.merge(df_2,on='id') df_3 Out[14]: id prod 0 1 a 1 2 b 2 4 d 3 5 e you neede use the parameter on='column' so the will generate a new df only with the correspondent rows that have the same id.
answers question: http://stackoverflow.com/q/52152103
downvote count: 0
has comment: http://stackoverflow.com/comment/91255058
type: Answer
upvote count: 1

http://stackoverflow.com/q/52229912
tagged with: selenium
has answer: http://stackoverflow.com/a/52230147
has answer: http://stackoverflow.com/a/52259188
type: Question
has comment: http://stackoverflow.com/comment/91427995
possible better answer: http://stackoverflow.com/a/52242087
has answer: http://stackoverflow.com/a/52242087
has comment: http://stackoverflow.com/comment/91410345
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/91409567
has comment: http://stackoverflow.com/comment/91412438
accepted answer: http://stackoverflow.com/a/52259188
has comment: http://stackoverflow.com/comment/91409830
tagged with: python-3.x
has body: I am playing around with the code below, and the weird thing is that it keeps opening a Chrome browser instead of a Firefox browser. import requests import selenium from selenium import webdriver from bs4 import BeautifulSoup from webbot import Browser driver = webdriver.Firefox(executable_path= r'C:/path_here/geckodriver.exe') web = Browser() url = 'https://web_browser' web.go_to(url) # 1st validation web.type('email_address' , into='username') web.click('Continue') # password web.type('passwd' , into='password') web.click('Next') I got the geckodriver from the link below, and I change the extension from .gz to .exe, which I think is correct, but I'm not totally sure.. https://github.com/mozilla/geckodriver/releases
has title: Trying to get Firefox working with Selenium
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion

pynput
tags question: http://stackoverflow.com/q/52241868
tags question: http://stackoverflow.com/q/52238664
type: Tag
tags question: http://stackoverflow.com/q/52149914
tag name: pynput

http://stackoverflow.com/comment/91426807
type: QuestionComment
score: 5
has text: Your output makes no sense. Dictionaries can't have duplicate keys, that contradicts the purpose of a dictionary. What would result["person"] give?
type: Comment
comment on: http://stackoverflow.com/q/52239110

http://stackoverflow.com/comment/91420930
type: QuestionComment
has text: Ok, why not? Which part are you having trouble with? Have you done the tutorial? Your existing code shows that you know how to get an instance based on a URL parameter. What prevents you from modifying and saving that instance?
comment on: http://stackoverflow.com/q/52236057
score: 0
type: Comment

http://stackoverflow.com/q/52156583
downvote count: 0
linked to: http://stackoverflow.com/q/7933417
has body: I am attempting to get user statistics from the Fortnite tracker API. I have an API key and am using the correct URL as indicated in the documentation Template URL: https://api.fortnitetracker.com/v1/profile/{platform}/{epic-nickname} Desired URL: https://api.fortnitetracker.com/v1/profile/pc/xantium0 If I use this link in browser I get: {"message":"No API key found in request"} (as I have not passed the API key) so the link should be correct. Also if I do not pass the API key with urllib then I still get a 403 error. I have checked out how to pass a header in a request: How do I set HTTP headers using Python's urllib? and so far have this code: import urllib.request as ur request = ur.Request('https://api.fortnitetracker.com/v1/profile/pc/xantium0', headers={'TRN-Api-Key' : 'xxx'}) response = ur.urlopen(request) print(response.read()) When run I get this error: urllib.error.HTTPError: HTTP Error 403: Forbidden 403 checks out as: HTTP 403 is a standard HTTP status code communicated to clients by an HTTP server to indicate that the server understood the request, but will not fulfill it. There are a number of sub-status error codes that provide a more specific reason for responding with the 403 status code. https://en.wikipedia.org/wiki/HTTP_403 The response is the same if I don't pass the api key in the header. I can only think of three reasons this code is not working: I have passed the wrong header name (i.e. it's not TRN-Api-Key) My code is incorrect and I am not actually passing a header to the server I have been banned My problem is that I think my code is correct: From the documentation: urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None) I have passed the url and I have passed the headers (wihout confusing with the data arguement). The api documentation also mentions it should be passed in the headers. I am also quite sure I need to use the TRN-Api-Key as it is shown in the api documentation: TRN-Api-Key: x…
has title: 403 (Forbidden) error when using Fortnite Tracker API with urllib.request
tagged with: urllib
type: Question
tagged with: http-headers
upvote count: 2
answer count: 1
linked to: http://stackoverflow.com/q/49371820
has comment: http://stackoverflow.com/comment/117258225
favorite count: 0
has answer: http://stackoverflow.com/a/52160385
type: UnansweredQuestion
tagged with: python
tagged with: request
has comment: http://stackoverflow.com/comment/117272271
score: 2
has comment: http://stackoverflow.com/comment/91263690

http://stackoverflow.com/comment/91405322
score: 0
has text: I have something similar written, I wanted to have a compact version of above loop because as you can see in above code only (A == B) changes for different conditions but rest of the code is same, unnecessarily makes the code redundant and big
type: Comment
comment on: http://stackoverflow.com/a/52227924
type: AnswerComment

http://stackoverflow.com/comment/91413378
comment on: http://stackoverflow.com/a/52231962
has text: Right - I get what you mean. I'd initially tried something similar but got "TypeError: '>' not supported between instances of 'str' and 'int' ". So I attempted it the way I'd pasted above, but I've tried a combo of your char line and wrapping it with ord(char) for the rest of it and it works! Thanks very much.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91483301
type: Comment
comment on: http://stackoverflow.com/a/52267810
has text: And post back probably tomorrow.
score: 0
type: AnswerComment

unit-testing
tags question: http://stackoverflow.com/q/52118765
tags question: http://stackoverflow.com/q/52160542
tags question: http://stackoverflow.com/q/52268531
tags question: http://stackoverflow.com/q/52155056
tags question: http://stackoverflow.com/q/52240060
tags question: http://stackoverflow.com/q/52133482
tags question: http://stackoverflow.com/q/52258367
tags question: http://stackoverflow.com/q/52230750
tags question: http://stackoverflow.com/q/52119941
type: Tag
tags question: http://stackoverflow.com/q/52205363
tag name: unit-testing
tags question: http://stackoverflow.com/q/52180059
tags question: http://stackoverflow.com/q/52113100
tags question: http://stackoverflow.com/q/52194265
tags question: http://stackoverflow.com/q/52115885
tags question: http://stackoverflow.com/q/52168784
tags question: http://stackoverflow.com/q/52267935

http://stackoverflow.com/q/52113978
has comment: http://stackoverflow.com/comment/91178522
answer count: 0
has title: In "spawn" multiprocessing, process for Python3 to load function internal to a module for execution
tagged with: python-multiprocessing
type: Question
tagged with: spawn
has comment: http://stackoverflow.com/comment/91178630
score: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: Kindly note, all the description below is w.r.t. "spawn" method of multiprocessing (for compatibility with Windows). When multiprocessing is set to "spawn" method, a new process is loaded from the main file. This is one of the first info to find by searching online. I'm trying to dig deeper, and speed up the loading of a new Process (whenever it's created). Here's some idea on how my project is structured: &lt;root&gt; &lt;root&gt;/main.py &lt;root&gt;/modules/__init__.py &lt;root&gt;/modules/app/__init__.py &lt;root&gt;/modules/app/app.py &lt;root&gt;/modules/app/middleware/__init__.py &lt;root&gt;/modules/app/middleware/middleware.py Now, when I try to create a process inside of middleware.py, it tries to load everything from main.py (and a lot of unnecessary modules gets loaded up, which slows down the loading process for process in middleware.py). In my code a lot of extra libraries are also imported in main.py, and app.py, which slows down the first time loading the process craeted in middleware.py. But these extra modules aren't required to run the process created in middleware.py 1) How can I possibly make the loading of middleware.py as fast as possible (at the time of first launch of Process). And is it possible to directly load the middleware module in this new Process, rather than having everything load from main.py ? 2) I experimented by conditionally not loading app.py inside main.py (and hence middleware.py) whenever main.py is run as __mp_main__. I was expecting this to result in middleware.py never being loaded in the child process. But I still notice that middleware.py gets loaded. How is this possible?
tagged with: python

http://stackoverflow.com/a/52196927
upvote count: 2
has body: Your error stems from the fact that you are trying to concat (torch.cat) center and conv5 - but the dimensions of these tensors do not match. Originally, you had the following spatial dimensions conv5: 4x4 pool: 2x2 center: 4x4 # upsampled This way you can concat center and conv5 since they are both 4x4 tensors. However, if you remove the pooling layer, you end up with conv5: 4x4 center: 8x8 # upsampling more than you need Now you cannot concat center and conv5 since their spatial dimensions mismatch. What can you do? One option is to remove center as well as the pooling, leaving you with dec5 = self.dec5(conv5) Another option is to remove the nn.Upsample part from the block of center, leaving you with self.block = nn.Sequential( ConvRelu(in_channels, middle_channels), ConvRelu(middle_channels, out_channels), )
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91349978
type: Answer
has comment: http://stackoverflow.com/comment/91350165
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91349771
accepted answer of: http://stackoverflow.com/q/52192599
answers question: http://stackoverflow.com/q/52192599

http://stackoverflow.com/q/52235796
has title: Deepcopy specific attributes
has answer: http://stackoverflow.com/a/52235852
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: oop
upvote count: 2
accepted answer: http://stackoverflow.com/a/52235852
has comment: http://stackoverflow.com/comment/91420153
type: Question
has body: Is there a way to override the __copy__ method for a class in a way such that some attributes are only copied as a reference and other attributes are actually copied? To clarify what I mean, here's my guess on how this could be done. Consider the class Spam: class Spam: def __init__(self, val=0, val2=0): self.eggs = [] self.foo = [] self.val = val self.val2 = val2 Suppose we wanted to make sure that, upon calling copy.copy (i.e. a shallow copy) on a Spam object, its eggs attribute was deep-copied into the new object (so that mutations to the original object's attribute don't alter the copy's eggs attribute). "Why don't you just deepcopy the whole object then?"—because, unlike eggs, we want the foo attribute to be copied as a reference (so that changes to it are visible to all copies). Then, would the following be a valid approach? to_be_copied = ['eggs'] # States which attributes are to be copied def __copy__(self): copy_ = Spam() for attr in self.__dict__: if attr in Spam.to_be_copied: # Make an actual copy of the attribute copy_.__dict__[attr] = copy.copy(self.__dict__[attr]) else: # Copy reference copy_.__dict__[attr] = self.__dict__[attr] return copy_
has comment: http://stackoverflow.com/comment/91420096
tagged with: copy
answer count: 1
downvote count: 0

http://stackoverflow.com/q/52230953
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52231058
type: Question
tagged with: pyqt
tagged with: pyqt4
answer count: 1
score: 0
has body: Given a list of strings, I am trying to populate the items in a tree view. Here is my code: class MyModel(QtGui.QStandardItemModel): def __init__(self, parent=None): super(MyModel, self).__init__(parent) self.get_contents() def get_contents(self): self.clear() contents = [ '|Base|character|Mike|body', '|Base|character|John', '|Base|camera' ] for content in contents: count = content.count('|') for index in range(count): index = index + 2 split_path = content.split('|')[0:index] self.add_item(split_path) def add_item(self,name): item1 = QtGui.QStandardItem(name) self.appendRow([item1]) However, the hierarchy that I have got in my Tree View are not collapsible (those with the small arrow icons by the side) and each row is appended with values and editable (if double click), in which I do not want. An example of the output from my code: |Base |Base|character |Base|character|Mike |Base|character|Mike|body |Base |Base|character |Base|character|John |Base |Base|camera where there are a few repeatable rows... And this is what I am expecting: |-- Base |--|-- character |--|--|-- Mike |--|--|--|-- body |--|-- character |--|--|-- John |--|-- camera Any insights?
has title: Creating QTreeView hierarchy from a given list
has comment: http://stackoverflow.com/comment/91411458
tagged with: qtreeview
has answer: http://stackoverflow.com/a/52231058
tagged with: python

http://stackoverflow.com/q/52167706
has comment: http://stackoverflow.com/comment/91288359
has title: Django Rest framework, how to include '__all__' fields and a related field using foreignkey_id field
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/91285803
has comment: http://stackoverflow.com/comment/91286910
has answer: http://stackoverflow.com/a/52168450
has comment: http://stackoverflow.com/comment/91286866
has comment: http://stackoverflow.com/comment/91285792
has answer: http://stackoverflow.com/a/52168817
tagged with: python
possible better answer: http://stackoverflow.com/a/52168450
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91286775
tagged with: django
type: Question
accepted answer: http://stackoverflow.com/a/52168817
has comment: http://stackoverflow.com/comment/91286488
has answer: http://stackoverflow.com/a/52168769
has comment: http://stackoverflow.com/comment/91286713
has comment: http://stackoverflow.com/comment/91286055
score: 0
answer count: 3
has body: So here is my files - Models.py class Model1(models.Model): user = models.ForeignKey(User) other_fields = models.CharField(max_length=40) Serializers.py class MySerializer(ModelSerializer): class Meta: model = Model1 fields = '__all__' Here json request {"user_id":1, "other_fields":"details"} and in views.py serializer = MySerializer(data=request.data) serializer.data **Throws keyerror "user"** When i try to change request parameter "user_id" to "user" it works for me . But I can't change request json. Is there any way to handle this issue in serializer? I can set all the fields inplace of '_all_' but it is not a good solution due to large number of fields . I also tried with - class MySerializer(ModelSerializer): user = serializers.CharField(source='user_id') class Meta: model = Model1 fields = '__all__' but it was not worked for me.

http://stackoverflow.com/q/52113158
favorite count: 0
type: UnansweredQuestion
score: -3
tagged with: python
has body: Attempting to test my project recently, I have been getting the following traceback every time. https://paste.gnome.org/pwkpqejza Python Version 3.5.3 pytest 3.6.3 Running via ./setup.py test --addopts "tests/ -s" The tests run fine in CI, so it is clearly an issue with my configuration. CI Configuration: platform linux -- Python 3.5.3, pytest-3.7.3, py-1.6.0, pluggy-0.7.1 -- /usr/bin/python3 EDIT: Turned out to be an issue primarily caused by the pytest version as mentioned by @phd. This was caused due to some version pinning which didn't seem to effect the CI. rm -rf .eggs solved the problem for me.
tagged with: pytest
has title: pytest ImportError Package
has answer: http://stackoverflow.com/a/52118595
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91365650
tagged with: importerror
downvote count: 4
answer count: 1
has comment: http://stackoverflow.com/comment/91226972
has comment: http://stackoverflow.com/comment/91370465

http://stackoverflow.com/q/52222404
has comment: http://stackoverflow.com/comment/91394440
tagged with: matplotlib
has title: Python matplotlib: legend gives wrong result for scatter
has body: I'm trying to visualize fashion MNIST dataset with different dimensional reduction techniques and I also want to attach the legend to resulted picture with so called real_labels which tells the real name of the label. For fashion MNIST real labels are: real_labels = ['t-shirt','trouser','pullover','dress','coat','sandal','shirt','sneaker','bag','ankle boot'] I'm doing the plotting part inside of following fucntion: def Draw_datasamples_to_figure(X_scaled, labels, axis): y = ['${}$'.format(i) for i in labels] num_cls = len(list(set(labels))) for (X_plot, Y_plot, y1, label1) in zip(X_scaled[:,0], X_scaled[:,1], y, labels): axis.scatter(X_plot, Y_plot, color=cm.gnuplot(int(label1)/num_cls),label=y1, marker=y1, s=60) , where X_scaled tells x and y coordinate, labels are integer numbers (0-9) for class information and axis tells in which subplot window picture will be drawn. The legend is drawn with following command: ax3.legend(real_labels, loc='center left', bbox_to_anchor=(1, 0.5)) Everything seems to work pretty well until the legend is drawn to picture. As you can see from picture in below, instead of numbers goes from 0 to 9, the chosen numbers in legend are arbitrary. I know that the problem is probably in scatter part and I should implement it in another way but I hope that there is still something simple that I miss which can fix my implementation. I don't want either to use hand-made legend in where markers and names are defined in the code because I have also other datasets with different classes and real label names. Thanks in advance!
score: 0
tagged with: legend
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91397748
type: Question
has comment: http://stackoverflow.com/comment/91395159

http://stackoverflow.com/q/52167672
has title: Conditional minimum of two columns with NA's
type: Question
tagged with: numpy
has body: How can I efficiently create a new column which is the minimum of column 3 and column 2 when column 1 has a particular value? Example: my_dataframe=pd.DataFrame({'col1':[1.0,2.0,3.0], 'col2':[4.0,5.0,6.0], 'col3':[0.25,np.nan,0.25]}) my_dataframe = my_dataframe.assign(col4 = lambda x: np.where(x['col1']&gt;1, np.minimum(x['col2'], x['col3']), 0)) RuntimeWarning: invalid value encountered in minimum I assume that the np.minimumfunction can't handle the NA, so how can I work around this? The numpy.nanmin function does not work as well. It returns the following error, since it is not applied to an array TypeError: 'Series' object cannot be interpreted as an integer So I tried to write it as follows my_dataframe = my_dataframe.assign(col4 = lambda x: np.where(x['col1']&gt;1, np.nanmin(x['col2'].values(), x['col3'].values()), 0)) which returns the error: TypeError: 'numpy.ndarray' object is not callable
tagged with: pandas
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/52167713
favorite count: 0
tagged with: python
tagged with: na
downvote count: 0
type: UnansweredQuestion
score: 1
tagged with: minimum

http://stackoverflow.com/comment/91213340
has text: @staydin `print(*divide_and_conquer(0, 10), sep='\n')`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52131177
type: AnswerComment

qwidget
tag name: qwidget
tags question: http://stackoverflow.com/q/52142950
type: Tag

http://stackoverflow.com/comment/92221190
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52207123
has text: Yes you have to ”install” them, otherwise imports will fail. Installing can be having the current working directory set so that the top level package can be found, or setting the PYTHONPATH environment variable accordingly, or installing the package in development mode i.e. making it available from the place you are editing it.

http://stackoverflow.com/a/52249216
has comment: http://stackoverflow.com/comment/91554773
has comment: http://stackoverflow.com/comment/91584838
answers question: http://stackoverflow.com/q/52249132
has comment: http://stackoverflow.com/comment/102923329
score: 4
upvote count: 4
downvote count: 0
has body: Look at the last "if" statement. If there's no text "html" in the url, nothing gets printed. Try removing that and un-indenting: class Scraper: def __init__(self, site): self.site = site def scrape(self): r = urllib.request\ .urlopen(self.site) html = r.read() parser = "html.parser" sp = BeautifulSoup(html, parser) for tag in sp.find_all("a"): url = tag.get("href") if url is None: continue print("\n" + url)
type: Answer

http://stackoverflow.com/q/52214170
has comment: http://stackoverflow.com/comment/91377887
upvote count: 1
type: Question
score: -2
tagged with: pythonista
has comment: http://stackoverflow.com/comment/91377898
has comment: http://stackoverflow.com/comment/91379047
answer count: 1
has comment: http://stackoverflow.com/comment/91378014
has answer: http://stackoverflow.com/a/52214629
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91377867
tagged with: python
has title: How do I make a specifically formatted dictionary from a csv file?
has comment: http://stackoverflow.com/comment/91378037
type: UnansweredQuestion
downvote count: 3
has body: I've looked around on the internet but I haven't found anything that works. I want to turn dovah.csv into a dictionary for a translator. Is there a way to specifically format it like this? english_to_dovahzul = { 'the': 'faal', 'quick': 'nel', 'brown': 'prun', 'fox': 'ilit' } dovahzul_to_english = {v: k for k, v in.english_to_dovahzul.items()}

http://stackoverflow.com/comment/91392879
type: AnswerComment
score: 0
type: Comment
has text: @KoYan Are your values integers like in the first dataframe or floats like in the second? It could be a floating point comparison problem. If your values are floats, you should cast them to integer before grouping.
comment on: http://stackoverflow.com/a/52220950

http://stackoverflow.com/comment/91259206
score: 1
has text: Please [edit] your question and make your [mcve] stand independent of your link to `commercialtrucktrader.com`. Your question should be useful not just to you but to future readers as well, and we cannot trust that the link will remain available and relevant to your question in the future. Thanks.
type: Comment
comment on: http://stackoverflow.com/q/52153881
type: QuestionComment

http://stackoverflow.com/comment/91511341
comment on: http://stackoverflow.com/a/52231058
has text: @yan Are you using QStandardItemModel?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52243060
accepted answer: http://stackoverflow.com/a/52243726
tagged with: dataframe
answer count: 3
tagged with: pandas-groupby
tagged with: pandas
downvote count: 0
favorite count: 0
has title: Get row value of maximum count after applying group by in pandas
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52243726
has body: I have the following df &gt;In [260]: df &gt;Out[260]: size market vegetable confirm availability 0 Large ABC Tomato NaN 1 Large XYZ Tomato NaN 2 Small ABC Tomato NaN 3 Large ABC Onion NaN 4 Small ABC Onion NaN 5 Small XYZ Onion NaN 6 Small XYZ Onion NaN 7 Small XYZ Cabbage NaN 8 Large XYZ Cabbage NaN 9 Small ABC Cabbage NaN 1) How to get the size of a vegetable whose size count is maximum? I used groupby on vegetable and size to get the following df But I need to get the rows which contain the maximum count of size with vegetable In [262]: df.groupby(['vegetable','size']).count() Out[262]: market confirm availability vegetable size Cabbage Large 1 0 Small 2 0 Onion Large 1 0 Small 3 0 Tomato Large 2 0 Small 1 0 df2['vegetable','size'] = df.groupby(['vegetable','size']).count().apply( some logic ) Required Df : vegetable size max_count 0 Cabbage Small 2 1 Onion Small 3 2 Tomato Large 2 2) Now I can say 'Small Cabbages' are available in huge quantity from df. So I need to populate the confirm availability column with small for all cabbage rows How to do this? size market vegetable confirm availability 0 Large ABC Tomato Large 1 Large XYZ Tomato Large 2 Small ABC Tomato Large 3 Large ABC Onion Small 4 Small ABC Onion Small 5 Small XYZ Onion Small 6 Small XYZ Onion Small 7 Small XYZ Cabbage Small 8 Large XYZ Cabbage Small 9 Small ABC Cabbage Small
has answer: http://stackoverflow.com/a/52243582
upvote count: 1
possible better answer: http://stackoverflow.com/a/52243839
type: Question
has answer: http://stackoverflow.com/a/52243839

http://stackoverflow.com/q/52165314
score: 0
tagged with: python
has title: Sometimes request.files is not working in FLASK while uploading a file
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: python-requests
has comment: http://stackoverflow.com/comment/91668181
tagged with: flask-restful
has body: I am trying to upload a CSV file using FLASK using this below code and I am trying to save the session of that file so that I can use later. if request.method=="POST": text=request.files['file'] text_f=secure_filename(text.filename) text.save(os.path.join("",text_f)) path=os.path.abspath(os.path.join("",text_f)) with open(path) as tickets: ticket=pd.read_csv(tickets) tic_body=ticket['body'] #session['tic_body']=tic_body Below is the HTML Code. &lt;input type="file" class="form-control" id="images" name="file" multiple/&gt; &lt;input type="submit" class="btn btn-labeled btn-primary" value="stop"&gt; Using this I am trying to upload a file I am receiving the below error. werkzeug.exceptions.HTTPException.wrap..newcls: 400 Bad Request: KeyError: 'file' Note: At times ,when I am not using the session I was able to load the file without any error.
type: Question
has comment: http://stackoverflow.com/comment/91671453
has comment: http://stackoverflow.com/comment/91454453
linked to: http://stackoverflow.com/q/19898283
tagged with: flask

http://stackoverflow.com/comment/91258785
has text: thank you very much... u r awesome
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52153985
type: QuestionComment

http://stackoverflow.com/q/52131295
tagged with: python
tagged with: dictionary
tagged with: nlp
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91463765
has comment: http://stackoverflow.com/comment/91411564
type: Question
has title: Tree structure from Stanford CoreNLP parser
tagged with: stanford-nlp
has comment: http://stackoverflow.com/comment/91466587
has comment: http://stackoverflow.com/comment/91397714
has comment: http://stackoverflow.com/comment/91397637
has answer: http://stackoverflow.com/a/52275686
accepted answer: http://stackoverflow.com/a/52275686
linked to: http://stackoverflow.com/q/34395127
has body: I am trying to run StanfordCoreNLP parser and I have the following code: from pycorenlp import StanfordCoreNLP nlp = StanfordCoreNLP('http://localhost:9000') def depparse(text): parsed="" output = nlp.annotate(text, properties={ 'annotators': 'depparse', 'outputFormat': 'json' }) for i in output["sentences"]: for j in i["basicDependencies"]: parsed=parsed+str(j["dep"]+'('+ j["governorGloss"]+' ')+str(j["dependentGloss"]+')'+' ') return parsed text='I shot an elephant in my sleep' depparse(text) This gives me output as: 'ROOT(ROOT shot) nsubj(shot I) det(elephant an) dobj(shot elephant) case(sleep in) nmod:poss(sleep my) nmod(shot sleep) ' To convert the relationships into tree, I am encountered one stackoverflow post Stanford NLP parse tree format. However, the output of the parser is in "bracketed parse (tree)". Hence, I am not sure how can I achieve it. I tried changing the outputformat as well but it gives an error. I also found Python - Generate a dictionary(tree) from a list of tuples and implemented list_of_tuples = [('ROOT','ROOT', 'shot'),('nsubj','shot', 'I'),('det','elephant', 'an'),('dobj','shot', 'elephant'),('case','sleep', 'in'),('nmod:poss','sleep', 'my'),('nmod','shot', 'sleep')] nodes={} for i in list_of_tuples: rel,parent,child=i nodes[child]={'Name':child,'Relationship':rel} forest=[] for i in list_of_tuples: rel,parent,child=i node=nodes[child] if parent=='ROOT':# this should be the Root Node forest.append(node) else: parent=nodes[parent] if not 'children' in parent: parent['children']=[] children=parent['children'] children.append(node) print forest I got the following output [{'Name': 'shot', 'Relationship': 'ROOT', 'children': [{'Name': 'I', 'Relationship': 'nsubj'}, {'Name': 'elephant', 'Relationship': 'dobj', 'children': [{'Name': 'an', 'Relationship': 'det'}]}, {'Name': 'sleep', 'Relationship': 'nmod', 'children': [{'Name': 'in', 'Relationship': 'case'}, {'Name': 'my', 'Relationship': 'nmod:poss'}]}]}]
has comment: http://stackoverflow.com/comment/91401644
score: 0
answer count: 1
tagged with: nested
linked to: http://stackoverflow.com/q/34964878

http://stackoverflow.com/a/52212470
has body: You can use index matching without the need to apply assign df = df.set_index('Name1').assign(Money_1=df2.set_index('Name').Money).reset_index().set_index('Name2').assign(Money_2=df2.set_index('Name').Money).reset_index() Which is actually a one-liner, but is kinda big. The other option is to explicitly write the lines: loc df = df.set_index('Name1') df.loc[:, 'Money_1'] = df2.set_index('Name').Money df = df.reset_index().set_index('Name2') df.loc[:, 'Money_2'] = df2.set_index('Name').Money df.reset_index() Both outputs Name1 Name2 Money_1 Money_2 0 John Jack 40.0 10.0 1 Eva Tom 20.0 80.0 2 Eva Sara 20.0 34.0 3 Carl Sam 77.0 NaN 4 Sam Erin NaN 12.0
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52210329
score: 1

http://stackoverflow.com/a/52254235
has comment: http://stackoverflow.com/comment/91456047
has comment: http://stackoverflow.com/comment/91460404
has comment: http://stackoverflow.com/comment/91471146
score: 0
has body: import psutil from subprocess import PIPE #How to open a process psutil.Popen(['SnippingTool.exe'],stdout=PIPE) #How to kill a process TARGET = "chrome.exe" [process.kill() for process in psutil.process_iter() if process.name() == TARGET]
has comment: http://stackoverflow.com/comment/91456329
answers question: http://stackoverflow.com/q/52253916
has comment: http://stackoverflow.com/comment/91456019
has comment: http://stackoverflow.com/comment/91458963
type: Answer

http://stackoverflow.com/q/52182361
type: AnsweredQuestion
has body: I am working with holt winter method taking help from here. My data format is Year Rate 0 2013 34.700000 1 2013 34.666667 2 2013 34.600000 3 2014 35.300000 4 2014 34.180000 Below is my code import pandas as pd #Importing data df = pd.read_csv('/home/rajnish.kumar/eclipse-workspace/ShivShakti/Result/weeklyDatarateyearonly/part-00000-971f46d7-a97d-4a7e-be41-dc840c2d0618-c000.csv') df.Timestamp = pd.to_datetime(df.Datetime,format='%Y') But I am getting this error: AttributeError: 'DataFrame' object has no attribute 'Datetime'
type: Question
has answer: http://stackoverflow.com/a/52183639
accepted answer: http://stackoverflow.com/a/52183639
tagged with: dataframe
upvote count: 3
answer count: 2
tagged with: pandas
has title: Pandas AttributeError: 'DataFrame' object has no attribute 'Datetime'
downvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/66257847
tagged with: python
has answer: http://stackoverflow.com/a/66257847
has comment: http://stackoverflow.com/comment/91314659
score: 2

http://stackoverflow.com/comment/91352628
type: Comment
comment on: http://stackoverflow.com/a/52163728
has text: I think gather_nd will help me. You are right about batch. I could write for _ in range(batch). The only problem is that I don't know what to write for batch if I can't write first dimension.
type: AnswerComment
score: 0

http://stackoverflow.com/q/52219864
has comment: http://stackoverflow.com/comment/91401707
type: Question
has answer: http://stackoverflow.com/a/52219908
tagged with: matrix-multiplication
tagged with: numpy
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91591459
has title: How to multiply each row of an array with all rows of an array element-wise in Python
tagged with: python
accepted answer: http://stackoverflow.com/a/52219908
type: AnsweredQuestion
has body: I need to multiply each row of an array A with all rows of an array B element-wise. For instance, let's say we have the following arrays: A = np.array([[1,5],[3,6]]) B = np.array([[4,2],[8,2]]) I want to get the following array C: C = np.array([[4,10],[8,10],[12,12],[24,12]]) I could do this by using for loop but I think there could be a better way to do it. EDIT: I thought of repeating and tiling but my arrays are not that small. It could create some memory problem.

http://stackoverflow.com/q/52114682
has answer: http://stackoverflow.com/a/52131867
has body: I'm tring to approximate an empirical cumulative distribution function (ECDF I want to approximate) with a smooth function (with less than 5 parameter) such as the generalized logistic function. However, using scipy.optimize.curve_fit, the fitting operation gives really bad approximations or it doesn't work at all (depending on the initial values). The variable series represents my data stored as pandas.Series. from scipy.optimize import curve_fit def fit_ecdf(x): x = np.sort(x) def result(v): return np.searchsorted(x, v, side='right') / x.size return result ecdf = fit_ecdf(series) def genlogistic(x, B, M, Q, v): return 1 / (1 + Q * np.exp(-B * (x - M))) ** (1 / v) params = curve_fit(genlogistic, xdata = series, ydata = ecdf(series), p0 = (0.1, 10.0, 0.1, 0.1))[0] Should I use another type of function for the fit? Are there any code mistakes? UPDATE - 1 As asked, I link to a csv containing the data. UPDATE - 2 After a lot of search and trial and error I find out this function f(x; a, b, c) = 1 - 1 / (1 + (x / b) ** a) ** c with a = 4.61320000, b = 2.94570952, c = 0.5886922 which fits a lot better than the other one. The only problem is the little step that the ECDF shows near x=1. How can I modify f to improve the quality of the fit? I was thinking of adding some sort of function that is "relevant" only in those kind of points. Here are the graphical results of the fit where the solid blue line is the ECDF and the dotted line represents the (x, f(x)) points.
has comment: http://stackoverflow.com/comment/91204328
favorite count: 0
has comment: http://stackoverflow.com/comment/91182947
has comment: http://stackoverflow.com/comment/91207677
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/52131867
tagged with: curve-fitting
tagged with: python
has comment: http://stackoverflow.com/comment/91207753
score: 0
has comment: http://stackoverflow.com/comment/91186455
upvote count: 1
downvote count: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/91207864
has comment: http://stackoverflow.com/comment/91212287
has comment: http://stackoverflow.com/comment/91208506
has comment: http://stackoverflow.com/comment/91206841
has answer: http://stackoverflow.com/a/52132759
has comment: http://stackoverflow.com/comment/91207953
has comment: http://stackoverflow.com/comment/91182541
possible better answer: http://stackoverflow.com/a/52132759
has title: Unable to fit an ECDF using scipy.optimize.curve_fit
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91193678
has comment: http://stackoverflow.com/comment/91204568

http://stackoverflow.com/comment/91274576
score: 1
has text: Your code is easy to understand, and does exactly what it should do. The few extra lines shouldn't matter too much.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52162549

http://stackoverflow.com/q/52242093
upvote count: 2
tagged with: python
tagged with: dictionary
score: 2
type: AnsweredQuestion
has body: I need to sort this dictionary by the second value in the list. That is 341 for the first dictionary "key-value" pair. {'Ariana Greenblatt': ['Young Gamora', 341], 'Stan Lee': ['Schoolbus Driver', 335], 'Anthony Mackie': ['Sam Wilson / Falcon', 70], 'Chadwick Boseman': ["T'Challa / Black Panther", 46], 'Letitia Wright': ['Shuri', 90], 'Ameenah Kaplan': ["Gamora's Mother", 342], 'Florence Kasumba': ['Ayo', 114], 'Carrie Coon': ['Proxima Midnight (voice)', 329], 'Samuel L. Jackson': ['Nick Fury (uncredited)', 332], 'Kenneth Branagh': ['Asgardian Distress Call (voice) (uncredited)', 357], 'Chris Evans': ['Steve Rogers / Captain America', 2], 'Chris Hemsworth': ['Thor Odinson', 6], 'Tom Vaughan-Lawlor': ['Ebony Maw', 97], 'Robert Pralgo': ['Thanos Reader', 344]} From a few Stack Overflow questions I found OrderedDict. Could it be used for this purpose? But I was unable to achieve this. PS: I want to get this sorted dictionary as dictionary, not tuple.
has title: How to search this dictionary file?
has answer: http://stackoverflow.com/a/52242145
type: Question
answer count: 2
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/52242300
has answer: http://stackoverflow.com/a/52242300
accepted answer: http://stackoverflow.com/a/52242145
tagged with: python-3.x

http://stackoverflow.com/comment/91446770
score: 0
has text: The issue here is variable scope. The 'question' variable in your function is not the referring to the same thing as 'question' in your loop. What you want to do is return a value from the function, and then print it in the loop.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52249270

http://stackoverflow.com/q/52114124
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: I looked at various solutions using csv, txt,py files, but could not accomplish quite what I want, which is: I would like keep a list of integers in a separate file append new entries to the list through user input to that separate file and read them back the updated version as a list, in int form so calculations can be made, from that file. I've been trying through the following code; print('Enter the result of your last reading=') newReading = input() reading = [int(newReading)] with open('avg.py', 'a') as f: f.write('reading = ' . reading) from avg.py import reading as my_list print(my_list)
score: -3
has comment: http://stackoverflow.com/comment/91178785
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52117451
downvote count: 3
type: Question
accepted answer: http://stackoverflow.com/a/52117451
has title: Writing, updating and reading lists to and from external files with user inputs

http://stackoverflow.com/comment/91256031
has text: what is holding your text? a browser?
type: Comment
comment on: http://stackoverflow.com/q/52152830
type: QuestionComment
score: 1

http://stackoverflow.com/q/52131883
has comment: http://stackoverflow.com/comment/91215440
tagged with: assistant
has title: os.system("mpg123 audio.mp3") - mpg123 doesnt work
has comment: http://stackoverflow.com/comment/91214349
type: Question
tagged with: python
tagged with: audio
has comment: http://stackoverflow.com/comment/91214994
has answer: http://stackoverflow.com/a/58154397
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/112379862
has body: So right now I'm trying to create a sound assistant (ok google, Alexa blah blah) in python. Works fine, except the sound output from that assistant. In the youtube Tutorial the dude uses os.sytsem("mpg123 audio.mp3"), the audio.mp3 is an mp3 in the same folder as the python file, and it's being created and output with these lines tts = gTTS(text=audio, lang="de") tts.save("audio.mp3") os.system("mpg123 audio.mp3") But when I run that it gives me the error that mpg123 either has been written wrong, or it couldn't be found. I installed it with pip though. So what can I do about that? Do I want my SOUND assistant to only response in text...are there other audio output ways besides mpg123?
has comment: http://stackoverflow.com/comment/91214577
type: UnansweredQuestion

http://stackoverflow.com/q/52144909
tagged with: diacritics
has title: Cannot open files with accents using Python 2.7
has comment: http://stackoverflow.com/comment/91240356
has answer: http://stackoverflow.com/a/52145190
has comment: http://stackoverflow.com/comment/91244684
has comment: http://stackoverflow.com/comment/91240329
tagged with: python
linked to: http://stackoverflow.com/q/10180765
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/10180765
upvote count: 1
type: Question
tagged with: filenames
has body: I try to read all the files in a directory, but as they contain spaces and accents, I get errors (already read many posts on SO but cannot find any answer) this returns a list of files files = [y for x in os.walk(".") for y in glob(os.path.join(x[0], '*.pdf'))] but as I try to open them one by one for file in files: with open(file,"r") as f: I get these kind of errors (I obfuscated the letters cos it's confidential): IOError: [Errno 22] invalid mode ('r') or filename: '.\abcd?efgh (hijk? lmnop).pdf' I believe the issues are caused by the accents but since it's python that gives me the the file names, I dont understand why they are not compatible with "open()" regards how can I fix this ?
score: 1
has comment: http://stackoverflow.com/comment/91239858
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91240013
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/91305271
type: QuestionComment
comment on: http://stackoverflow.com/q/52164003
has text: @Bryan Oakley It seems like the custom event that I generate upon Telnet session status change doesn't fire anything. But, I also don't get any exception. I suppose that this is not the way to get an update regarding a status change.
score: 0
type: Comment

http://stackoverflow.com/comment/91384923
has text: the resulting object that you claim to be after is a `set`. Are you sure you want a set? If you originally started out with `Counter({5: 3, 3: 5})` you would get only `{15}`. Are you fine with that?
score: 1
comment on: http://stackoverflow.com/q/52218107
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91444914
comment on: http://stackoverflow.com/q/52245721
type: Comment
type: QuestionComment
has text: @MaharshiRoy I saw that post. That method (presumably) works should I train with top_k_accuracy as a metric, but when I try to do so afterwards, it doesn't work.
score: 0

http://stackoverflow.com/q/52194406
has comment: http://stackoverflow.com/comment/91338753
has title: Best-case scenario for saving models files in Django project
has comment: http://stackoverflow.com/comment/91338673
has body: I have a question about good practice for saving images in Django project. Let's say we have two apps inside Django project appOne and appTwo. Should I save my images for every app to the same root folder or every app should have a separate folder for images? And is there a benefit if we create a folder for images for every model inside an app (if that model saves images). I know that there's not one correct answer but there is always most useful case scenario in the long run. p.s. I came from asp.net world and I fall in love with Django and Python
score: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: django
type: Question

http://stackoverflow.com/a/52270855
accepted answer of: http://stackoverflow.com/q/52266886
has body: You could do something like this @bot.event async def on_message(message): prefix = re.findall('([;]|[-]|[=]+)', message.content.lower()) if prefix and message.channel.id == "405815888177266689": await bot.delete_message(message) muted_bots = ['bot_1_id','bot_2_id'] async for msg in bot.logs_from(bot.get_channel("405815888177266689"), limit=4): if msg.author.id in muted_bots: await bot.delete_message(msg) where after someone writes a message with that prefix and it gets deleted, it checks for the last number of messages (whatever you put the limit to depending on how many bots respond) and checks if whoever wrote that is in your muted_bots id list.
answers question: http://stackoverflow.com/q/52266886
score: 0
has comment: http://stackoverflow.com/comment/91511052
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91510932
type: Answer
has comment: http://stackoverflow.com/comment/91511114
has comment: http://stackoverflow.com/comment/91510488
has comment: http://stackoverflow.com/comment/91510095

http://stackoverflow.com/comment/91453619
type: Comment
comment on: http://stackoverflow.com/a/52250845
score: 0
type: AnswerComment
has text: i don't think you have lista1[2] what did you expect to get returned ? @OsvaldoBouché

http://stackoverflow.com/q/52261561
favorite count: 0
has comment: http://stackoverflow.com/comment/91470871
has title: Reversing a list of elements by indicator
tagged with: python
has answer: http://stackoverflow.com/a/52261619
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/91470827
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/52261624
type: Question
accepted answer: http://stackoverflow.com/a/52261619
possible better answer: http://stackoverflow.com/a/52261624
has body: I have a list containing: [1,2,3,4,0,9,8,7,6] and i want to reverse the values in the list based on an indicator which is '0' in the list. Hence, for the elements before the '0', i want them to be reversed. and the element after '0' follows which will get me: [4,3,2,1,0,6,7,8,9] I tried using list[::-1] but it doesn't work if i were to condition it based on that indicator. Would appreciate some help on this.
answer count: 2
downvote count: 0

http://stackoverflow.com/a/52252519
accepted answer of: http://stackoverflow.com/q/52252477
answers question: http://stackoverflow.com/q/52252477
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I think need to remove assign to variable eMean in eMean = ("%.2f" % eMean) and if necessary cast values to floats: mod = float(df.consent.iloc[0]) eMean = df['emit'].astype(float).mean() print ("%.2f" % eMean) diff1 = eMean - mod diff = diff1 / mod

http://stackoverflow.com/comment/91333767
type: Comment
has text: Thanks Bazinga. This is close to what I have attempted. However, whenever you apply `y=np.unique(y)` it reorders the array so that it is in ascending order. To see the issue, if you look in your array, at the `x` array coordinate `-100` and the `y` coordinate `30`, the value of `z` should be `-0.3` (next to last value in all three vectors), but it looks to be around `-0.7` (top right corner of graph). Please correct me if I'm missing something.
comment on: http://stackoverflow.com/a/52187744
score: 0
type: AnswerComment

http://stackoverflow.com/a/52123077
accepted answer of: http://stackoverflow.com/q/52122948
score: 0
type: AcceptedAnswer
type: Answer
has body: Just use dictionary like :- dataframe_dict = {} for seriesName in newSeries0: seriesName=fred.get_series_first_release(seriesName) seriesName=seriesName.resample('D').fillna('ffill') dataframe_dict[seriesName]=seriesName df = pd.DataFrame() for name in dataframe_dict: df[name] = dataframe_dict[name]
answers question: http://stackoverflow.com/q/52122948

http://stackoverflow.com/q/52137238
has title: Scrape with python a website in which google log in is needed
has body: First of all, I think it's worth saying that, I know there are a bunch of similar questions but none of them works for me... I'm trying to scrape user information from a website which needs to login with google account first. In my tests I use scraper my user settings from this page as example. The main page is 'https://www.futmondo.com' and the target page is 'http://www.futmondo.com/user/settings' Here are what I've tried: import requests from bs4 import BeautifulSoup # TEST 1 payload = { 'action': 'login', 'identifier': 'xxxxxxxxx@gmail.com', 'password': 'xxxxxxxxx' } # TEST 2 payload = { 'action': 'login', 'username': 'xxxxxxxxx@gmail.com', 'password': 'xxxxxxxxx' } with requests.Session() as s: s.post('https://www.futmondo.com', data=payload) base_page = s.get('http://www.futmondo.com/user/settings') soup = BeautifulSoup(base_page.content, 'html.parser') print(soup.title) print(soup.text) But I'm getting the html code without my user values. I think that the problem is that I don't know which is the "main log in page", when I click on "Jugar" (Play) they redirect me to another page to write user (First user web,First user html code), and when I write user they redirect me to another more page to write password (Second password web,Second password html code). Also I've searched in the html code once I've log in to find these "username" and "password" keys but I only find this: html code once logged in Also I've read some discussions about differences between HTTP Authentication and cookies. Still none of them worked. Please any help would be appreciated. Thank you very much.
has comment: http://stackoverflow.com/comment/91224915
has comment: http://stackoverflow.com/comment/91224186
type: Question
has comment: http://stackoverflow.com/comment/91494381
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91230738
tagged with: parsing
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: html-parsing
has comment: http://stackoverflow.com/comment/91230578
has comment: http://stackoverflow.com/comment/91230633

http://stackoverflow.com/comment/91484076
type: AnswerComment
score: 0
type: Comment
has text: @MarkD You're welcome! I already wondered how this calculation on daily data can be SLOW, SLOW, SLOW ;) 8000 rows is really way to little to earn the overhead of creating a pool back in the first place.
comment on: http://stackoverflow.com/a/52247585

http://stackoverflow.com/a/52189631
answers question: http://stackoverflow.com/q/52189478
has comment: http://stackoverflow.com/comment/91329401
has comment: http://stackoverflow.com/comment/91329015
has comment: http://stackoverflow.com/comment/91329228
has body: The stack trace is not available, so I have to guess, but it seems to be the line in the exception handler which uses responsedata: print ("page #{0} run #{1} failed. Returned status code {2}. Reason: {3}. Msg: {4}. Retry.".format(page, n, responsedata.status_code, responsedata.reason, sys.exc_info()[0])) That is going to fail of the exception was raised before the assignment to responsedata was made. You should never use within except block the variables which you initialize within the try block, because they don't have to be available there. BTW, I suggest not using lines which are that long.
has comment: http://stackoverflow.com/comment/91329060
has comment: http://stackoverflow.com/comment/91329110
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91328959
has comment: http://stackoverflow.com/comment/91344681
has comment: http://stackoverflow.com/comment/91329268
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/91329078

http://stackoverflow.com/a/52118860
has comment: http://stackoverflow.com/comment/91283297
type: Answer
has body: The name you need to patch isn't src.main.utils.a_plus_b, but src.main.myfile.a_plus_b, since that is what method_under_test uses. @patch('src.main.myfile.a_plus_b') def test(self, mock_a_plus_b): mock_a_plus_b.side_effect = self.a_plus_b_side_effect method_under_test()
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/91282314
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52118765
answers question: http://stackoverflow.com/q/52118765

http://stackoverflow.com/comment/91498033
score: 0
has text: instead of generating " _abc.txt " , can we have a user input prompt to save the file by the name of our choice ? any idea how can we do that ?
type: AnswerComment
comment on: http://stackoverflow.com/a/52258468
type: Comment

exit
tags question: http://stackoverflow.com/q/52246412
type: Tag
tag name: exit

http://stackoverflow.com/comment/91239017
has text: The approach I was going to suggest to deal with the gaggle of types (of both `bytes` and `str`) would have been something similar to what `traceback2` does, basically every non-ascii characters will simply be rendered as `\x` escaped representation, i.e. `[u"Exception: b'\\xe2\\x80\\xa2'\n"]`. Python 2 forces a lot of unhealthy habits because zero distinction between human readable text and raw bytes, resulting in the **internal API** being completely inconsistent with how those types are handled (manifests in stdlib breakages). I can't wait till Python 2 is completely dropped everywhere.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52143333
score: 0

http://stackoverflow.com/q/52154509
has comment: http://stackoverflow.com/comment/91259491
has comment: http://stackoverflow.com/comment/91259470
score: -1
accepted answer: http://stackoverflow.com/a/52154697
tagged with: numpy
has comment: http://stackoverflow.com/comment/91259424
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91259364
favorite count: 0
has comment: http://stackoverflow.com/comment/91259412
has comment: http://stackoverflow.com/comment/91259433
has title: Converting a column having numpy arrays convert it into a numpy array with dtype as object
tagged with: pandas
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91259534
has answer: http://stackoverflow.com/a/52154697
has comment: http://stackoverflow.com/comment/91259900
downvote count: 1
type: Question
has body: I have a column in a dataframe having numpy arrays of length 10. My dataframe is like this: 0 [2.0, 1246.0, 82.0, 43.0, 569.0, 46.0, 424.0, ... 1 [395.0, 2052.0, 1388.0, 8326.0, 5257.0, 176.0,... 10 [4.0, 1.0, 13.0, 1409.0, 7742.0, 259.0, 1856.0... 100 [4.0, 87.0, 1595.0, 706.0, 2935.0, 6028.0, 442... 1000 [45.0, 582.0, 124.0, 6530.0, 6548.0, 748.0, 61... Name: embedding1, dtype: object When I am converting it into a numpy array of array using this: input = np.asarray(df.tolist()) It is giving the array like this: array([array([ 2., 1246., 82., 43., 569., 46., 424., 446., 1054., 39.]), array([4.0000e+00, 1.0000e+00, 1.3000e+01, 1.4090e+03, 7.7420e+03, 2.5900e+02, 1.8560e+03, 3.6181e+04, 4.2000e+01, 8.9000e+02]), ..., array([4.000e+00, 1.000e+00, 1.300e+01, 2.900e+01, 4.930e+02, 2.760e+02,1.100e+01, 6.770e+02, 6.740e+02, 5.806e+03]),], dtype=object) The type it is giving is object. I want the object as float because it is giving the shape(1000,) but I want shape as (1000,10). I have tried using this: input1 = np.asarray(df1.tolist(),dtype=np.float) But it is giving the following error: ValueError: setting an array element with a sequence. How to solve this? PS: All the elements of the dataframe's row numpy array are of float type

gmail
type: Tag
tags question: http://stackoverflow.com/q/52144829
tags question: http://stackoverflow.com/q/52246770
tags question: http://stackoverflow.com/q/52206251
tag name: gmail

http://stackoverflow.com/comment/91427710
type: AnswerComment
type: Comment
has text: Yeah no that i understand, ive always just wondered if the workaround basics (so header recreation, etc..) still worked
comment on: http://stackoverflow.com/a/52239520
score: 0

http://stackoverflow.com/q/52262155
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91490076
tagged with: python-requests
tagged with: uwsgi
type: Question
has answer: http://stackoverflow.com/a/52263134
tagged with: ssl-certificate
has body: I am running Django REST API project through uwsgi in nginx webserver. Also configured ssl for HTTPS. In project directory there are certificate &amp; key files (as below), which helps to establish the secured HTTPS connection. /my-project/test-cert.pem /my-project/test-cert.KEY I have checked from browser, the https://mysite.domain.com/ is returning all the APIs, and the https://mysite.domain.com/admin/ is returning the Django Admin page. This means the Django is responding properly. I am facing error in calling my internal APIs through external web URLs. https://mysite.domain.com/api/account/ is my web url which will call the https://mysite.domain.com/user-list-details/api internally. Both the above APIs (/api/account/ &amp; /user-list-details/) are mentioned in my Django urls.py. The sequence is that API-1 will be called from my Angular front-end and API-2 will be called internally by Django REST. API-2 will fetch data from DB and returns back to Angular through API-1. This structure is basically designed to serve the purpose of our business logic and was working fine for HTTP version of my project but now I am facing issue after implementing HTTPS. Sample code of internal API call: import requests # I have tried with three different certificates available. CERT_1 = '/etc/ssl/certs/ca-bundle.crt' CERT_2 = '/my-project/test-cert.pem' CERT_3 = '/tech/lib/python3.5/site-packages/certifi/cacert.pem' url = 'https://mysite.domain.com/user-list-details/' apisession = requests.Session() response = apisession.get(url, verify=CERT_1) # &lt;= Error in this line Error: HTTPSConnectionPool(host='', port=443); Max reties exceeded with url: /user-list-details/?query=all&amp;name=Jhon (caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)'),)) I have tried using the bundle certificate (CERT_1), but for that I am getting 504 error. I tried verify=False though not recommended, but getting 504 error. I have checked similar posts as …
upvote count: 2
answer count: 1
favorite count: 0
type: UnansweredQuestion
has title: SSL: CERTIFICATE_VERIFY_FAILED Error in Django running through uwsgi on nginx webserver
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91658467
linked to: http://stackoverflow.com/q/10667960

http://stackoverflow.com/comment/91303893
type: Comment
has text: @abarnert. I had a pointless blurb about lists. Got rid of the whole section. Fixed now.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52176646

http://stackoverflow.com/comment/91443744
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52247954
has text: Can you give an example of your `html` file? Maybe you have all that junk data in one line, and if you `skiprows=14` you end up skipping other 13 lines which are already data in your table
score: 2

http://stackoverflow.com/comment/91445706
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52246874
has text: As far as I understand it, it doesn't matter at what distance you do the calibration... in fact you should move the chessboard around in the 3D space (tilting and moving forward/back) to get a good measure. What it does is determine the distortion caused by the optics, so that you can undistort the input and get a uniform (linear) image to make measurements on (or stack). The characteristics of the optics will stay the same no matter how far from the imaged surface you are (assuming it's fixed, not some mechanized auto-focus). -- It might be close if anything is adjusted, but best if static.
score: 0

http://stackoverflow.com/q/52148916
upvote count: 1
has body: I am new to Python. I have learned the If else statement, sto this exercise has to be with the If else and not with something more. Write a program which asks the user to type an integer and then prints "Yes" if that integer is divisible by 3, otherwise prints "No" My code is this: user_input = input("Type an integer: ") user_int = int(user_input) if user_int / 3: print("Yes) else: print("No") I think I messed up the if statement, but really I cannot figure it out.
type: Question
has answer: http://stackoverflow.com/a/52149566
has answer: http://stackoverflow.com/a/52148958
has answer: http://stackoverflow.com/a/52149742
possible better answer: http://stackoverflow.com/a/52148958
answer count: 3
linked to: http://stackoverflow.com/q/8002217
score: -1
duplicate of: http://stackoverflow.com/q/8002217
tagged with: integer
favorite count: 0
tagged with: input
accepted answer: http://stackoverflow.com/a/52149742
tagged with: python
has comment: http://stackoverflow.com/comment/91247953
type: AnsweredQuestion
has title: ask the user to type an integer and then prints "Yes" if that integer is divisible by 3, otherwise prints "No" (Python)
downvote count: 2

http://stackoverflow.com/q/52162190
has answer: http://stackoverflow.com/a/52162277
tagged with: python
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/52162277
type: AnsweredQuestion
upvote count: 0
has title: Merge two list of tuples with unequal length
type: Question
favorite count: 0
score: -1
tagged with: python-3.x
has body: How can one merge two unequal list of tuples: x = [('Animal', 1), ('Bird', 2)] y = [('Animal', 'Dog'), ('Animal', 'Cat'), ('Bird', 'Parrot')] ..to get.. [('Animal', 1, 'Dog'), ('Animal', 1, 'Cat'), ('Bird', 2, 'Parrot')] ..using list comprehension?

http://stackoverflow.com/comment/91343500
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52185038
type: Comment
has text: Thanks Harshita, now i get a better understanding on how to use variables, but unfortunately i get an error. "Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1544, in __call__ return self.func(*args) File "script.py", line 188, in saveValues obj = LoginWindow() File "script.py", line 23, in __init__ self.init_window() File "script.py", line 28, in init_window self.master.title("FairIT Login") AttributeError: 'NoneType' object has no attribute 'title'

http://stackoverflow.com/a/52165418
answers question: http://stackoverflow.com/q/52165285
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91343885
downvote count: 0
has body: In Python 2.x print is a statement, not a function, so you can't change its behavior. You can use a future statement to make it a function first (like in Python 3.x) and override that: from __future__ import print_function counter = 0 _print = print # save a reference to the built-in print() def print(*args, **kwargs): global counter counter += 1 _print(*args, **kwargs)
upvote count: 2

http://stackoverflow.com/q/52255191
has comment: http://stackoverflow.com/comment/91458063
has title: Sending a CV::Mat from C++ to python script function
answer count: 0
type: Question
tagged with: python
tagged with: c++
score: 0
has comment: http://stackoverflow.com/comment/91463022
has body: I am trying to pass a cv::Mat object from C++ code to a python script to have some manipulation on it there (for simplification issue I will just post the code to just display the image). In the c++ code I did the following: import_array(); Mat image = imread("test.jpg"); PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue; pName = PyUnicode_FromString("test"); if (pName == NULL) { PyErr_Print(); break ; } pModule = PyImport_Import(pName); if (pModule == NULL) { PyErr_Print(); break; } pDict = PyModule_GetDict(pModule); pFunc = PyDict_GetItemString(pDict, "check"); if (pFunc == NULL) { PyErr_Print(); break; } pArgs = PyTuple_New(1); npy_intp dimensions[3] = {image.rows, image.cols, image.channels()}; pValue = PyArray_SimpleNewFromData(image.dims + 1, (npy_intp*)&amp;dimensions, NPY_UINT8, image.data); PyTuple_SetItem(pArgs, 0, pValue); PyObject* pResult = PyObject_CallObject(pFunc, pArgs); if(pResult == NULL) LERROR&lt;&lt;"error calling"; on the python side import cv2 import numpy as np def check(a): image = a print (image.shape) print (type(image)) cv2.imshow("win",a) return 0 shape is printed as (width height channels), type is shown as ndarray but code is crashing on imshow function. I tried cv2.imread("test.jpg") on the python side and got same results when printing shape and type and imshow did work, so I guess there is something missing when trying to get the data from c++. Is that the correct way or am I missing something?
tagged with: opencv
type: UnansweredQuestion
tagged with: numpy
has comment: http://stackoverflow.com/comment/91461989
has comment: http://stackoverflow.com/comment/91460957

http://stackoverflow.com/comment/91276540
type: AnswerComment
comment on: http://stackoverflow.com/a/52163365
has text: *"nothing is every copied implicitly in Python"* – Right, which is why implicitly making a copy of the list in the constructor is arguably the surprising behaviour.
score: 0
type: Comment

http://stackoverflow.com/q/52238521
tagged with: tensorflow-datasets
has answer: http://stackoverflow.com/a/52240106
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52240106
upvote count: 2
tagged with: machine-learning
has title: Tensorflow csv dataset usage
has body: I have a csv file with the following format and data: ID nr1 nr2 nr3 nr4 nr5 next_nr 1 1 2 3 4 5 6 2 2 3 4 5 6 7 3 3 4 5 6 7 8 4 4 5 6 7 8 9 5 5 6 7 8 9 10 6 6 7 8 9 10 11 7 7 8 9 10 11 12 8 8 9 10 11 12 13 9 9 10 11 12 13 14 10 10 11 12 13 14 15 So, there are 10 rows including my train data. And I want to use tf.contrib.data.CsvDataset to read the data. Here is the example code for reading it: import tensorflow as tf import numpy as np ITERATOR_BATCH_SIZE = 2 NR_EPOCHS = 3 train1_path = 'train1_short.csv' dataset = tf.contrib.data.CsvDataset(train1_path, [tf.float32, tf.float32, tf.float32, tf.float32, tf.float32, tf.float32, tf.float32], header=True) dataset = dataset.batch(ITERATOR_BATCH_SIZE) with tf.Session() as sess: for i in range (NR_EPOCHS): print('\nepoch: ', i) iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() while True: try: data_and_target = sess.run([next_element]) except tf.errors.OutOfRangeError: break print("\n\n", data_and_target) When I run this code, I expect the output to include 2 rows of data in each batch. But the data I get looks pretty strange. Here is the output from the first epoch: epoch: 0 [(array([1., 2.], dtype=float32), array([1., 2.], dtype=float32), array([2., 3.], dtype=float32), array([3., 4.], dtype=float32), array([4., 5.], dtype=float32), array([5., 6.], dtype=float32), array([6., 7.], dtype=float32))] [(array([3., 4.], dtype=float32), array([3., 4.], dtype=float32), array([4., 5.], dtype=float32), array([5., 6.], dtype=float32), array([6., 7.], dtype=float32), array([7., 8.], dtype=float32), array([8., 9.], dtype=float32))] [(array([5., 6.], dtype=float32), array([5., 6.], dtype=float32), array([6., 7.], dtype=float32), array([7., 8.], dtype=float32), array([8., 9.], dtype=float32), array([ 9., 10.], dtype=float32), array([10., 11.], dtype=float32))] [(array([7., 8.], dtype=float32), array([7., 8.], dtype=float32), array([8., 9.], dtype=float32), array([ 9., 10.], dtype=float32), array([10., 11.]…
tagged with: tensorflow
type: Question
score: 2
answer count: 1
downvote count: 0
tagged with: dataset
favorite count: 0

http://stackoverflow.com/a/52130502
has body: You can simplify your code as follow, and to avoid unnecessary recursion in the code: operations = { "+": lambda x, y: x + y, "-": lambda x, y: x - y, "/": lambda x, y: x / y, "*": lambda x, y: x * y } continue_calculation = "" while True: calc_again = input('''Do you want to calculate again?Please type Y for YES or N for NO.''') if calc_again == "n" or calc_again == "N": break operation = input('''Please type in the math operation you would like to complete: + for addition - for subtraction * for multiplication / for division ''') number_1 = int(input('Please enter the first number: ')) number_2 = int(input('Please enter the second number: ')) try: print(operations[operation](number_1, number_2)) except: print('You have not typed a valid operator, please run the program again.')
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52130313

http://stackoverflow.com/comment/91306628
type: AnswerComment
has text: When I try setting the index, I actually get " KeyError: " ['Date'] not in index " which seems confusing as that is what I'm trying to set.
type: Comment
comment on: http://stackoverflow.com/a/52178054
score: 0

http://stackoverflow.com/q/52128445
upvote count: 1
downvote count: 1
has body: I have a dataset, df. I extracted another dataset from df, df_rec, based on a certain condition. I can access the indexes of df_rec by df_rec.index. Now, I want to create a column in df, where the index in df if matches with indexes in df_rec should be populated as 1 otherwise 0. Any help, will be appreciated. I am thinking, like, which throws error. df['reccurences'] = 0 df['reccurences'][df.index in df_rec.index] = 1
type: Question
type: AnsweredQuestion
score: 0
has title: Pandas Indexing and Column Creation
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/52128508
tagged with: data-science
favorite count: 0
has comment: http://stackoverflow.com/comment/91207493
has comment: http://stackoverflow.com/comment/91207378
accepted answer: http://stackoverflow.com/a/52128508
has comment: http://stackoverflow.com/comment/91207391
tagged with: python

http://stackoverflow.com/a/52195764
has comment: http://stackoverflow.com/comment/91342099
has comment: http://stackoverflow.com/comment/91364593
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52195649
has comment: http://stackoverflow.com/comment/91341735
has body: There are multiple things about your code that are confusing but not actually wrong, like the fact that you shadow your run method with an instance attribute with the value 0… The fact that you’re using tkinter from a background thread actually is wrong, and can lead to a hang on some platforms. But it probably isn’t the cause here. Your actual problem is the queue logic. Think about how it works: Your main thread checks whether the thread is running. Your main thread calls output_q.get(), which blocks forever until something gets put on the queue. Your background thread gets a destroy event. Your background thread sets run = 0 and exits. Your main thread is still waiting on the queue forever, so it will never see that run is now falsely, so it will never exit. One way to solve this is to use the same queue that you’re already using to wake up the main thread so it can see that you’ve quit: def callback(self): self.run = 0 self.root.quit() self.root.destroy() self.output_q.put(None) Of course now you can’t just use result[0], because result could be None, so you need to add: if result is not None: But there’s still a problem: variables that you change in one thread are guaranteed to eventually be visible to other threads, but not immediately. What happens if the main thread doesn’t see the change until after its gone to block on the queue again? It’s stuck forever. I’m pretty sure this will work on CPython, but that isn’t guaranteed, it just happens to be true by accident, and it may not work on a different implementation like Jython. The right way to fix this is to synchronize all access to any variables you want to share between threads by using a Lock or Condition or Queue or other sync object. But notice that you don’t actually need the while app.run: test anymore, because you can just do this: while True: result = app.output_q.get() if result is None: break print result[0] And then you don’t have to worry about races. Your code is simpler, and guaranteed correc…
has comment: http://stackoverflow.com/comment/91341654
downvote count: 0
has comment: http://stackoverflow.com/comment/91364662
has comment: http://stackoverflow.com/comment/91364735
has comment: http://stackoverflow.com/comment/91342023
score: 1
has comment: http://stackoverflow.com/comment/91341643
has comment: http://stackoverflow.com/comment/91376314

http://stackoverflow.com/comment/91509561
has text: i'll elaborate in comments, but the example code you provide doesn't address my designs
comment on: http://stackoverflow.com/a/52265974
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52189362
score: 4
has comment: http://stackoverflow.com/comment/93338643
upvote count: 4
answers question: http://stackoverflow.com/q/52189202
downvote count: 0
type: Answer
has body: Try change last line to: config, unknown = parser.parse_known_args() This will parse only known arguments (ignoring every unknown). as in this question: Python argparse ignore unrecognised arguments
has comment: http://stackoverflow.com/comment/93491832

http://stackoverflow.com/comment/91460160
comment on: http://stackoverflow.com/q/52234474
has text: The issue was that I couldn't find a library that does the parsing so I am having to resort to regex manipulation and re.sub
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91315969
has text: @tashakori Done. Added my full bot code.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52173331

http://stackoverflow.com/a/52262112
type: Answer
score: 1
upvote count: 1
downvote count: 0
has body: You can use itertools.combinations for getting all the unique pairs of files in the directory and a set to determine similarities between files as done in this solution. Also the glob package has better functionality than os.listdir as it lists proper paths to files in the given directory: import itertools import glob path = ("/path/to/files/") for files in itertools.combinations(glob.glob(path + '*'), 2): file1, file2 = map(open, files) similarities = set(file1).intersection(file2) if similarities: print('_'.join(files), 'have {} in common'.format(','.join(similarities))
answers question: http://stackoverflow.com/q/52261100

http://stackoverflow.com/comment/91180589
comment on: http://stackoverflow.com/q/52115036
type: Comment
score: 0
has text: seems like you are not sending `name` from the iOS app
type: QuestionComment

open-source
tags question: http://stackoverflow.com/q/52249488
tag name: open-source
type: Tag

http://stackoverflow.com/comment/91487789
comment on: http://stackoverflow.com/q/52270187
score: 0
type: Comment
has text: `None and any-object` is `None`, since `any-object` is ignored. It is normal for programming languages to evaluate from left-to-right, with `and` it keeps going until something is "falsey" (like `None`), with `or` it keeps going until something is "truthy".
type: QuestionComment

http://stackoverflow.com/q/52265021
has comment: http://stackoverflow.com/comment/91478465
has comment: http://stackoverflow.com/comment/91478162
has comment: http://stackoverflow.com/comment/91478109
answer count: 3
tagged with: sql
downvote count: 0
has comment: http://stackoverflow.com/comment/91478328
favorite count: 0
tagged with: postgresql
has answer: http://stackoverflow.com/a/52265244
tagged with: python
has comment: http://stackoverflow.com/comment/91478105
score: 2
has comment: http://stackoverflow.com/comment/91478424
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91478222
upvote count: 2
has comment: http://stackoverflow.com/comment/91478147
has answer: http://stackoverflow.com/a/52266997
possible better answer: http://stackoverflow.com/a/52265249
type: Question
accepted answer: http://stackoverflow.com/a/52265244
has title: Best data type for PostgreSQL datatime type
has answer: http://stackoverflow.com/a/52265249
has comment: http://stackoverflow.com/comment/91478541
has body: Actually I have: CREATE TABLE public.user( id BIGSERIAL NOT NULL, nick VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, born DATE, joined DATE, tags text[] ); I want to choose best option to save register time, and born data. I searched internet but didnt find any good results. Maybe its better to use time from python, and just insert it to postgres?

http://stackoverflow.com/comment/91314422
type: Comment
has text: @Niranjan , Hello! Check my post, pelase :)
comment on: http://stackoverflow.com/q/52181539
score: 0
type: QuestionComment

http://stackoverflow.com/a/52277985
has comment: http://stackoverflow.com/comment/91504600
has comment: http://stackoverflow.com/comment/91712805
has comment: http://stackoverflow.com/comment/91506174
type: Answer
has comment: http://stackoverflow.com/comment/91773178
score: 4
has comment: http://stackoverflow.com/comment/91504864
has comment: http://stackoverflow.com/comment/91790464
has comment: http://stackoverflow.com/comment/91506108
has comment: http://stackoverflow.com/comment/91506256
answers question: http://stackoverflow.com/q/52220462
has comment: http://stackoverflow.com/comment/91506566
has comment: http://stackoverflow.com/comment/91782283
accepted answer of: http://stackoverflow.com/q/52220462
has comment: http://stackoverflow.com/comment/91722287
upvote count: 4
has body: Solution without any extra copying of lists other than the sublist results: def sublists(a, tolerance): result = [] index = 0 while index &lt; len(a): curr = a[index] for i in range(index, len(a)): if a[i] == curr: end = i elif i - end &gt; tolerance: break if index != end: result.append(a[index:end+1]) index += end - index + 1 return result Usage is simply as follows: a = ['A', 'B', 'A', 'B', 'A', 'C', 'D', 'E', 'D', 'E', 'D', 'F', 'G', 'A', 'B'] sublists(a, 0) # [] sublists(a, 1) # [['A', 'B', 'A', 'B', 'A'], ['D', 'E', 'D', 'E', 'D']] sublists(a, 2) # [['A', 'B', 'A', 'B', 'A'], ['D', 'E', 'D', 'E', 'D']] Possible solution to extra requirement as specified in the comments: if i &gt; index and a[i] == a[i-1] == curr: end = i - 1 break elif a[i] == curr: end = i elif i - end &gt; tolerance: break Note: I've not tested this thoroughly.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91506393
downvote count: 0

http://stackoverflow.com/comment/91315360
comment on: http://stackoverflow.com/a/52181511
type: AnswerComment
score: 0
has text: @AthotaSrinivas - Try `df = df1[df1[0].astype(str).str.contains(pat)]`
type: Comment

http://stackoverflow.com/comment/91256939
has text: @Peter: take into account that that won't preserver order! `list(OrderedDict.fromkeys(stream))` would keep the inputs in order of first-seen id.
comment on: http://stackoverflow.com/q/52153270
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91550775
comment on: http://stackoverflow.com/q/52179919
type: Comment
type: QuestionComment
has text: @DrM is there a way to not to normalize the newSignal? It seems to be putting newsignal around 0 and not like the original values. I have attached the output in the problem description above.
score: 0

http://stackoverflow.com/comment/91387367
has text: Upon further though I think this might be more appropriate to ask in the Geographic Information Systems community. How can I move it there?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52218951

http://stackoverflow.com/comment/91319928
score: 0
has text: https://stackoverflow.com/questions/15121844/does-uwsgi-need-to-be-restarted-when-django-code-changes
type: AnswerComment
comment on: http://stackoverflow.com/a/52185095
type: Comment

http://stackoverflow.com/a/52170467
type: Answer
answers question: http://stackoverflow.com/q/52167309
has body: I dont know how your model structure or anything. But here is an idea on how to do this: class LabelTree(serializers.ModelSerializer): children = serializers.SerializerMethodField() class Meta: fields = ('label', 'children') model = Label def get_children(self, obj): children = Label.objects.filter(parent=obj) return LabelTree(children, many=True) You find the children of your obj by filtering by the parent field and you serialize them. the code is not tested but The idea behind it should work.
score: 0

http://stackoverflow.com/a/52268088
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52267929
upvote count: 1
has body: Try assert "200" in resp.code or assert "OK" in resp.reasonin your test_http_client() function. The object that is getting assigned to resp is the AsyncHTTPClient, not the response itself. To call the response message, you need something like resp.code, resp.reason, resp.body, resp.headers, etc. Here's a list of things that you can call http://www.tornadoweb.org/en/stable/httpclient.html#response-objects
type: Answer

http://stackoverflow.com/comment/91337905
has text: Even for 3.6, you can either use the dataclasses backport, or the third-party library that inspired it, attrs.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52192786
type: Comment

http://stackoverflow.com/comment/91219197
has text: First, source activate the conda env. Then make sure you have python and pip installed inside the env. Then do your normal pip installs inside the env. All the packages whether installed using pip or conda are all installed inside the env now.
type: Comment
comment on: http://stackoverflow.com/a/52134146
score: 1
type: AnswerComment

http://stackoverflow.com/comment/91315481
comment on: http://stackoverflow.com/a/52182801
has text: @jezrael, Maybe it's a bug in a new version, will check if I have some time. OP should definitely try this one first in my opinion, it's more memory efficient and cleaner.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52115582
upvote count: 2
answers question: http://stackoverflow.com/q/52115244
score: 1
downvote count: 1
has body: Thanks to @IanS. Of course, a ; at the end of the line works.
type: Answer

http://stackoverflow.com/comment/91472877
type: QuestionComment
comment on: http://stackoverflow.com/q/52262533
has text: @Klaus, Hostnames aren't handled by DNS. They're handled by Avahi/Zeroconf, which all hosts have installed.
score: 0
type: Comment

http://stackoverflow.com/q/52174419
score: 5
has answer: http://stackoverflow.com/a/52174649
favorite count: 0
upvote count: 5
has body: This would be the layout some_function.py def some_function(): print("some_function") some_library.py from some_function import some_function class A: def xxx(self): some_function() main.py from some_library import A from some_function import some_function def new_some_function(): print("new_some_function") if __name__ == '__main__': some_function = new_some_function a = A() a.xxx() In the class A, the method xxx, calls some_function, so is it possible to override it with something else, without re-implementing the entire class?
has comment: http://stackoverflow.com/comment/91299803
tagged with: python
has answer: http://stackoverflow.com/a/52174680
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52174828
accepted answer: http://stackoverflow.com/a/52174828
downvote count: 0
has title: How to override a method used by a 3rd party library
has comment: http://stackoverflow.com/comment/91299954
type: Question
has answer: http://stackoverflow.com/a/52174618
has comment: http://stackoverflow.com/comment/91299899
possible better answer: http://stackoverflow.com/a/52174649

http://stackoverflow.com/q/52263451
downvote count: 1
has answer: http://stackoverflow.com/a/52263558
type: Question
has title: Loop through subsets of rows in a DataFrame
score: 1
has answer: http://stackoverflow.com/a/52263527
tagged with: apply
linked to: http://stackoverflow.com/q/52038896
favorite count: 0
answer count: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52263527
tagged with: python
has answer: http://stackoverflow.com/a/52263692
has body: I try to loop trough rows of a DataFrame with a function calculation most frequent element in a series. The function works perfectly when i manually supply a series into it: # Create DataFrame df = pd.DataFrame({'a' : [1, 2, 1, 2, 1, 2, 1, 1], 'b' : [1, 1, 2, 1, 1, 1, 2, 2], 'c' : [1, 2, 2, 1, 2, 2, 2, 1]}) # Create function calculating most frequent element from collections import Counter def freq_value(series): return Counter(series).most_common()[0][0] # Test function on one row freq_value(df.iloc[1]) # Another test freq_value((df.iloc[1, 0], df.iloc[1, 1], df.iloc[1, 2])) With both tests I get the desired result. However, when i try to apply this function in a loop through DataFrame rows and save the result into new column, i get an error "'Series' object is not callable", 'occurred at index 0'. The line producing the error is as follows: # Loop trough rows of a dataframe and write the result into new column df['result'] = df.apply(lambda row: freq_value((row('a'), row('b'), row('c'))), axis = 1) How exactly row() in apply() function works? Shouldn't it supply to my freq_value() function values from columns 'a', 'b', 'c'?
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/91474841
possible better answer: http://stackoverflow.com/a/52263558
tagged with: loops

http://stackoverflow.com/q/52268126
possible better answer: http://stackoverflow.com/a/52268209
has answer: http://stackoverflow.com/a/52268209
has title: Sort CSV on new value and print top 10 lines
has answer: http://stackoverflow.com/a/52268163
type: Question
accepted answer: http://stackoverflow.com/a/52268163
tagged with: dataframe
tagged with: numpy
score: 0
answer count: 2
has body: I am trying to create a new column by dividing two pre existing columns, sorting the csv descending on the new column, then printing out the new top 10 lines. Here is what I have so far. import pandas as pd import numpy as np import csv #loading the csv file df = pd.read_csv('tmdb-movies.csv') #Create column for calculated profitability df['Profitability'] = df['revenue_adj'] / df['budget_adj'] df = sorted(df['Profitability'], key=float) df.head(10) I can calculate the "Profitability" column but I can't seem to sort by it.
tagged with: python
type: AnsweredQuestion

svd
type: Tag
tags question: http://stackoverflow.com/q/52235314
tags question: http://stackoverflow.com/q/52198701
tag name: svd

http://stackoverflow.com/q/52155591
duplicate of: http://stackoverflow.com/q/2960772
has answer: http://stackoverflow.com/a/52155609
type: Question
has title: How to insert string into a string as a variable?
has answer: http://stackoverflow.com/a/52155663
linked to: http://stackoverflow.com/q/44462209
score: 10
has answer: http://stackoverflow.com/a/52155770
accepted answer: http://stackoverflow.com/a/52155770
has answer: http://stackoverflow.com/a/52155710
answer count: 7
tagged with: variables
tagged with: string
has body: I'm trying to create a program and one thing I'm trying to do is add variables to a string like so. EnemyHealth = 0 EnemyIs = 'dead' print("The Enemy's health is %d. The Enemy is %d." % (EnemyHealth,EnemyIs) But everytime I try that it won't let me use a string as one of the variables. How would I insert a variable string into another string? P.S. I am using python 3.7.0
has answer: http://stackoverflow.com/a/52155650
favorite count: 0
has answer: http://stackoverflow.com/a/52155643
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52155713
upvote count: 10
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52155713
downvote count: 0

http://stackoverflow.com/a/52174837
has body: Use groupby df.groupby('Movie', as_index=False).sum() output: Movie Comedy Horror Drama A 1 0 1 B 0 1 1
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52174829
has comment: http://stackoverflow.com/comment/91300577

http://stackoverflow.com/q/52228550
has title: How to close aiohttp ClientSession
tagged with: aiohttp
score: 13
has body: I am trying to make an app that might live for a day, a week or longer. Dyring the app's lifetime, it will make requests to different API's. Some of these apis might require log in, so it is important that i have access to cookies at all times. So what i need is a file that the different API's can use without blocking the app. I am new to asynchronous programming(asyncio/aiohttp) and examples i have seen, shows how to make a lot of requests from a list of url's, but this is not what i need. The problem with the code i have is, either i get ClientSession is closed error or unclosed ClientSession warnings. import asyncio # only here for debugging purposes import aiohttp USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:61.0) Gecko/20100101 Firefox/61.1' def default_headers(): header = { 'User-Agent': USER_AGENT } return header class WebSession(object): session = None @classmethod def create(cls): cls.session = aiohttp.ClientSession() return cls.session @classmethod def close(cls): if cls.session is not None: cls.session.close() async def request(method, url, **kwargs): if kwargs.get('headers', None) is None: kwargs['headers'] = default_headers() if WebSession.session is None: session = WebSession.create() else: session = WebSession.session async with session.request(method=method, url=url, **kwargs) as response: if isinstance(session, aiohttp.ClientSession): # if i close the session here, i will get the ClientSession closed error on 2. request. # await session.close() pass return response async def get(url, **kwargs): return await request('GET', url=url, **kwargs) async def post(url, **kwargs): return await request('POST', url=url, **kwargs) async def get_url(): res = await get('https://httpbin.org/get') print(f'Status code: {res.headers}') m_loop = asyncio.get_event_loop() m_loop.run_until_complete(get_url()) # if i run this without closing the ClientSession, i will get unclosed ClientSession warnings. m_loop.run_until_complete(get_url()) m_loop.close() I do get a…
type: Question
has comment: http://stackoverflow.com/comment/91446773
has comment: http://stackoverflow.com/comment/91444449
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91447777
tagged with: python
has answer: http://stackoverflow.com/a/52317307
upvote count: 13

http://stackoverflow.com/comment/91495657
type: Comment
comment on: http://stackoverflow.com/a/52266483
has text: Hi, thanks for your response. But I still get the same error even with `reverse('thanks')`. Interestingly, a redirect to another view name in a different app works even without the `reverse`. This makes me think that somehow, the view / url names in the `home` app seem to be not recognized..
score: 0
type: AnswerComment

http://stackoverflow.com/q/52210222
has comment: http://stackoverflow.com/comment/91370633
type: Question
has body: I'm testing out pygame (in python 2.7) before I try to use it in any programs, what I am trying to do is make an image appear in the display, wait for half a second, then cover the previous image with a new one, but the second image is not placed on top of the old image, but underneath it. I tried switching the image order, using different images, and even tried using 3 images. import time as t import pygame from pygame.locals import * pygame.init() screen = pygame.display.set_mode((1000,1000),0,32) image1 = pygame.image.load("image1.png").convert_alpha() image2 = pygame.image.load("image2.png").convert() while True: screen.blit(image1,(0,0)) pygame.display.update() t.sleep(0.5) screen.blit(image2,(0,0)) pygame.display.update()
answer count: 1
tagged with: python-2.7
score: 0
tagged with: python
tagged with: pygame
has title: Why do images appear behind previous images when trying to put new images into a Pygame display?
has answer: http://stackoverflow.com/a/52210642
type: UnansweredQuestion
tagged with: blit
has comment: http://stackoverflow.com/comment/91369941
has comment: http://stackoverflow.com/comment/91370065

http://stackoverflow.com/comment/91235399
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52142449
has text: Thanks a bunch, Pizza! I really hope I get something close to your solution if I get asked this question at a technical interview.
type: AnswerComment

http://stackoverflow.com/a/52130149
upvote count: 2
has body: Using requests module in combination with selectors you can try like the following as well: import requests from bs4 import BeautifulSoup link = 'http://www.pythonscraping.com/pages/page3.html' soup = BeautifulSoup(requests.get(link).text, 'lxml') for table in soup.select('table#giftList tr')[1:]: cell = table.select_one('td').get_text(strip=True) print(cell) Output: Vegetable Basket Russian Nesting Dolls Fish Painting Dead Parrot Mystery Box
answers question: http://stackoverflow.com/q/52129625
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/52170770
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52172047
type: Question
tagged with: python
tagged with: paint
tagged with: tkinter
score: 0
has body: from tkinter import * import tkinter as tk import math class Paint(): def __init__(self): self.window=Tk() self.sizex=500 self.sizey=500 self.default_pen_size=10 self.canvas = Canvas(self.window, width=self.sizex, height=self.sizey, bg = "white") self.canvas.pack() self.img = PhotoImage(width=self.sizex, height=self.sizey) self.canvas.create_image((self.sizex/2, self.sizey/2), image=self.img, state="normal") self.canvas.bind("&lt;Button-1&gt;", self.color_in) self.canvas.bind("&lt;B1-Motion&gt;", self.color_in) self.window.mainloop() def color_in(self, event): self.img.put("black", (event.x , event.y)) radius_sqrt=math.sqrt(self.default_pen_size) circle=self.canvas.create_oval(event.x - radius_sqrt, event.y - radius_sqrt, event.x + radius_sqrt, event.y + radius_sqrt, fill="black") self.img.put(circle) if __name__=='__main__': paint=Paint() In my code above, I'm trying to draw a circle onto a Photoimage object using the canvas.create_oval method. Its working so far, but it keeps throwing the exception "_tkinter.TclError: can't parse color "115"". Any idea whats causing this?
answer count: 1
has answer: http://stackoverflow.com/a/52172047
has comment: http://stackoverflow.com/comment/91294064
has title: Keep getting error "_tkinter.TclError: can't parse color "115" when attempting to draw circle onto PhotoImage in Tkinter through mouse input
has comment: http://stackoverflow.com/comment/91292536
has comment: http://stackoverflow.com/comment/91294698

http://stackoverflow.com/comment/91437828
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52242955
has text: Hi Nukesor i have re-edited the question. Please take a look and kindly give your feedback. Thanks
score: 0

http://stackoverflow.com/q/52178508
score: 0
answer count: 1
tagged with: windows-7
accepted answer: http://stackoverflow.com/a/52178754
tagged with: python
type: AnsweredQuestion
has title: Can't install tensorflow on windows 7 32-bit
has body: I can't install TensorFlow in Windows 7, Python 3(32-bit, Lenovo ThinkPad X201s). When I type pip3 install tensorflow: Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\sjkim&gt;pip3 install tensorflow Collecting tensorflow Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow C:\Users\sjkim&gt; And I also have 2 python versions. How can I install it?
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/52178754

http://stackoverflow.com/q/52115503
type: Question
has body: What is the best way to use ROC / AUC as metric in Keras instead of 'accuracy', while doing a KFold validtation? I tried replacing 'accuracy' with sklearns 'roc_curve' and 'auc', but this did not work. Also: How could I access the 'cross_val_score()' loops in order to plot the ROC-Curve? Here is my code: X = X.values Y = Y.values def create_baseline(): model = Sequential() model.add(Dense(82, input_dim=82, kernel_initializer='normal', activation='relu')) model.add(Dense(50, activation='relu')) model.add(Dense(1, kernel_initializer='normal', activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) return model estimator = KerasClassifier(build_fn=create_baseline, epochs=100, batch_size=5, verbose=0) kfold = KFold(n_splits=50, shuffle=True, random_state=True) results = model_selection.cross_val_score(estimator, X, Y, cv=kfold) print("Accuracy: %.3f%% (%.3f%%)" % (results.mean()*100.0, results.std()*100.0))
has comment: http://stackoverflow.com/comment/91184070
tagged with: cross-validation
score: 0
upvote count: 1
downvote count: 1
tagged with: scikit-learn
tagged with: keras
favorite count: 0
tagged with: roc
type: UnansweredQuestion
tagged with: python
answer count: 0
has title: ROC AUC Metric in KFold Validation
has comment: http://stackoverflow.com/comment/91181736

http://stackoverflow.com/comment/91289449
has text: Tried. Not the solution. :( . The worst thing is that i can't see any error so i can search it.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52169422
type: AnswerComment

http://stackoverflow.com/a/52185581
answers question: http://stackoverflow.com/q/52184724
type: Answer
has body: You can use dictionnaries to map your existing data. First create a dictionnary which tells you for every area in which area it fusing: areas_to_fuse = dict(zip(frame2.year0.values, frame2.year2.values)) areas_to_fuse = {**areas_to_fuse,**dict(zip(frame2.year1.values, frame2.year2.values))} {'area1': 'area5', 'area2': 'area5', 'area3': 'area5', 'area4': 'area5', 'area6': 'area6'} This being done, you can create the NewArea column by using replace on frame3['area'] (note that replace permits to keep the values not present in the keys of the dictionnary, if you prefer missing values, use map) frame3['NewArea'] = frame3.area.replace(areas_to_fuse) Then you can create a second dictionnary coding for every area which value corresponds, and map it to your column NewArea: newvalues = frame3.groupby('NewArea').numbercount.sum().to_dict() frame3['TotalNumber'] = frame3.NewArea.map(newvalues) frame3'NewArea','TotalNumber' NewArea TotalNumber 0 area5 85 1 area5 85 2 area5 85 3 area5 85 4 area5 85 5 area6 25
accepted answer of: http://stackoverflow.com/q/52184724
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91401600
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52225951
has text: What if the number is 1000? You account for <101 and <1000, but not for 1000 itself.

http://stackoverflow.com/q/52152512
answer count: 1
tagged with: praw
has comment: http://stackoverflow.com/comment/91255863
tagged with: keyerror
has comment: http://stackoverflow.com/comment/91255782
has comment: http://stackoverflow.com/comment/91255430
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/91257221
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91255651
has comment: http://stackoverflow.com/comment/91256516
has body: I'm losing my mind here. What I am trying to do here is pull up a Reddit threads from a csv file that is already generated, then pull the title of the thread, the number of comments, and the current date and time and append it into the first dictionary. Then what I try to do is remove the punctuation's(which I am also still kind of failing at) and encoding. Lastly append each value from the first dictionary into the second one so that each thread from the first dictionary could have their own individual csv file. TLDR: Im getting a key error when appending the first dict to the second dict, can anyone help? Also improve my chances of removing punctuations? import csv import praw import os import errno import pandas as pd import datetime as dt thread_id = [] volume_dict = { "post":['These', 'are', 'values'], "num_comments":['62', '43', '96'], "date_time":[] } volume_dict2 = { "post2":[], "num_comments":[], "date_time":[] } for post in volume_dict["post"]: volume_dict2['post2'].append(post) volume_dict2['num_comments'].append(volume_dict['num_comments']) volume_dict2['date_time'].append(dt.datetime.now()) pathV = os.path.join(os.getcwd() + post + '.csv') volume_data = pd.DataFrame(volume_dict2) volume_data.to_csv(pathV, index=True) print('saved to' + pathV) volume_dict2.clear()
type: Question
has answer: http://stackoverflow.com/a/52152676
score: 0
has comment: http://stackoverflow.com/comment/91255758
has comment: http://stackoverflow.com/comment/91257728
has comment: http://stackoverflow.com/comment/91256220
has title: Python Key Error Appending Dictionary to Dictionary with list

http://stackoverflow.com/q/52157755
answer count: 1
has answer: http://stackoverflow.com/a/52158592
tagged with: io
has comment: http://stackoverflow.com/comment/91267069
tagged with: python
has body: on raspberry pi opencv python, I'm successfully capturing an image from a USB cam, then saving as 'image.png' then passing the filename to an smtp client that reads in the file and sends it as an attachement in an email. obviously this is bad for the sd card... how do I treat an area of RAM as a file? that I can stream data to and from?.. I'm not at home now but if needed I can attach code of what I've tried so far. cheers
tagged with: ram
tagged with: file
type: Question
type: AnsweredQuestion
has title: Python raspberry pi - how to treat RAM memory as a file
has comment: http://stackoverflow.com/comment/91266051
score: 0
accepted answer: http://stackoverflow.com/a/52158592

http://stackoverflow.com/comment/91343807
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52195622
has text: Yes I think it'd be much faster if you collated the coordinates into a `2XN` numpy array where `N` is the number of points, then you modified the entire image at once like `im[coordinates]=0.0`, where `im = np.ones(shape)`. Then you can use `findcontours` from `cv2` as suggested in the answers by others below

http://stackoverflow.com/a/52212683
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52212594
answers question: http://stackoverflow.com/q/52212594
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91375226
has comment: http://stackoverflow.com/comment/91374951
type: Answer
score: 2
has body: IIUC, from your description, you can do: df[~df.iloc[:,3].isin(df.iloc[:,0])] Which returns: 0 1 2 3 3 11 2 1 32 5 13 2 1 108 Contrary to your desired output, this removes the row with 000000011, but not the one with 000000108, because 000000011 is found in both columns, but 000000108 is not

http://stackoverflow.com/q/52258645
has answer: http://stackoverflow.com/a/66032075
type: UnansweredQuestion
tagged with: pandas
has body: I am getting the error below after running the code at end. Please let me know how to solve it. I am importing pandas, numpy before. return object.__getattribute__(self, name) AttributeError: 'DataFrame' object has no attribute 'nunique' train_dt = pd.DataFrame(train.dtypes,columns = ['Numpy Dtype']) train_dt['Nunique'] = train.nunique()
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52258672
upvote count: 1
tagged with: python
has title: AttributeError: 'DataFrame' object has no attribute 'nunique'
downvote count: 0

http://stackoverflow.com/comment/91266690
comment on: http://stackoverflow.com/a/52151005
type: Comment
has text: I think it's because I may have the class inside the function def new_window().
type: AnswerComment
score: 0

http://stackoverflow.com/q/52153573
tagged with: anaconda
score: 1
has answer: http://stackoverflow.com/a/56040974
type: Question
downvote count: 0
answer count: 1
favorite count: 0
tagged with: pyinstaller
tagged with: python
has title: Pyinstaller with Anaconda 3 can't install
type: UnansweredQuestion
upvote count: 1
has body: I'm trying to compile an exe with pyinstaller inside an Anaconda 3 environment. Any idea how to fix this: 201 INFO: PyInstaller: 3.3.1 201 INFO: Python: 3.6.6 202 INFO: Platform: Linux-2.6.32-754.3.5.el6.x86_64-x86_64-with-centos-6.10-Final ........ SOME BLOAT..... 8666 INFO: Python library not in binary dependencies. Doing additional searching... Traceback (most recent call last): File "/home/rokner/miniconda3/envs/bisection/bin/pyinstaller", line 6, in &lt;module&gt; ...BIG TRACEBACK ... File "/home/rokner/miniconda3/envs/bisection/lib/python3.6/site- packages/PyInstaller/building/build_main.py", line 629, in _check_python_library raise IOError(msg) OSError: Python library not found: libpython3.6.so.1.0, libpython3.6mu.so.1.0, libpython3.6m.so.1.0 This would mean your Python installation doesn't come with proper library files. This usually happens by missing development package, or unsuitable build parameters of Python installation. * On Debian/Ubuntu, you would need to install Python development packages * apt-get install python3-dev * apt-get install python-dev * If you're building Python by yourself, please rebuild your Python with `-- enable-shared` (or, `--enable-framework` on Darwin) I've tried installing some dev packages for my OS(Cent OS 6.10) but with no luck because the python used is in a conda env.

http://stackoverflow.com/comment/91429906
has text: Also, the last answer you had already does what you want. Do you **need** a stack? You can just append the regex results to a stack... https://stackoverflow.com/questions/52239686/extract-html-tags-from-a-text-file-through-iteration-and-append-them-to-a-list-a
type: Comment
comment on: http://stackoverflow.com/q/52240338
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91358603
comment on: http://stackoverflow.com/q/52204615
type: Comment
type: QuestionComment
has text: Can I ask what you're trying to do this for? You might be able to do something with [`SearchRank`](https://docs.djangoproject.com/en/2.1/ref/contrib/postgres/search/#searchrank) to order by the amount of matches..
score: 0

http://stackoverflow.com/comment/91310893
type: Comment
type: QuestionComment
has text: Yes, that is. The message said something like: ERROR: The process "AspenPlus.exe" could not be terminated with PID 1100. Reason: There is no active instance of the task. Also, I am able to kill it from task manager GUI.
comment on: http://stackoverflow.com/q/52180175
score: 0

http://stackoverflow.com/q/52193263
type: Question
has answer: http://stackoverflow.com/a/52193794
accepted answer: http://stackoverflow.com/a/52193794
tagged with: key
score: 0
has comment: http://stackoverflow.com/comment/91336289
upvote count: 1
has comment: http://stackoverflow.com/comment/91336628
has comment: http://stackoverflow.com/comment/91336516
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91336389
tagged with: python
has comment: http://stackoverflow.com/comment/91336310
has comment: http://stackoverflow.com/comment/91336331
favorite count: 0
has comment: http://stackoverflow.com/comment/91336639
has title: adding a key value pair to dict
has comment: http://stackoverflow.com/comment/91336708
has body: In the following code I get an error at 'row[header]': for field in Document._meta.get_fields(): headers.append(field.name) docs = Document.objects.order_by('id') for doc in docs: row = {} for header in headers: if hasattr(doc, header): row[header] = getattr(doc, header) files.append(row) Python says: TypeError: list indices must be integers or slices, not str What goes wrong? Python traceback: Traceback (most recent call last): File "/home/niels/PycharmProjects/sitesv/env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/niels/PycharmProjects/sitesv/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/niels/PycharmProjects/sitesv/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/niels/PycharmProjects/sitesv/files/views.py", line 87, in get_file_list row[header] = getattr(doc, header) TypeError: list indices must be integers or slices, not str
tagged with: django
has comment: http://stackoverflow.com/comment/91336500
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91336862
has comment: http://stackoverflow.com/comment/91337198
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/91336813
has comment: http://stackoverflow.com/comment/91336570
has comment: http://stackoverflow.com/comment/91336921
has comment: http://stackoverflow.com/comment/91336782
has comment: http://stackoverflow.com/comment/91336477

http://stackoverflow.com/comment/91465775
score: 0
comment on: http://stackoverflow.com/q/52257398
has text: From your description, it sounds like you should instead build a list of "lurkers", then ask the user if they should be kicked, then loop through that list to kick them. Or should the process ask on a per-lurker basis? If so, you should probably send the lurkers name to the person making the decision.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91420994
has text: I've done tutorial, yet the one I did, didn't mention writing views that update an attribute of a model at all, so I basicall had no idea I could do it like this. Then I'll just check how to do this and probably figure something out. Thanks a lot for mentioning this method.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52236057

http://stackoverflow.com/q/52149819
accepted answer: http://stackoverflow.com/a/52150135
tagged with: python
type: AnsweredQuestion
has title: How to open the .txt in a folder if the .xls in another folder is of same name
type: Question
has comment: http://stackoverflow.com/comment/91249729
tagged with: dataframe
score: 0
tagged with: for-loop
upvote count: 1
tagged with: file-permissions
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91249769
has comment: http://stackoverflow.com/comment/91249645
has body: There are two folders containing individual's data, one folder containing .txt files, and another folder containing the .xls files. Folder1 :['A.txt', 'B.txt', 'C.txt'] Folder2 :['A.xls', 'B.xls', 'C.xls'] I want to open both the files of the same individual and do some action on .txt file based on information in .xls file. This is what i tried: Tpath = 'Path to Folder1' Xpath = 'Path to Folder2' for tfilename in glob.glob(os.path.join(Tpath)): for tfile in os.listdir(Tpath): for xfilename in glob.glob(os.path.join(Xpath)): for xfile in os.listdir(Xpath): if (xfile[:-4] == tfile[:-4]): tdf = pd.read_csv(tfilename) xdf = pd.read_excel(xfilename) I encounter Permission Denied error. I know it is due to the fact that I am trying to access the file from the for loop from one folder to for loop from another folder. But I don't know how to solve this. Can anyone correct my mistake here?
favorite count: 0
has comment: http://stackoverflow.com/comment/91249814
has answer: http://stackoverflow.com/a/52150135

http://stackoverflow.com/q/52127689
score: 1
tagged with: loops
has title: python function doesn't return anything
type: Question
has comment: http://stackoverflow.com/comment/91205876
tagged with: function
has comment: http://stackoverflow.com/comment/91205812
has comment: http://stackoverflow.com/comment/91205850
has body: I'm trying to solve this problem:Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array. I came up with this code: def almostIncreasingSequence(seq): count_2 = 0 for element in seq: count = 0 seq.remove(element) for i in range(len(seq)-1): if seq[i] &lt; seq[i+1]: count += 1 else: break if count == len(seq): return True else: seq = [element]+ seq count_2 += 1 if count_2 == len(seq): return False The problem is that when I give an input, the function doesn't do anything.for example in the interactive shell: &gt;&gt;&gt;print(almostIncreasingSequence([10,1,2,3,4,5])) &gt;&gt;None and if I don't use print: &gt;&gt;&gt;almostIncreasingSequence([10,1,2,3,4,5]) &gt;&gt;&gt; it returns nothing,it should return True for this special sequence.
has comment: http://stackoverflow.com/comment/91205813
has answer: http://stackoverflow.com/a/52128101
upvote count: 2
answer count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/52127836
has comment: http://stackoverflow.com/comment/91205818
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91206027
has comment: http://stackoverflow.com/comment/91205968
type: UnansweredQuestion
tagged with: python

permissions
tag name: permissions
type: Tag
tags question: http://stackoverflow.com/q/52250623
tags question: http://stackoverflow.com/q/52162046

http://stackoverflow.com/comment/91343333
comment on: http://stackoverflow.com/a/52196736
type: AnswerComment
has text: Ok, see edit - probably easier to just use `split` instead
score: 0
type: Comment

http://stackoverflow.com/comment/91416032
has text: Have a look at my answer here for detecting pixels of a certain colour... https://stackoverflow.com/a/52183666/2836621 Note however that if you use **OpenCV**, hues are scaled on range 0-180 rather than 0-255 that **PIL** uses.
score: 1
comment on: http://stackoverflow.com/q/52233448
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52171056
has body: I want to detect if the key H was pressed in anytime, and not just one time. I am currently using the keyboard module like that: import keyboard while True: if keyboard.is_pressed('h'): print("H pressed") break So, if I pressed H it will output H pressed, but if I pressed H again nothing will happen because I've breaked the while loop. I want it to work again and not only one time key detection. Any help would be appreciated. Thanks!
has comment: http://stackoverflow.com/comment/91293099
has comment: http://stackoverflow.com/comment/91292798
favorite count: 0
has comment: http://stackoverflow.com/comment/91292857
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91292762
has answer: http://stackoverflow.com/a/52171322
tagged with: python
has title: Detect if key was pressed anytime
upvote count: 0
has comment: http://stackoverflow.com/comment/91292751
tagged with: loops
type: Question
score: -1
answer count: 2
has answer: http://stackoverflow.com/a/52171335
downvote count: 1

http://stackoverflow.com/a/52129875
has comment: http://stackoverflow.com/comment/91210486
has comment: http://stackoverflow.com/comment/91210719
type: Answer
has comment: http://stackoverflow.com/comment/91210739
accepted answer of: http://stackoverflow.com/q/52129623
has comment: http://stackoverflow.com/comment/91210626
has comment: http://stackoverflow.com/comment/91210300
answers question: http://stackoverflow.com/q/52129623
has body: You don't need any library to use. All you need is using python built-in functions. m = ["$((2+1))","$((2+0))","$((1+1))aa$((5**2))bb","$((0+0))"] def OPGetter(string) : i = 0 while i &lt; len(string) : if string[i] == ")" : last = i i += 1 res1 = (string[last+1:]) # i = 0 while i &lt; len(string) : if string[i] == "(" : one = i+1 i += 1 i = 0 while i &lt; len(string) : if string[i] == ")" : two = i break i += 1 return [string[one:two],res1] result =[] i = 0 while i &lt; len(m) : string = m[i].split("$") if len(string) &gt; 0 : res = string[0] string = string[1:] for item in string : code = "def returning() :\n return "+ OPGetter(item)[0] exec(code) value = returning() res += str(value)+OPGetter(item)[1] result.append(res) i += 1 the result will have the final list of the answers.
has comment: http://stackoverflow.com/comment/91211066
score: 0
has comment: http://stackoverflow.com/comment/91210264
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91210594
has comment: http://stackoverflow.com/comment/91212898

http://stackoverflow.com/q/52130720
has answer: http://stackoverflow.com/a/52130809
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52130748
has title: python 3 get specific value from json dictionary
favorite count: 0
tagged with: python-3.x
has body: I have a dictionary I'm getting from an API call. I am trying to grab a specific value from the results. names = requests.get("http://some.api") The result of that call when printed looks like this {'mynames': [{'id': 38, 'name': 'Betsy'}, {'id': 93, 'name': 'Pitbull'}, {'id': 84, 'name': 'Liberty'}]} I've tried the code below just to grab the result with 'Pitbull' as its name filtered_names = {k:v for (k,v) in names.items() if "Pitbull" in v} I get an error of AttributeError: 'Response' object has no attribute 'items' How can I just grab a specific value from the data that is being pulled from the API call?
tagged with: python
tagged with: dictionary
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/52130748
tagged with: python-requests
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52130809

http://stackoverflow.com/comment/91335931
type: QuestionComment
comment on: http://stackoverflow.com/q/52192877
type: Comment
score: 2
has text: I can repro in a script, and I wouldn't expect this to work interactively unless you're on something like IPython, since interactive mode shouldn't save the source code.

sensors
type: Tag
tag name: sensors
tags question: http://stackoverflow.com/q/52236700

http://stackoverflow.com/comment/91496274
score: 0
type: Comment
has text: @MaxDaen make sure to upvote if you found this useful!
type: AnswerComment
comment on: http://stackoverflow.com/a/52246938

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/52182607
tags question: http://stackoverflow.com/q/52153191
tags question: http://stackoverflow.com/q/52185218
tags question: http://stackoverflow.com/q/52221761
tags question: http://stackoverflow.com/q/52231010
tags question: http://stackoverflow.com/q/52211983
tags question: http://stackoverflow.com/q/52230219
type: Tag

http://stackoverflow.com/comment/91443239
type: Comment
type: QuestionComment
has text: You can use `os.listdir()` or `glob.glob()` to find all names in a directory.
comment on: http://stackoverflow.com/q/52247468
score: 0

virtual
tags question: http://stackoverflow.com/q/52116500
type: Tag
tag name: virtual

http://stackoverflow.com/a/52162281
score: 1
has comment: http://stackoverflow.com/comment/104616907
has body: How about you split your query and execute them one by one? qList = query.split(";") for q in qList: cursor.execute(q)
accepted answer of: http://stackoverflow.com/q/52160361
has comment: http://stackoverflow.com/comment/104706409
answers question: http://stackoverflow.com/q/52160361
has comment: http://stackoverflow.com/comment/104616891
upvote count: 2
type: AcceptedAnswer
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91278835
has comment: http://stackoverflow.com/comment/105910358

http://stackoverflow.com/q/52225003
has comment: http://stackoverflow.com/comment/91399129
tagged with: python
answer count: 1
upvote count: 3
has body: I'm trying to write to file the result from multiprocessing (4 cores/processes). Since the CPU cores work simultaneously, I thought of making 4 files, 0.txt, 1.txt, 2.txt and 3.txt and keep it in a multiprocessing.Manager().list(). But I'm getting error, TypeError: cannot serialize '_io.TextIOWrapper' object. def run_solver(total, proc_id, result, fouts): for i in range(10)): fouts[proc_id].write('hi\n') if __name__ == '__main__': processes = [] fouts = Manager().list((open('0.txt', 'w'), open('1.txt', 'w'), open('2.txt', 'w'), open('3.txt', 'w'))) for proc_id in range(os.cpu_count()): processes.append(Process(target=run_solver, args=(int(total/os.cpu_count()), proc_id, result, fouts))) for process in processes: process.start() for process in processes: process.join() for i in range(len(fouts)): fouts[i].close() I've tried to populate the list with file handle inside the function too, like below. def run_solver(total, proc_id, result, fouts): fout[proc_id] = open(str(proc_id)+'.txt', 'w') for i in range(10)): fouts[proc_id].write('hi\n') fout[proc_id].close() if __name__ == '__main__': processes = [] fouts = Manager().list([0]*os.cpu_count()) Both doesn't work and I understood there's something related to not able to serialize or unpickleable. But I don't know how to resolve this. Can someone suggest a solution?
tagged with: multiprocessing
has answer: http://stackoverflow.com/a/52225133
downvote count: 0
type: Question
type: AnsweredQuestion
score: 3
has title: Writing to multiple files using multiprocessing. Error: "TypeError: cannot serialize '_io.TextIOWrapper' object"
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52225133

http://stackoverflow.com/q/52151394
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52151450
tagged with: pytube
has title: facing problem in importing python package pytube in sudo su mode
tagged with: python
answer count: 1
score: 0
has body: when I imported pytube in normal mode it works just fine, but when i do the same on superuser it gives error saying ImportError: No module named pytube wanted to use it in file management so needed superuser in python.
has answer: http://stackoverflow.com/a/52151450
type: Question

http://stackoverflow.com/q/52231982
tagged with: http://stackoverflow.com/tag/json
downvote count: 2
upvote count: 1
type: Question
score: -1
has body: I am trying to write the following code but I am getting the attached error. I don't know what seems to be the problem? Have tried a lot of different ways birthday = {} with open('birthdays.json', 'r') as f: birthday = json.load(f) and the error message I receive is the following: File "/Users/Apple/PycharmProjects/test1/birthday_dictionaries2.py", line 4, in &lt;module&gt; with open('birthdays.json', 'r') as f: FileNotFoundError: [Errno 2] No such file or directory: 'birthdays.json'
answer count: 2
has comment: http://stackoverflow.com/comment/91413424
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has title: How to fix Python 3 Json file error in Pycharm?
has comment: http://stackoverflow.com/comment/91423992
tagged with: python
has answer: http://stackoverflow.com/a/52232059
has comment: http://stackoverflow.com/comment/91422999
has answer: http://stackoverflow.com/a/52232098

http://stackoverflow.com/comment/91292224
comment on: http://stackoverflow.com/q/52170785
score: 0
has text: You can't create dynamically named variables. I suggest putting the random numbers in a list.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52234270
has body: You may want to use shutil.move() to iteratively move the files from a directory to another. For example, import os import shutil from_dir = os.path.join(os.getcwd(),"test-dir") to_dir = os.path.abspath(os.path.expanduser('.')) for file in os.listdir(from_dir): shutil.move(os.path.join(from_dir, file), to_dir)
has comment: http://stackoverflow.com/comment/138692719
upvote count: 6
type: Answer
has comment: http://stackoverflow.com/comment/108326495
answers question: http://stackoverflow.com/q/52234073
downvote count: 0
score: 6

http://stackoverflow.com/a/57065216
answers question: http://stackoverflow.com/q/52154168
has body: To make it a bit easier you can use this: user = discord.utils.get(ctx.guild.roles, id=result["userif"]) Hope this helps! :D
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52154168

http://stackoverflow.com/a/52182581
score: 0
has comment: http://stackoverflow.com/comment/99230625
answers question: http://stackoverflow.com/q/52178818
has comment: http://stackoverflow.com/comment/99232758
accepted answer of: http://stackoverflow.com/q/52178818
type: AcceptedAnswer
has body: I figured it out, basically, the points are the landmark points of a face that resides in a 112,96 image, the nose is centered in the image and thus transforming landmark points of another face onto these points will center align a face just like these template landmark points
type: Answer

http://stackoverflow.com/comment/91347272
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52198414
score: 0
has text: you can add `*.csv` or `*.xml` file

http://stackoverflow.com/comment/91302800
type: Comment
score: 0
type: AnswerComment
has text: My point is that every incarnation of this function already exists in the language. There's not much market for inefficient redundancy.
comment on: http://stackoverflow.com/a/52174465

http://stackoverflow.com/comment/91261273
comment on: http://stackoverflow.com/q/52155522
type: Comment
has text: what's wrong with this line? which line?
score: 0
type: QuestionComment

http://stackoverflow.com/q/52266935
tagged with: python-imaging-library
tagged with: qr-code
tagged with: image
has body: I'm trying to convert in the air without save a temp file from image.pil.PilImage object ('qrcode.image.pil.PilImage') to Reportlab canvas.drawImage(pilimage, x, y, width=30, height=30) I have this error: TypeError: expected str, bytes or os.PathLike object, not PilImage After that I tried use BytesIO to convert PilImage: io_img = BytesIO(image) I have this error: TypeError: a bytes-like object is required, not 'PilImage' io_img = StringIO(image) TypeError: initial_value must be str or None, not PilImage Everything what I found is solutions with saved file and reopen it! Is there any way to convert PilImage object directly to reportLab, without saving file and open it !
score: 0
has comment: http://stackoverflow.com/comment/91481811
answer count: 1
has comment: http://stackoverflow.com/comment/91481963
has answer: http://stackoverflow.com/a/52267084
has title: convert PilImage to reportlab
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91481846
tagged with: python
has comment: http://stackoverflow.com/comment/91481933
has comment: http://stackoverflow.com/comment/91481786
tagged with: reportlab
type: Question

http://stackoverflow.com/comment/91773178
type: Comment
comment on: http://stackoverflow.com/a/52277985
type: AnswerComment
has text: I can't help but feel there is probably a dynamic programming solution to this that doesn't require a O(N^2) quadratic loop.
score: 0

http://stackoverflow.com/a/52231118
answers question: http://stackoverflow.com/q/52218112
score: 0
type: AcceptedAnswer
has body: The best answer comes from schwobaseggl: "Have you tried lp_wrapper = lp(obj.method)" It turns out that this is the way you wrap methods.
type: Answer
accepted answer of: http://stackoverflow.com/q/52218112

http://stackoverflow.com/a/59009606
upvote count: 1
answers question: http://stackoverflow.com/q/52141785
has body: The following code works for me. Not sure how efficient is this. sorted_list_by_value=sorted(data_dict, key=data_dict.__getitem__)
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/52122358
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52122191
score: 2
upvote count: 2
has body: Avoid using regex to parse html data. Use something specially designed for this like BeautifulSoup &gt;&gt;&gt; text = """&lt;address&gt; ... 113 N Michigan St&lt;br/&gt;Chicago, IL 60661 ... &lt;/address&gt;""" &gt;&gt;&gt; &gt;&gt;&gt; from bs4 import BeautifulSoup &gt;&gt;&gt; soup = BeautifulSoup(text, "html.parser") &gt;&gt;&gt; &gt;&gt;&gt; [addr.strip() for tag in soup.find_all('address') for addr in tag.strings] ['113 N Michigan St', 'Chicago, IL 60661']

http://stackoverflow.com/q/52271228
has comment: http://stackoverflow.com/comment/91489956
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/91489847
has comment: http://stackoverflow.com/comment/91490747
accepted answer: http://stackoverflow.com/a/52272407
has comment: http://stackoverflow.com/comment/91491021
has title: PyQt5 with multiple intents ( pages in the same window )
has comment: http://stackoverflow.com/comment/91490965
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91490817
has body: I'm totally new to PyQt5 and I'm trying to develop an application with a main menu and sub menus and i don't know how to start. All examples that I found are using that pop up windows as sub menu. Here is an example of what I'm going to do. Any suggestion on how to start and what to use in PyQt5 please ? The main menu is on the right and a sub menu is on the left
upvote count: 2
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/91489662
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52272407
score: 0

http://stackoverflow.com/q/52175938
answer count: 2
upvote count: 0
accepted answer: http://stackoverflow.com/a/52176027
possible better answer: http://stackoverflow.com/a/52175966
has title: How do I use a value inside a def outside a def
has body: I'm wondering how to call a value inside a def, to outside eg def location(): ##Bunch of other code key = 'true' if key == 'true': print('You may pass') Current this code returns undefined_variable key or something like that. My aim is to draw out the value of key. Edit: if key == 'true' Thks Julien I know the difference but just forgot to add the quotation marks.
favorite count: 0
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/91302461
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91302506
has answer: http://stackoverflow.com/a/52176027
score: -2
type: Question
has answer: http://stackoverflow.com/a/52175966

http://stackoverflow.com/comment/91254380
type: Comment
score: 0
has text: Please share a self-contained notebook that reproduces the problem.
type: QuestionComment
comment on: http://stackoverflow.com/q/52149644

http://stackoverflow.com/comment/91382722
score: 0
type: Comment
type: QuestionComment
has text: Your code writes a header here.
comment on: http://stackoverflow.com/q/52215155

http://stackoverflow.com/comment/91406440
score: 0
type: Comment
has text: thanks, I just noticed that too. I put in the `*` and it worked
type: AnswerComment
comment on: http://stackoverflow.com/a/52228429

http://stackoverflow.com/a/52118854
upvote count: 1
answers question: http://stackoverflow.com/q/52116711
downvote count: 0
type: Answer
score: 1
has body: Check your xml syntax, just put them in an online xml checker when this doesn't work, just comment out the different xml files and see where your error comes from. And share that piece with us.

http://stackoverflow.com/comment/91472808
score: 0
type: Comment
type: QuestionComment
has text: I'm aware url_for won't submit a form like I want to do (I wasn't clear enough, my fault). I'm trying to learn if there is a way to submit form data with a POST request (besides having it on the URL) . I don't have to use redirect or url_for if there is another way as long as the data is available in the request.form. The session store data seems like a work around (although it's a good idea, I didn't think of it) but I'm not opposed to using it if I have to. Is there some other command I should be using to POST form data to a URL on that line instead of redirect or url_for?
comment on: http://stackoverflow.com/q/52241131

http://stackoverflow.com/q/52132774
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91216323
tagged with: python
has comment: http://stackoverflow.com/comment/91216272
answer count: 0
has comment: http://stackoverflow.com/comment/91216167
has comment: http://stackoverflow.com/comment/91216318
has comment: http://stackoverflow.com/comment/91216302
has title: Pandas and scikit-learn: ValueError: Input contains NaN, infinity or a value too large for dtype('float64')
type: Question
has comment: http://stackoverflow.com/comment/91216141
has comment: http://stackoverflow.com/comment/91216181
has body: I am trying to fit Knearest Neigbors model to my data. but, I am getting this error: ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). Here is the code to my Knearest Neigbhors algorithm: def knn_train_test_new(training_col, target_col, df): np.random.seed(1) df = df.loc[np.random.permutation(len(df))] # shuffled_index = np.random.permutation(df.index) # df = df.reindex(shuffled_index) train_df = df.iloc[0:150] #training set has 75% of the data test_df = df.iloc[150:] #test set has 25% of the data k = [5] rmse = {} for k_val in k: model = KNeighborsRegressor(n_neighbors = k_val) model.fit(train_df[training_col], train_df[target_col]) predictions = model.predict(test_df[training_col]) mse = mean_squared_error(test_df[target_col], predictions) rmse[k_val] = (mse ** 0.5) return rmse two_features = ["width", "wheel-base"] rmse_val = knn_train_test(two_features, 'price', numeric_cars) And the top five rows of my dataframe: numeric_cars.head() I don't get this error when I use shuffled_index( which I have commented) instead of np.random.permutation. I don't clearly understand the difference between the two. The complete error track: ValueError Traceback (most recent call last) &lt;ipython-input-13-03e0dd7acfd0&gt; in &lt;module&gt;() 25 26 two_features = ["width", "wheel-base"] ---&gt; 27 rmse_val = knn_train_test_new(two_features, 'price', numeric_cars) 28 29 #rmse_results = {} &lt;ipython-input-13-03e0dd7acfd0&gt; in knn_train_test_new(training_col, target_col, df) 14 15 model = KNeighborsRegressor(n_neighbors = k_val) ---&gt; 16 model.fit(train_df[training_col], train_df[target_col]) 17 18 predictions = model.predict(test_df[training_col]) ~\Anaconda3\lib\site-packages\sklearn\neighbors\base.py in fit(self, X, y) 743 """ 744 if not isinstance(X, (KDTree, BallTree)): --&gt; 745 X, y = check_X_y(X, y, "csr", multi_output=True) 746 self._y = y 747 return self._fit(X) ~\Anaconda3\lib\site-packages\sklearn\utils\validation.py in check_X_y(X…
score: 0
tagged with: pandas
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/91216295
has comment: http://stackoverflow.com/comment/91216384

http://stackoverflow.com/q/52229780
has body: I'm having trouble referencing outer fields from a django subquery in a way that would be pretty easy to do in SQL. I have these two models: class Modem(models.Model): mac = Models.LowerCaseCharField class DHCPEvent(models.Model): timestamp = models.DateTimeField() # date released modem = models.ForeignKey(Modem) ip = models.LowerCaseCharField() The time window of when an IP is assigned to a given modem A is: [timestamp when IP assigned to modem A, timestamp when IP is assigned to another modem). I want to be able to query for all IP assignments to a specific modem overlapping a search time window (modem, from_date, to_date -> [ips]). To do this, I believe I need to find DHCPEvents assigned to a modem before the time window ends, and then, for each one, confirm there is no DHCPEvent for its IP assigned elsewhere before the search time window starts. This defines that the IP-to-modem assignment overlaps with the search window. But I am not sure how to do this in Django. What I have so far is this: Modem.objects.filter( dhcpevent__ip=Subquery( DHCPEvent.objects.filter( ip=OuterRef('dhcpevent__ip'), timestamp__gt=OuterRef('dhcpevent__timestamp'), timestamp__lte=to_date))) There are two issues: It is throwing "ValueError: This queryset contains a reference to an outer query and may only be used in a subquery." It seems to be inside a subquery to me. I need the OuterRefs to only look at the DHCPEvent first referenced in the second line, not every DHCPEvent attached to this Modem. But I don't know how to express this. Any advice is appreciated. Thanks! EDIT: I have now written this query in SQL which might clear up what I'm trying to achieve in Django a lot: select * from "MODEM" modem inner join "DHCPEVENT" dhcp_event_assign on modem."ID" = dhcp_event_assign."MODEM_ID" where modem."ID" = %(id)s dhcp_event_assign."TIMESTAMP" &lt;= %(to_date)s and not exists( select * from "DHCPEVENT" dhcp_event_next where dhcp_event_next."REMOTE_ADDRESS" = dhcp_event_assign."REMOTE_ADDRES…
has comment: http://stackoverflow.com/comment/91467025
has comment: http://stackoverflow.com/comment/91456674
score: 0
has title: Django ORM: how to filter one model with a subquery on a related model
has comment: http://stackoverflow.com/comment/91453248
has comment: http://stackoverflow.com/comment/91443903
has comment: http://stackoverflow.com/comment/91462104
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91410259
answer count: 0
type: Question

http://stackoverflow.com/a/52206779
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52206550
upvote count: 5
score: 5
has body: To get the date and time (or rather the datetime) from your input, it's easiest to use strptime. import datetime s = "2015 02 25 09:00:00" dt = datetime.datetime.strptime(s, "%Y %m %d %H:%M:%S") print(dt) Output: 2015-02-25 09:00:00 You don't even have to bother with the exact amount of spaces in the "format" string. You can then convert/format the datetime object as needed.

http://stackoverflow.com/comment/91261438
comment on: http://stackoverflow.com/q/52155404
score: 0
has text: Actually, this is gaskets, I can't think of diameter as a feature to consider from my point of view Cris. Since this gaskets come in irregular shapes too. Thank you for the tip, I'll try to figure out what else I can consider as feature by comparing two similar looking gaskets :)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91334847
score: 2
has text: Have you tried to manually run the command *Package Control: Satisfy Dependencies*?
comment on: http://stackoverflow.com/q/52187919
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91307494
comment on: http://stackoverflow.com/a/52154412
score: 0
type: AnswerComment
type: Comment
has text: Hi, onno! Thank you for your reply! I tried to use both methods, but when I run your code, I am still getting only one graph in the end. I am not sure which part is wrong as your explanation makes sense to me. I have attached the code and the output for your reference . code and output of the first method can be found here imgur.com/a/FxPBlRr ; that of the second method can be found here: imgur.com/a/sQGXLBl

http://stackoverflow.com/comment/91375889
has text: Because it doesn't answer the question. Anyway, I took it back.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52213127
type: AnswerComment

http://stackoverflow.com/comment/91185712
type: Comment
type: QuestionComment
has text: @DanSafee as he mentioned he needs updated Id which he might use to query or something for which we do not need to commit, a refresh will do the job in fetching the id.
comment on: http://stackoverflow.com/q/52116158
score: 0

http://stackoverflow.com/comment/91260063
type: Comment
type: AnswerComment
has text: Thanks a lot! I have one small additional requirement. It would be really helpful if you help me on the same! Updated the question accordingly.
score: 0
comment on: http://stackoverflow.com/a/52149678

http://stackoverflow.com/q/52117648
tagged with: python
upvote count: 4
tagged with: prediction
has body: I am trying to predict 2 features. This is how my model looks like: Defining the model def my_model(): input_x = Input(batch_shape=(batch_size, look_back, x_train.shape[2]), name='input') drop = Dropout(0.5) lstm_1 = LSTM(100, return_sequences=True, batch_input_shape=(batch_size, look_back, x_train.shape[2]), name='3dLSTM', stateful=True)(input_x) lstm_1_drop = drop(lstm_1) lstm_2 = LSTM(100, batch_input_shape=(batch_size, look_back, x_train.shape[2]), name='2dLSTM', stateful=True)(lstm_1_drop) lstm_2_drop = drop(lstm_2) y1 = Dense(1, activation='relu', name='op1')(lstm_2_drop) y2 = Dense(1, activation='relu', name='op2')(lstm_2_drop) model = Model(inputs=input_x, outputs=[y1,y2]) optimizer = Adam(lr=0.001, decay=0.00001) model.compile(loss='mse', optimizer=optimizer,metrics=['mse']) model.summary() return model model = my_model() for j in range(50): start = time.time() history = model.fit(x_train, [y_11_train,y_22_train], epochs=1, batch_size=batch_size, verbose=0, shuffle=False) model.reset_states() print("Epoch",j, time.time()-start,"s") p = model.predict(x_test, batch_size=batch_size) My data set has 9 features: x_train (31251, 6, 9) y_11_train (31251,) y_22_train (31251,) x_test (13399, 6, 9) y_11_test (13399,) y_22_test (13399,) I am trying to predict the first(y_11) and second(y_22) feature of my dataset. But I am getting prediction for only first feature not the second one. Any help on how can I get both the predictions instead of one?
tagged with: tensorflow
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52117977
tagged with: lstm
type: Question
has title: Keras model LSTM predict 2 features
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52117977
tagged with: keras
score: 4
favorite count: 0

http://stackoverflow.com/comment/91451975
comment on: http://stackoverflow.com/a/52176027
type: Comment
has text: Thanks, but what if I wanted to return multiple values?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91295911
has text: Just simple Django's Model.objects.all()
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52168027
type: QuestionComment

http://stackoverflow.com/a/52155929
has comment: http://stackoverflow.com/comment/91290949
has comment: http://stackoverflow.com/comment/91287874
has comment: http://stackoverflow.com/comment/91295843
has comment: http://stackoverflow.com/comment/91293403
score: 3
has comment: http://stackoverflow.com/comment/91269908
has comment: http://stackoverflow.com/comment/91291553
has comment: http://stackoverflow.com/comment/91266410
accepted answer of: http://stackoverflow.com/q/52140317
has comment: http://stackoverflow.com/comment/91535503
has body: pdata = pdata + ''' Επιλεκτική Αναζήτηση: %s %s %s <input type="image" src="/static/img/submit.gif" name="seek" value="<Αναζήτηση>"> ''' % (url_for( 'seek' ), \ ' '.join( names ), ''.join( map( lambda args: ' %s ' % (args[0], args[1]), enumerate(months) ) ), ' '.join( list( map( str, years ) ) ) ) print(pdata)
answers question: http://stackoverflow.com/q/52140317
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91262552
type: Answer
upvote count: 3

fft
tags question: http://stackoverflow.com/q/52179919
tags question: http://stackoverflow.com/q/52122123
tags question: http://stackoverflow.com/q/52218795
type: Tag
tags question: http://stackoverflow.com/q/52174178
tags question: http://stackoverflow.com/q/52243955
tag name: fft
tags question: http://stackoverflow.com/q/52224285

http://stackoverflow.com/comment/91186620
score: 0
comment on: http://stackoverflow.com/a/52117799
has text: What if the list item contains `tag2 P - tag3`?
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52248803
has body: You can't. An f-string isn't a kind of string, it's a kind of string literal, which is evaluated immediately. You can't store an f-string in a variable to be evaluated later, or accept one from a user, etc.1 This is the only reason that they're safe. So, what if you do want to use a format multiple times (or one taken from a user, etc.)? You use str.format. Occasionally, you need to capture all of the locals and globals the same way an f-string does, but to do it explicitly. Because this is a rare case (and potentially a security hole), it's intentionally a bit ugly: TEXT_AMOUNT = 'text {amount}' def f1(beginning): amount = 100 return beginning + TEXT_AMOUNT.format(**locals(), **globals()) This makes you think about what you're writing—you don't really want globals here, right? So leave it off. And it also signals the reader—if you're pulling in locals, they'll want to see that the string really is a constant in your source that isn't doing anything dangerous. 1. Well, you could use an f-string inside a string that you pass to eval… but that's a terrible idea.
has comment: http://stackoverflow.com/comment/91445645
type: Answer
accepted answer of: http://stackoverflow.com/q/52248776
score: 14
answers question: http://stackoverflow.com/q/52248776
type: AcceptedAnswer
downvote count: 1
upvote count: 15

mfcc
type: Tag
tag name: mfcc
tags question: http://stackoverflow.com/q/52232839

http://stackoverflow.com/q/52207065
score: 0
tagged with: mypy
has comment: http://stackoverflow.com/comment/91363579
linked to: http://stackoverflow.com/q/41417679
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/41417679
has comment: http://stackoverflow.com/comment/91363774
answer count: 0
has comment: http://stackoverflow.com/comment/91363866
has comment: http://stackoverflow.com/comment/91363922
has title: mypy is complaining about getting the length of an abstract Enum in python
tagged with: abstract-class
type: Question
has body: Consider the following MWE: from enum import Enum class IMeasurements(Enum): pass class _MYMeasurements(IMeasurements): FIRST = 0 SECOND = 1 class MYParser(): def __init__(self): pass @staticmethod def get_measurement_enum(): return _MYMeasurements parser = MYParser() weld_measurements_enum: IMeasurements = parser.get_measurement_enum() n_measures = len(weld_measurements_enum) print(n_measures) The project I am working on uses abstraction on several levels, to keep things modular and force implementations to adhere to some interfaces. Notably, the Enum IMeasurements doesn't have members as-is, but it's extension _MyMeasurements does. Now this code works, Python returns the expected value. But when checking this code for typing errors with mypy, I get the error message: Argument 1 to "len" has incompatible type "IMeasurements"; expected "Sized" One of my attempted solutions was to use EnumMeta in place of Enum for IMeasurements, but while this silents mypy, it leads to another error: TypeError: object of type 'type' has no len(). Is this a bug in mypy? If not, how am I supposed to proceed in those cases? Thanks!
tagged with: python
has comment: http://stackoverflow.com/comment/91363465

http://stackoverflow.com/comment/91388415
comment on: http://stackoverflow.com/a/52212276
type: Comment
has text: @Denziloe This approach has also another drawback but it can be significantly diminished by a small change in computation see [Edit3: Improving Newton d'Lambert integration precision even more](https://stackoverflow.com/a/28020934/2521214)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91381236
has text: There must be some way out , right?
comment on: http://stackoverflow.com/q/52215711
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52147216
type: Answer
upvote count: 1
has body: Given a list of lists input L with the structure as specified, you can flatten your list of lists and feed to np.array: import numpy as np from itertools import chain res = np.array(list(chain.from_iterable(L))) print(res) array([[ -80983.957, 175470.593, 393.486], [ -80994.122, 175469.889, 394.391], [ -80996.591, 175469.757, 394.595], ... [ -81029.668, 175472.131, 397.895], [ -80847.281, 175417.644, 378.2 ], [ -80853.651, 175417.621, 378.781]])
answers question: http://stackoverflow.com/q/52146977
downvote count: 0
score: 1

http://stackoverflow.com/q/52187616
type: Question
has comment: http://stackoverflow.com/comment/91325200
answer count: 2
has body: I am new to tkinter. I want to write two numbers in two different entries in GUI and see their updated subtraction result on the display. here is my code: from tkinter import * window = Tk() lb1 = Label(window,text="variable 1") lb1.pack() name1=IntVar() en1=Entry(window, textvariable=name1) en1.pack() lb2 = Label(window,text="variable 2") lb2.pack() name2=IntVar() en2=Entry(window, textvariable=name2) en2.pack() subt=IntVar() subt=name1.get()-name2.get() label_subt=Label(window, text=subt).pack() how can I update label_subt?
has title: how to update a variable in Tkinter
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/91325316
tagged with: user-interface
has answer: http://stackoverflow.com/a/52188599
has answer: http://stackoverflow.com/a/52187751
favorite count: 0
linked to: http://stackoverflow.com/q/17457178
possible better answer: http://stackoverflow.com/a/52187751
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/52188599
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/91283688
comment on: http://stackoverflow.com/q/52166973
type: Comment
type: QuestionComment
has text: I want to output 'sku'.
score: 0

http://stackoverflow.com/comment/91277779
has text: it has duplicated keys but in nested dictionary
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52164115
score: 0

http://stackoverflow.com/q/52261195
tagged with: python-2.x
has comment: http://stackoverflow.com/comment/91470428
accepted answer: http://stackoverflow.com/a/52261244
upvote count: 3
has body: When I enable an interpreter feature in Python 2 with a from __future__ import X statement (e.g. from __future__ import unicode_literals), the interpreter behavior changes from there on out. Is there a way, at runtime, to determine what __future__ pragmas have been enabled at a given point in execution? The reason I want to do this is that some legacy code I maintain conditionally enables some __future__ pragmas before evaling/runtime-importing other arbitrary code. When debugging behavior issues in that code, I want to check whether it's because some of those conditional __future__ imports have been triggered or not. I know that conditionally importing __future__ (or importing it at anything other than the top of an entry point) is an antipattern and have no plans of spreading it; I just want to debug code that does this. I've tried checking sys.modules, and using that I can tell that something from __future__ has been imported because the __future__ module shows up in the already-imported list. However, that's just the __future__ module, and the interpreter-behavior changes are not implemented as submodules, so I can't see which have been enabled or not.
type: AnsweredQuestion
score: 3
type: Question
has comment: http://stackoverflow.com/comment/91471250
has answer: http://stackoverflow.com/a/52261244
answer count: 1
downvote count: 0
favorite count: 0
has title: How can I tell what pragmas from '__future__' have been enabled at runtime in a Python program?
tagged with: python

http://stackoverflow.com/a/52221607
has body: The answers provided in this thread worked for me. It allows you to leave out optional parameters in the URL completely. This is the adjusted code example: class price_history(Resource): def get(self, from_=None, to=None): if from_ and to: return 'all data' if from_ and not to: return 'data beginning at date "from_"' if not from_ and to: return 'data going to date "to"' if not from_ and not to: return 'please provide at least one date' api.add_resource(price_history, '/price_history/from=&lt;from_&gt;/to=&lt;to&gt;', '/price_history/from=&lt;from_&gt;', '/price_history/to=&lt;to&gt;' )
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52219025
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52219025

http://stackoverflow.com/q/52115244
has comment: http://stackoverflow.com/comment/91181301
tagged with: python
has body: When I use scatter_matrix function from pandas, I get lots of text like array([[&lt;matplotlib.axes._subplots.AxesSubplot object at 0x000001BD9F985860&gt;, &lt;matplotlib.axes._subplots.AxesSubplot object at 0x000001BD9F9C0588&gt;, Anyone knows how to tell pandas not to return this text?
has comment: http://stackoverflow.com/comment/123269040
has answer: http://stackoverflow.com/a/52115582
has title: scatter_matrix in pandas returns lots of text - how to remove it?
type: Question
has comment: http://stackoverflow.com/comment/91181188
upvote count: 6
score: 4
has comment: http://stackoverflow.com/comment/91181637
answer count: 2
downvote count: 2
tagged with: visualization
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/52115956
type: UnansweredQuestion

http://stackoverflow.com/comment/91317420
score: 0
type: Comment
type: QuestionComment
has text: Well then how come you are doing a distance calculation? Your query above is the well known distance calculation sql query
comment on: http://stackoverflow.com/q/52127370

tensorboard
tags question: http://stackoverflow.com/q/52185422
type: Tag
tags question: http://stackoverflow.com/q/52200075
tags question: http://stackoverflow.com/q/52162387
tags question: http://stackoverflow.com/q/52228023
tags question: http://stackoverflow.com/q/52115445
tags question: http://stackoverflow.com/q/52182255
tag name: tensorboard
tags question: http://stackoverflow.com/q/52112771

http://stackoverflow.com/q/52137231
type: Question
upvote count: 2
tagged with: mongodb
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52137307
tagged with: access-token
has body: I am using mongodb with python and trying to figure out how should I store the access tokens, whether I should go with embedded documents and store access tokens in the same user's collection or create a new collection called access_tokens and keep a reference field of user in that? Here's the example with different collection: { "_id" : ObjectId("5b8bc5efac5a49b53fddb4d6"), "name" : "Rohit Khatri", "email" : "rohit@email.com", "username" : "rohit", "password" : "password" } { "_id" : ObjectId("5b8bdc2aac5a49b82c1f4e32"), "token" : "sf33849hskjdfhj9348khsjdf", "expires_at" : ISODate("2018-09-02T12:48:42.218Z"), "user_id" : { "$ref" : "users", "$id" : ObjectId("5b8bc5efac5a49b53fddb4d6") } } With embedded collection { "_id" : ObjectId("5b8bc5efac5a49b53fddb4d6"), "name" : "Rohit Khatri", "email" : "rohit@email.com", "username" : "rohit", "password" : "password", "access_tokens": [ { "token" : "sf33849hskjdfhj9348khsjdf", "expires_at" : ISODate("2018-09-02T12:48:42.218Z") } ] } Which way is better in terms of performance, scalability, etc.?
accepted answer: http://stackoverflow.com/a/52137307
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
has title: Storing access tokens in the user's collection is better or separate?

http://stackoverflow.com/q/52206940
possible better answer: http://stackoverflow.com/a/52207270
downvote count: 0
score: 1
type: Question
tagged with: discord.py
has answer: http://stackoverflow.com/a/52207112
accepted answer: http://stackoverflow.com/a/52207112
has body: I am using discord.py to make my discord bot and when somebody types a message I want to check if the user is lets say foo#3645 and then do something if it is not then do something else if(messageAuthor == "foo#3645): # do something else: # do something else I tried this: if(ctx.message.author == "foo#3465"): # do something but that is not working for some reason... If you need more info please comment.
answer count: 3
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91363483
has title: How to check if message was sent by certain user discord.py
has answer: http://stackoverflow.com/a/52207270
has answer: http://stackoverflow.com/a/61979530
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/52217601
has body: Consider the following DataFrame df: Date Kind 2018-09-01 13:15:32 Red 2018-09-02 16:13:26 Blue 2018-09-04 22:10:09 Blue 2018-09-04 09:55:30 Red ... ... In which you have a column with a datetime64[ns] dtype and another which contains a np.object which can assume only a finite number of values (in this case, 2). You have to plot a date histogram in which you have: On the x-axis, the dates (per-day histogram showing month and day); On the y-axis, the number of items belonging to that date, showing in a stacked bar the difference between Blue and Red. How is it possible to achieve this using Matplotlib? I was thinking to do a set_index and resample as follows: df.set_index('Date', inplace=True) df.resample('1d').count() But I'm losing the information on the number of items per Kind. I also want to keep any missing day as zero. Any help very appreciated.
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52218308
answer count: 1
downvote count: 1
score: 0
tagged with: matplotlib
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52218308
has title: How to plot stacked time histogram starting from a Pandas DataFrame?
tagged with: data-science
favorite count: 0
type: Question
tagged with: pandas

http://stackoverflow.com/comment/91424869
type: Comment
has text: Really nice solution and elegant ! I especially liked that you created the the double letter 5 times and the rest of the combinations made it two. I also liked that you gave better names for the variables. Great :)
comment on: http://stackoverflow.com/a/52236378
score: 0
type: AnswerComment

http://stackoverflow.com/q/52251389
score: 2
downvote count: 0
tagged with: typeerror
type: Question
type: AnsweredQuestion
has title: How to retrieve the values from the database with column name using python script?
tagged with: python
possible better answer: http://stackoverflow.com/a/52251475
has answer: http://stackoverflow.com/a/52251475
favorite count: 0
has body: I need to retrieve values from the database for the column names specified. The below code I've tried, import pyodbc def get_db_data(): cursor = getConnection.cursor() cursor.execute("select * from student") return cursor cur = get_db_data() for row in cur.fetchall(): print(row["student_name"]) I'm facing below error TypeError: row indices must be integers, not str How to achieve this?
upvote count: 2
answer count: 2
tagged with: select
has answer: http://stackoverflow.com/a/52251456
accepted answer: http://stackoverflow.com/a/52251456

http://stackoverflow.com/q/52140428
has title: OverLoading In python
favorite count: 0
has body: class tri: def __init__(self,x=0): self.x=x def __str__(self): return '({0})'.format(self.x) def __add__(self,one,two): length=self.x+one.x+two.x return length &gt;&gt;&gt;perp=tri(5) &gt;&gt;&gt;print(perp) &gt;&gt;&gt;base=tri(8) &gt;&gt;&gt;print(base) &gt;&gt;&gt;hyp=tri(9) &gt;&gt;&gt;print(hyp) &gt;&gt;&gt;print (perp+base+hyp) This is showing me: TypeError(): __add__() missing 1 required positional argument: 'two' What's the problem? I am not getting it.
downvote count: 2
has answer: http://stackoverflow.com/a/52140587
upvote count: 1
tagged with: python
tagged with: overloading
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/36785417
has comment: http://stackoverflow.com/comment/91230587
type: Question
duplicate of: http://stackoverflow.com/q/36785417
answer count: 2
accepted answer: http://stackoverflow.com/a/52140587
score: -1
possible better answer: http://stackoverflow.com/a/52140482
has answer: http://stackoverflow.com/a/52140482

http://stackoverflow.com/a/52133036
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52132916
answers question: http://stackoverflow.com/q/52132916
has body: You can control how results are persisted through a combination of setting the create_disposition and write_disposition. The python library exposes these options in QueryJobConfig, and links to more details from the REST API docs. For queries, the default behavior for write dispostion is WRITE_EMPTY, which causes a failure if the table already exists. Switching that to WRITE_TRUNCATE should give you the atomic replacement of data that you're looking for. TL;DR: just add this to your job config: job_config.write_disposition = bigquery.WriteDisposition.WRITE_TRUNCATE
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91409220
comment on: http://stackoverflow.com/q/52229706
score: 0
type: Comment
has text: Veera Samantula - As already stated, I'm not allowed to modify the last three lines.
type: QuestionComment

http://stackoverflow.com/comment/91485163
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52250332
type: QuestionComment
has text: I have several monitors and one of them is clear often enough that it is fun to have a live view of the sun there. Generally I'm thinking 10-30 files at most.

http://stackoverflow.com/comment/91368945
has text: I implemented a mix of your original and your edited answer to use this on training loss and validation loss. I then modified the on_batch_end method with an if statement so as to perform this every 20 iterations, in order not to slow the training too much.
type: Comment
comment on: http://stackoverflow.com/a/52206330
score: 1
type: AnswerComment

http://stackoverflow.com/a/52120676
score: 1
has body: You only receive pygame.KEYDOWN when the key is first pressed - not while it is held down. The simple solution is to only draw while the key is down (ie. when x_int != 0) #On Loop while ON == True: #Screen Event for Screen in pygame.event.get(): # &lt;Removed not relevant code for brevity&gt; #Player Movement K DOWN if Screen.type == pygame.KEYDOWN: if Screen.key == pygame.K_d: x_int = 20 if Screen.key == pygame.K_a: x_int = -20 #Player Movement K UP if Screen.type == pygame.KEYUP: if Screen.key == pygame.K_d or Screen.key == pygame.K_a: x_int = 0 # Render only happens if x_int is not zero # (Need to add code to force render first time) if x_int: x_axis += x_int Window.fill((back_color)) Player = pygame.draw.rect(Window, light_color, [x_axis, y_axis, Block_size, Block_size]) pygame.display.update() As the program grows and gets more complex, you'll need better logic for when to render, but this will get you started.
answers question: http://stackoverflow.com/q/52120258
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/91237948
comment on: http://stackoverflow.com/q/52144105
has text: You have 2 statements in your `timeit` call, you need to separate them either with a `;` or a newline `\n`.
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52175352
accepted answer: http://stackoverflow.com/a/52176277
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/52176337
has answer: http://stackoverflow.com/a/52176337
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91301869
has title: Django rest framework writeable nested serializer data missing from validated_data
has answer: http://stackoverflow.com/a/52176277
has body: I'm trying to create a writeable nested serialiser for my API endpoint, however upon entering my parent serialiser's create method the nested data doesn't appear in my validated_data dictionary like it is supposed to in the example here. Instead, the nested key is not even present in the dictionary. Instead, it looks like: {'foo': 'bar'}. So, the nested keys appear to be flattened, and any other nested object with the same keys are overwritten. Any clues as to what the problem might be? I have some fairly complicated validation logic, however after trimming all of this out the problem wasn't recitified, so it appears to be irrelevant. My models are defined thus: class Payment(models.Model): id = models.AutoField(primary_key=True) foo = models.CharField(max_length=15, blank=True, null=True) class Booking(models.Model): id = models.AutoField(primary_key=True) payment = models.ForeignKey(Payment, blank=True, null=True) My serializers: class PaymentSerializer(serializers.ModelSerializer): class Meta: model = Payment fields = '__all__' class BookingSerializer(serializers.ModelSerializer): payment = PaymentSerializer(source='*', write_only=True) def create(self, validated_data): print("Creating booking", validated_data) # Outputs "Creating booking {'foo': 'bar'}" payment_data = validated_data.pop('payment') # Obviously errors at this point primary_guest = Payment.objects.create(payment_data) booking = Booking.objects.create(**validated_data) # other creation related code return booking class Meta: fields = '__all__' My ViewSet: class PrebookingViewSet(viewsets.ModelViewSet): queryset = Booking.objects.all().order_by('id') serializer_class = BookingSerializer My request contains the following POST body: { "payment": { "foo": "bar" } }
answer count: 2
has comment: http://stackoverflow.com/comment/91301730
downvote count: 0
tagged with: django-rest-framework
favorite count: 0

http://stackoverflow.com/comment/91193492
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52121121
has text: Can you share the lines of code which generates these output?
score: 0

http://stackoverflow.com/comment/91260413
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52155123
has text: and assign the result of the function...
score: 2

http://stackoverflow.com/comment/91258357
score: 0
has text: i think no changes gonna happen if i delete those two lines. I am using pycharm
type: Comment
comment on: http://stackoverflow.com/q/52153985
type: QuestionComment

http://stackoverflow.com/comment/91562696
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52305223
has text: Thanks for your reply. I don't have the chance at the moment to try out your suggestions, but I'll get back as soon as I have. I was also thinking along the lines that it's still the same object, but with swapped out values. As for the "I'm not explicitly defining the value of _id, but letting pymongo do this for me" part, for me that's not an issue, but rather how I expect PyMongo to behave.
type: AnswerComment

http://stackoverflow.com/comment/91269701
has text: If you want help, post an mvce as suggested earlier.
comment on: http://stackoverflow.com/q/52159749
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52239582
type: Answer
answers question: http://stackoverflow.com/q/52237376
score: 6
upvote count: 6
has body: This comes from the case where you have multiple features (inputs) and one response variable (output). Then, the input X is a matrix with number_of_features columns and number_of_samples rows, and the output y is a column vector with number_of_samples elements. Following the convention of naming matrices with uppercase letters and vectors with lowercase letters, which is widely used in mathematics and/or related fields, it makes sense that X has to be uppercase and y has to be lowercase. If you only have one feature, so the input is a column vector and not a matrix, then x should be lowercase. And if you have multiple response variables and the output is a matrix, then Y should be uppercase. Finally, using more descriptive names than X and y is always a good idea. Then, following the PEP 8 convention uf using snake_case for variable names - or whatever the style guide you are following recommends - is the way to go.
downvote count: 0

http://stackoverflow.com/q/52264886
score: 0
has comment: http://stackoverflow.com/comment/91478143
type: Question
tagged with: hadoop
has title: How to access hdfs files direclty in python?
has comment: http://stackoverflow.com/comment/91479927
tagged with: python-2.7
tagged with: apache-spark
tagged with: python
tagged with: mrjob
has body: I am working on Hadoop and Spark Framework for clustering of images. I am using Python as my programming language.For map-reduce framework MRJOB package is used. The doubt i am having is how to access the hdfs files directly in python? For example if my file on hdfs is /a.txt now how do i access it in python directly to apply further processing. I looked at many libraries but i am not getting a concrete answer.I saw snakebite but it is only for python 2.
linked to: http://stackoverflow.com/q/51546108
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/52243752
answers question: http://stackoverflow.com/q/52243573
has comment: http://stackoverflow.com/comment/91436021
has comment: http://stackoverflow.com/comment/91435982
type: Answer
has body: for col in df.columns: if df[col].dtype == 'object': print('\nColumn Name:', col,) print(df[col].value_counts()) I found the solution myself...
score: 0
has comment: http://stackoverflow.com/comment/91436035

http://stackoverflow.com/comment/91370437
comment on: http://stackoverflow.com/a/52209070
score: 0
type: AnswerComment
has text: Thanks again! Sorry for being unclear, what I meant is that running 'multiple_agg([0,1,2])' or 'multiple_agg([1,3,0], '2016-01-01', '2017-12-31')' or 'multiple_agg([2,3,1], start_date='2017-01-01', end_date='2018-12-31')' return the same multi-index (Customer, then Category, Sub-Category, then Product'. I was thinking that the multi-index order would change based on what orders the levels were passed in.
type: Comment

http://stackoverflow.com/comment/91517937
type: AnswerComment
has text: Alright I see what's going on. Take a look at my edit.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52266953

http://stackoverflow.com/q/52136597
has body: A 1D complex number can be converted to a 2D real number matrix as shown below. How can I implement it in python?
has title: How to create real number matrix from a complex number
accepted answer: http://stackoverflow.com/a/52136643
downvote count: 1
type: AnsweredQuestion
score: -1
type: Question
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52136643
tagged with: python

http://stackoverflow.com/q/52261995
has comment: http://stackoverflow.com/comment/91473541
tagged with: python
tagged with: pygame
has title: Pygame 1.9.4. Installation Trouble
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/42019184
has answer: http://stackoverflow.com/a/52262178
has comment: http://stackoverflow.com/comment/91472294
has body: Using Windows/Python 3.7 and Pygame 1.9.4 is already installed, except I exited out of the terminal and can't find the version name to finish the installation. According to the book I'm following, I need to finish by typing in: "python -m pip install --user pygame-[version name].whl" I can't find the version name anywhere online. I remember it started with "pygame-18.0" Edit: It works now! It was installed the whole time. Still not sure what the book wants me to do with the whl file thing, but if that raises problems, I'll just restart the whole process again. Thank you!
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91472688
has comment: http://stackoverflow.com/comment/91473022
answer count: 1

http://stackoverflow.com/comment/91195034
comment on: http://stackoverflow.com/q/52121635
score: 0
has text: @tif, yes I did, corrected it now, thanks!
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91250843
comment on: http://stackoverflow.com/a/52149227
score: 0
type: AnswerComment
type: Comment
has text: Thanks. I've been trying with several W1, b1 combinations which have a solution. Solutions are not within the (0,1) bound sometimes. But the problem goes away when I add options = {"bland": True} to your program.

http://stackoverflow.com/q/52211884
has body: I program a solar system. ATM all the planet interact with the sun(Gravitation). Now I also want that the every planets interacts with all the other planets ( How it is in reality). I thought I could do that with a double for-loop. I tried it out but it didn't work. Could you help me? I think the mistake has something to do that with sun the planets had a fix point. But now its just always planet to planet. But I dont really know... Here is my code: from vpython import * #Konstanten zum rechnen s_rad0 = 6.9e8 s_rad1 = 30 * s_rad0 e_rad = s_rad1 * 0.9 m_rad = e_rad * 0.4 ae = 200 * s_rad0 #1 Astr. Einheit bezieht sich auf Ent. Sonne-Erde ae2 = 200 * s_rad0 #bezieht sich auf Ent. Sonne-Mond g = 6.6725e-11 framerate = 100 #array liste von Planeten planets = [] class Sphere(object): def __init__(self, pos, radius, make_trail): self.pos = pos self.radius = radius self.make_trail = make_trail class planet(Sphere): def __init__(self, pos, radius, make_trail, mass, velocity): super().__init__(pos, radius, make_trail) self.mass = mass self.velocity = velocity planetSphere = sphere (pos = self.pos, radius = self.radius, make_trail = self.make_trail, mass = self.mass, velocity = self.velocity) sun = planet(pos=vec(0,0,0),radius=s_rad1*1.5, make_trail=True, mass=2e30, velocity=vec(0,0,0)) mercury = planet(pos=vec(ae/3,0,0), radius=s_rad1/1.5, make_trail=True, mass=3.25e23, velocity=vec(0,0,-47000)) venus = planet(pos=vec(ae/1.6,0,0), radius=s_rad1/1.3, make_trail=True, mass=4.9e24, velocity=vec(0,0,-35000)) earth = planet(pos=vec(ae,0,0), radius=e_rad, mass=5.9e24, make_trail=True, velocity=vec(0,0,-25000)) mars = planet(pos=vec(ae*1.52,0,0), radius=s_rad1/1.8, make_trail=True, mass=6.4e23, velocity=vec(0,0,-24000)) jupiter = planet(pos=vec(ae*5.18,0,0), radius=s_rad1/1.2, make_trail=True, mass=10e27, velocity=vec(0,0,-9678)) saturn = planet(pos=vec(ae*9.5,0,0), radius=s_rad1/1.4, make_trail=True, mass=5.7e26, velocity=vec(0,0,-7678)) uranus = planet(pos=vec(ae*19.13,0,0), radi…
tagged with: astronomy
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/28014922
upvote count: 1
downvote count: 1
type: Question
tagged with: math
has answer: http://stackoverflow.com/a/52226191
score: 0
answer count: 2
has title: How to achieve that planets are influenced by the gravitation of other planets and not only sun?
tagged with: for-loop
has answer: http://stackoverflow.com/a/52212276
tagged with: vpython
has comment: http://stackoverflow.com/comment/91384764
favorite count: 0

http://stackoverflow.com/comment/91429148
comment on: http://stackoverflow.com/q/52240080
score: 0
type: Comment
type: QuestionComment
has text: Sorry I am fresh in Python. The output could be two parts. The first one is the headers of the csv file, such as ['play', 'weather', 'temperature'] . The second one can be this: [['yes', 'sunny', '77'], ['no', 'rainny', '60'], ['yes', 'windy', '70']...]

http://stackoverflow.com/comment/91250895
type: Comment
comment on: http://stackoverflow.com/q/52150008
score: 0
has text: That "the compute graph seems incorrect" is too vague & broad statement
type: QuestionComment

transferable
tags question: http://stackoverflow.com/q/52261050
type: Tag
tag name: transferable

http://stackoverflow.com/comment/91421164
has text: @SruthiV This sort of thing tends to depend on the terminal & OS. It's not hard to do it on a standard OS, but it gets tricky if you want it to be portable to non-standard quirky proprietary systems. ;)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52236219
type: Comment

http://stackoverflow.com/q/52141529
has body: I'm writing a hangman game and can't figure out how to account for words of varying lengths, and my code doesn't seem to work. Here are the steps: A word is randomly selected from a list of strings A board is built resembling ['_','_','_','_','_','_'] The user guesses a letter Replace the board with any matches in the word based on the input End the game when the turns are up or the letter has been found word = random.choice(i) guesses = 0 turns = 11 a = [['_']*len(word)] print(a) print ( word) while turns &gt; 0: letter = input('Enter a letter:') for i in range (0, 6): if word[0][i] == letter: a[0][i] = letter print(a) if a == word: turns -= 1 print("You won. ") else : turns -= 1
has answer: http://stackoverflow.com/a/52141601
tagged with: list
score: 0
type: Question
has comment: http://stackoverflow.com/comment/91232868
answer count: 3
has answer: http://stackoverflow.com/a/52141634
has title: How do I build a list of the same length as a string for my hangman game?
has answer: http://stackoverflow.com/a/52141632
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/98202540
comment on: http://stackoverflow.com/q/52205479
type: Comment
type: QuestionComment
has text: I am trying to solve same thing. Have you got any luck to solve this? How to define such a loss and metric?
score: 0

http://stackoverflow.com/comment/91492782
type: Comment
has text: @K-Log In the end, this is what I did. I was able to re-write the whole thing in Selenium in like 5 minutes, after spending the requisite time setting up Selenium and Chromedriver. Still would be great to do in `html_requests` if possible someday!
type: QuestionComment
comment on: http://stackoverflow.com/q/52264028
score: 0

http://stackoverflow.com/comment/91246685
comment on: http://stackoverflow.com/a/52148468
score: 0
has text: i tried but the output was: 0 Stunden, 0 Minuten und 11 Sekunden0 Tage, 0 Stunden, 0 Minuten und 10 Sekunden0 Tage, 0 Stunden, 0 Minuten und 9 Sekunden0 Tage, 0 Stunden, 0 Minuten und 8 Sekunden0 Tage, 0 Stunden, 0 Minuten und 7 Sekunden0 Tage, 0 Stunden, 0 Minuten und 6 Sekunden0 Tage, 0 Stunden, 0 Minuten und 5 Sekunden0 Tage, 0 Stunden, 0 Minuten und 4 Sekunden0 Tage, 0 Stunden, 0 Minuten und 3 Sekunden0 Tage, 0 Stunden, 0 Minuten und 2 Sekunden0 Tage, 0 Stunden, 0 Minuten und 1 SekundenCounter finished!
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52135026
has body: change your code to def insert(self, val, currentNode): if self.root is None: self.root = Node(val) elif currentNode.info &gt; val: if currentNode.left is None currentNode.left = Node(val) else: self.insert(val, currentNode.left) elif currentNode.info &lt; val: if currentNode.right is None currentNode.right = Node(val) else: self.insert(val, currentNode.right) and call it via tree.insert(val,tree.root)
has comment: http://stackoverflow.com/comment/91220017
answers question: http://stackoverflow.com/q/52134538
type: Answer
has comment: http://stackoverflow.com/comment/91220008
has comment: http://stackoverflow.com/comment/91220081
has comment: http://stackoverflow.com/comment/91220196
accepted answer of: http://stackoverflow.com/q/52134538
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91220975

http://stackoverflow.com/comment/91421934
type: Comment
comment on: http://stackoverflow.com/a/52236526
type: AnswerComment
score: 0
has text: @KaiserKatze: With the right decorator, probably, but you'd need to replace the methods with some other object type, which has its own messy consequences.

http://stackoverflow.com/q/52202852
has body: I have the following code import win32com.client as win32 outlook = win32.Dispatch('outlook.application') mail = outlook.CreateItem(0) mail.To = 'madanraj.c@sss.com; mail.Subject = 'Daily Backlog' mail.Send() I have two accounts in outlook and i installed redemption too, but struck how to switch account i saw vb code and i cant convert to python code set Session = CreateObject("Redemption.RDOSession") Session.MAPIOBJECT = Application.Session.MAPIOBJECT set Accounts = Session.Accounts for each Account in Accounts Debug.Print Account.Name next
favorite count: 0
has title: Need to switch accounts in outlook using python for sending email using other account
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/64966813
has answer: http://stackoverflow.com/a/52207308
downvote count: 1
type: Question
tagged with: outlook
has answer: http://stackoverflow.com/a/73412445
answer count: 3
tagged with: outlook-redemption

http://stackoverflow.com/comment/91483559
type: AnswerComment
has text: @MadPhysicist Yeah, that's right, edited, but just for OP to know how to create error message
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52267998

http://stackoverflow.com/q/52140611
has answer: http://stackoverflow.com/a/52140712
answer count: 2
has answer: http://stackoverflow.com/a/52140617
accepted answer: http://stackoverflow.com/a/52140617
possible better answer: http://stackoverflow.com/a/52140712
tagged with: beautifulsoup
has title: Scraping multiple pages with python
score: 0
tagged with: web-scraping
tagged with: python
type: AnsweredQuestion
has body: I'm trying to scrape a multiple page website with beautiful soup. The code works partially. It returns only the last one page instead of all pages. How can I fix the problem? # import libraries import urllib.request from bs4 import BeautifulSoup # specify the url aziende = [ '35-azienda-4_planets', '36-azienda-archivio_23', '24-azienda-bm', '16-azienda-brolese_virginio', '39-azienda-castellani', '19-azienda-centro_ottico_bisa', '25-azienda-comel_optik', '37-azienda-de_lorenzo_occhiali', '15-azienda-delta_laser', '34-azienda-dem', '21-azienda-erizzo', '3-azienda-evo', '27-azienda-farben_occhialeria', '32-azienda-gio__eyewear', '7-azienda-gipizeta', '42-azienda-h8', '20-azienda-idea_91', '5-azienda-lem', '41-azienda-lasertec', '22-azienda-le_thi_thu_thu', '28-azienda-m1', '1-azienda-mati_', '38-azienda-metal_dream', '30-azienda-mictu', '23-azienda-nete', '10-azienda-new_italian_design_eyewear', '31-azienda-okki_lux', '9-azienda-ottica_pra_floriani', '12-azienda-pao', '40-azienda-palladio_occhiali', '29-azienda-plastil_due', '17-azienda-punti_di_vista', '14-azienda-quemme', '4-azienda-red_line', '43-azienda-revert', '33-azienda-sm', '6-azienda-scussel', '8-azienda-sistem', '18-azienda-stile_italiano', '26-azienda-tecnodanta', '11-azienda-toffoli_costantino', '13-azienda-tri_color', '2-azienda-zago' ] for azienda in aziende: page_link = 'http://www.occhialeriabellunotreviso.it/' + azienda page = urllib.request.urlopen(page_link ) # query the website and return the html to the variable ‘page’ soup = BeautifulSoup(page, 'html.parser') # parse the html using beautiful soup and store in variable `soup` # Take out the &lt;div&gt; of name and get its value name_box = soup.find('h2') name = name_box.text.strip() # strip() is used to remove starting and trailing print (name)
type: Question

http://stackoverflow.com/comment/124151158
has text: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/70230372

deserialization
type: Tag
tag name: deserialization
tags question: http://stackoverflow.com/q/52262350

http://stackoverflow.com/q/52128613
tagged with: python
has comment: http://stackoverflow.com/comment/91207755
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91208815
has comment: http://stackoverflow.com/comment/91207841
tagged with: win32com
tagged with: ironpython
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91208753
has title: IronPython doesn't recognize win32com
has body: I need to run a software through IronPython ( I have to and can only use Ironpython and it's not a choice) . this software needs win32com library to be loaded so the software could be run. But Importing it in IronPython fails since it's not a recognized library. I tried to load win32com library in python and then try to run the software, and it was successful. But now the problem is that I need to run this python file through Ironpython, I mentioned the python name via : os.system("pythontry.py 1") It sounds like something has worked, cause I don't get the error win32com is not a recognized module, but from the other side, nothing happens . I mean that software does not run

http://stackoverflow.com/comment/91215137
type: QuestionComment
comment on: http://stackoverflow.com/q/52130812
score: 0
has text: @pygo sorry I’m on mobile or if write an answer. That second line of code df_cols is redundant as you could import all the columns you need in the read_csv command. You don’t not need to load a second DF into memory just to select certain columns. Instead just read in only the columns you want initially.
type: Comment

http://stackoverflow.com/q/52253378
tagged with: tensorflow
type: Question
tagged with: numpy
has title: Convert a tensor of shape (?,32,24,24) into a 3D numpy array
tagged with: arrays
score: -1
has body: I have a tensor with a batch of 32 grayscale images, each of size 24x24. The tensor is produced after a Conv2D layer in a CNN built using Keras with tensorflow backend. The data is provided to the model as a numpy array. Now, I wish to covert the output tensor into a numpy array, and again back into a tensor. I have referred to this page and wrote this simple piece of code that doesn't seem to work sess = tf.InteractiveSession() ip = np.array(x.eval()) here, x is my tensor and ip is the intended numpy array. This throws as InvalidArgumentError(). Is there any way I can get rid of the unkown (?) dimension? Here's the stack trace: Message=InvalidArgumentError() Source=c:\users\rangan\source\repos\fuzzycnn\fuzzycnn\fuzzyconv2d.py StackTrace: File "c:\users\rangan\source\repos\fuzzycnn\fuzzycnn\fuzzyconv2d.py", line 31, in call ip = np.array(x.eval()) File "c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\keras\engine\base_layer.py", line 507, in __call__ inputs=to_list(inputs)) File "c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\keras\engine\sequential.py", line 185, in add output_tensor = layer(self.outputs[0]) File "c:\users\rangan\source\repos\fuzzycnn\fuzzycnn\fuzzycnn.py", line 39, in baseline_model model.add(F_Conv2D(5)) File "c:\users\rangan\source\repos\fuzzycnn\fuzzycnn\fuzzycnn.py", line 49, in &lt;module&gt; model = baseline_model()
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91454375
has answer: http://stackoverflow.com/a/52253730
favorite count: 0
has comment: http://stackoverflow.com/comment/91454407
type: UnansweredQuestion
tagged with: python
upvote count: 0

http://stackoverflow.com/q/52118182
downvote count: 0
score: 1
tagged with: selenium
type: Question
answer count: 1
has title: Can't write date according to the content of the source
has comment: http://stackoverflow.com/comment/91187557
upvote count: 1
favorite count: 0
tagged with: python-3.x
tagged with: datetime
tagged with: python
tagged with: selenium-webdriver
has body: I've written a script in python in combination with selenium to parse some dynamic content from a webpage and write them to a csv file accordingly. The following script can do this errorlessly except for one thing the date. If you take a look at the content of that site, you can see that there is no year mentioned in that tabular data. However, when I click on any cell under Date column header in the output file, excel by default count it as the current year whereas the date should be 2004. How can I make the year 2004 according to what is being shown in the below image2? Script I'm trying with: import csv import datetime from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC url = "http://info.nowgoal.com/en/League/2004-2005/36.html" def get_information(driver,link): driver.get(link) for items in wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,'table#Table3 tr')))[2:]: try: date = items.find_elements_by_css_selector("td")[1].text.split("\n")[0] date = datetime.datetime.strptime(date, '%m-%d').strftime('%d-%B') except Exception: date = "" try: match_name = items.find_elements_by_css_selector("td")[2].find_element_by_tag_name("a").text except Exception: match_name = "" writer.writerow([date,match_name]) print(date,match_name) if __name__ == '__main__': driver = webdriver.Chrome() wait = WebDriverWait(driver,10) with open("outputfile.csv","w",newline="") as infile: writer = csv.writer(infile) writer.writerow(['Date','Match name']) try: get_information(driver,url) finally: driver.quit() This is how the date are being shown in the csv file: This is what you can see in that webpage:
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91187498
has answer: http://stackoverflow.com/a/52118392
accepted answer: http://stackoverflow.com/a/52118392

http://stackoverflow.com/q/52165938
has title: colorbar in 3D GIF
downvote count: 1
has comment: http://stackoverflow.com/comment/91282566
tagged with: python
has answer: http://stackoverflow.com/a/52167115
has body: So i am trying to plot the movement of particles in a box, and want to visualize the velocity with a colorbar. My Code looks like this import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.animation import FuncAnimation from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.axes_grid1 import make_axes_locatable fig = plt.figure() ax = fig.add_subplot(111, projection='3d') div = make_axes_locatable(ax) cax = div.append_axes('right', size='15%', pad='5%') tx = ax.set_title('Timestep 0') def update(t): tx.set_text('Timestep {0}'.format(t)) X,Y,Z,u,v,w=np.random.rand(6,6) track = ax.scatter(X, Y, Z, s=1, c=np.linalg.norm([u, v, w], axis=0), cmap=plt.cm.get_cmap('inferno')) cax.cla() plt.colorbar(track,cax=cax) return track, ax if __name__ == '__main__': anim = FuncAnimation(fig, update, frames=np.arange(10), interval=100, blit=False) anim.save('ClusterTrajectories.gif', dpi=150, writer='imagemagick') However, if i run that, i get following error Traceback (most recent call last): File "&lt;stdin&gt;", line 3, in &lt;module&gt; File "/home/itvmi/.local/lib/python2.7/site-packages/matplotlib/animation.py", line 1007, in save anim._init_draw() File "/home/itvmi/.local/lib/python2.7/site-packages/matplotlib/animation.py", line 1490, in _init_draw self._draw_frame(next(self.new_frame_seq())) File "/home/itvmi/.local/lib/python2.7/site-packages/matplotlib/animation.py", line 1512, in _draw_frame self._drawn_artists = self._func(framedata, *self._args) File "&lt;stdin&gt;", line 6, in update File "/home/itvmi/.local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 2262, in colorbar ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw) File "/home/itvmi/.local/lib/python2.7/site-packages/matplotlib/figure.py", line 1602, in colorbar cb = cbar.colorbar_factory(cax, mappable, **kw) File "/home/itvmi/.local/lib/python2.7/site-packages/matplotlib/colorbar.py", line 1347, in colorbar_factory cb = Colorbar(cax, mappable, **kwargs) Fi…
favorite count: 0
tagged with: colorbar
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91282107
tagged with: matplotlib
type: Question
tagged with: 3d
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/52167115
has comment: http://stackoverflow.com/comment/91281573
score: 0

http://stackoverflow.com/comment/91430097
comment on: http://stackoverflow.com/q/52240694
score: 0
type: Comment
type: QuestionComment
has text: @Abhi I just tried that again and the types are still "object." I don't understand.

http://stackoverflow.com/q/52258040
has title: Lambdify Sympy expression to NumPy containing Mod function
has comment: http://stackoverflow.com/comment/91465695
downvote count: 0
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: Similar to this question I got a problem with lambdifying a sympy expression containing the modulo function. Minimal example: from sympy import * modules = [str('numpy'),str('sympy')] x,y = symbols('x y') f = x%y g = lambdify((x,y),f,modules = modules) g(3.2,3) gives the error: Traceback (most recent call last): File "minimalexample.py", line 9, in &lt;module&gt; g(3.2,3) File "&lt;string&gt;", line 1, in &lt;lambda&gt; NameError: global name 'Mod' is not defined Is there a way to make this work? Thanks! SOLUTION: As answered in the comments I had an old version of sympy installed without noticing
has comment: http://stackoverflow.com/comment/91465406
score: 2
linked to: http://stackoverflow.com/q/26127414
has comment: http://stackoverflow.com/comment/91513408
type: Question
upvote count: 2
tagged with: numpy
tagged with: sympy

http://stackoverflow.com/a/52148671
downvote count: 0
has body: You can use a dictionary with pd.Series.map: d = {1: 1, 2: 2, 3: 2, 4: 2, 21: 2, 33: 4, 34: 4} data['CityID'] = data['CityID'].map(d).fillna(3) If the dictionary construction feels laborious, you can use unpacking: d = {1: 1, **dict.fromkeys((2, 3, 4, 21), 2), **dict.fromkeys((33, 34), 4}
type: Answer
score: 4
answers question: http://stackoverflow.com/q/52148632
accepted answer of: http://stackoverflow.com/q/52148632
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/a/52273633
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52247428
has comment: http://stackoverflow.com/comment/91511916
type: Answer
has body: My guess is your script is working perfectly and that the effect you are seeing (i.e. conversion to scientific format) is a result of the conversion of the CSV file into Excel (or other spreadsheet application). You should try opening the CSV file in a text editor such as Notepad. As a slightly bizarre workaround, you can convert it to text and prefix a tab character to it. This should stop the conversion: def writeExtended(id, idstr, full_text, display_text_range, created_at): #Write Extended tweet details to CSV file with open('Extended.csv', mode='a+', newline='') as employee_file: employee_writer = csv.writer(employee_file) employee_writer.writerow([id, '\t{}'.format(idstr), full_text, display_text_range, created_at]) writeExtended(count, tweet.id, tweet.full_text.encode('utf8'), tweet.display_text_range, tweet.created_at)
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52247428
type: AcceptedAnswer

search-engine
type: Tag
tags question: http://stackoverflow.com/q/52128097
tag name: search-engine

http://stackoverflow.com/comment/91444329
score: 1
has text: Yes, definitely.
type: AnswerComment
comment on: http://stackoverflow.com/a/52237811
type: Comment

http://stackoverflow.com/comment/91301665
type: AnswerComment
comment on: http://stackoverflow.com/a/52175455
has text: I appreciate the effort and while what you're suggesting would get me there, I was hoping pandas offered something more elegant. If that's not the case, It'll have to make do.
score: 0
type: Comment

http://stackoverflow.com/comment/91354573
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52202459
score: 1
has text: The thread may get stuck in requests.get. Try some timeout value and retry if request timeouts.

http://stackoverflow.com/a/52247856
has body: In your view/template you're trying to iterate through listalbumes but I don't see that being passed anywhere. So I think you need to pass album list in some way like this: @app.route('/artist/&lt;string:autor&gt;', methods=['GET', 'POST']) def artista(autor): autor = request.form.get("autor") if request.method == "GET": # Handle GET request alb = db.session.query(Album._id, Album.name, Album.autor, Album.year, Album.media, Album.continent).filter(Album.autor=autor) if alb.exists(): # Handle if matching album list exists return render_template("artist.html", {"listalbumes": alb}) else: # Handle if matching albumlist is not found return render_template("artist.html", {"listalbumes": []}) else: # Handle POST request Album.create(autor) return Response("Created", status=201)
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91443821
has comment: http://stackoverflow.com/comment/91444766
has comment: http://stackoverflow.com/comment/91447308
has comment: http://stackoverflow.com/comment/91447557
answers question: http://stackoverflow.com/q/52247813
has comment: http://stackoverflow.com/comment/91450781

http://stackoverflow.com/a/52249346
upvote count: 1
has comment: http://stackoverflow.com/comment/91476923
has body: There are several problems: zip is the wrong function if you want to compare the head rects with each rect in trail1 and trail2. You will only get pairs of rects at the same indices and also drop elements of the longer list. Take a look at this example: &gt;&gt;&gt; trail1 = [1, 2, 3] &gt;&gt;&gt; trail2 = ['a', 'b', 'c', 'd', 'e'] &gt;&gt;&gt; list(zip(trail1, trail2)) [(1, 'a'), (2, 'b'), (3, 'c')] Just iterate over the rects in the trail lists and check if char1 or char2 collide with them. # I skip the last few rects by slicing the list, otherwise they would collide immediately. for trail in trail1[:-5]: if OnRectCollison(char1, trail): print('collision') for trail in trail2: if OnRectCollison(char1, trail): print('collision') You append the same Rect objects (char1, char2) to the trail lists when you move, so the lists only contain references to the head rects and therefore only the heads of the trails are able to collide. trail1.append(char1) Append (shallow) copies instead: trail1.append(copy.copy(char1)) Side note: Collision is spelled incorrectly.
accepted answer of: http://stackoverflow.com/q/52247828
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52247828
type: Answer
score: 1

http://stackoverflow.com/comment/91468073
has text: nope, that was just a spelling mistake as I did not copy paste
type: Comment
comment on: http://stackoverflow.com/a/52259742
score: 0
type: AnswerComment

http://stackoverflow.com/q/52176612
tagged with: image
tagged with: pandas
has title: Strategy to combine RGB image (numpy array) and a pandas dataframe
has body: My background is primarily working on R but now I am working on a project where I need to use python, hence this question. My problem is relatively simple (I think): I have a set of RGB images in python represented as numpy arrays. I also have a dataset (which I have loaded as a pandas dataframe) with some characteristics which need to be mapped to the rows in the images. Now, the challenge is that the index in the dataframe is not the same as the row number in the images; I can derive a calculation that would link the index on the dataframe to the row on the image, but I don’t know how to incorporate this information into the image itself, so that by "looking" at the image I can extract the characteristics in the dataframe. In short, I think what I need is a way to join the information in the dataframe to the image. Not sure if I have made it clear so let me know how to better explain the problem. Thanks
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/91325001
score: 0
has comment: http://stackoverflow.com/comment/91315649
tagged with: numpy
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91398508
has text: Are you submitting the form after that? What error are you getting?
comment on: http://stackoverflow.com/q/52224669
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91373633
type: Comment
type: QuestionComment
has text: If `B` was (2000,100) you could use `np.dot`.
comment on: http://stackoverflow.com/q/52210441
score: 0

http://stackoverflow.com/comment/91370088
type: Comment
type: QuestionComment
score: 0
has text: What about other solutions as the ones mentioned here: https://stackoverflow.com/questions/543196/how-do-i-attach-a-remote-debugger-to-a-python-process
comment on: http://stackoverflow.com/q/52169226

http://stackoverflow.com/comment/91224414
comment on: http://stackoverflow.com/a/52137290
type: AnswerComment
score: 0
type: Comment
has text: @hpaulj: I thought it's clear why the failed approach doesn't work. The slice indices are expected to be integers and not as lists.

http://stackoverflow.com/comment/92194193
comment on: http://stackoverflow.com/q/52206248
score: 0
type: Comment
type: QuestionComment
has text: @MichaelButscher Thank you, this didn't work unfortunately.

http://stackoverflow.com/q/52259924
type: Question
tagged with: for-loop
has answer: http://stackoverflow.com/a/52259963
tagged with: nested-loops
has answer: http://stackoverflow.com/a/52259972
has body: I'm trying to generate some files which will have data from a for loop, and for now, I'm generating 20 files with the for loop of the following structure: for t in range(1, 20, 1): file = open("data_" + str(t) + ".txt", "w+") for E in range(1, 20, 1): stringData = str(t * E) file = open("data_" + str(t) ".txt", "a") file.write(stringData + '\n') file.close() However, I get the following syntax error: File "&lt;ipython-input-18-0fa0e5a273c1&gt;", line 52 file = open("data_" + str(t) ".txt", "a") ^ SyntaxError: invalid syntax Does anyone know what the specific error is? I thought this was occurring because I was missing a parenthesis somewhere but I am not so sure. I'm new to Python so any assistance would mean a lot! Thank you in advance!
score: 0
tagged with: syntax-error
answer count: 3
has title: Generating output files using a nested for loop in Python, and getting invalid syntax error?
has answer: http://stackoverflow.com/a/52259988
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91467263
tagged with: file

http://stackoverflow.com/q/52236296
has title: Extract substring between two characters - python DataFrame
has comment: http://stackoverflow.com/comment/91421171
score: 0
has body: What is the meaning of string locator ', \s*([^\.]*)\s*\.' =? I have a dataframe identical to Extract sub-string between 2 special characters from one column of Pandas DataFrame and want to extract the substring located between "," and ".". Thanks to the post answer, a way would be as below: In [157]: df['Title'] = df.Name.str.extract(r',\s*([^\.]*)\s*\.', expand=False) In [158]: df Out[158]: Name Title 0 Jim, Mr. Jones Mr 1 Sara, Miss. Baker Miss 2 Leila, Mrs. Jacob Mrs 3 Ramu, Master. Kuttan Master Although I see the outcome being correct, what is the meaning of ',\s*([^\.]*)\s*\.'? In particular, what is the meaning of '*' and '\'?
tagged with: pandas
answer count: 1
tagged with: python
linked to: http://stackoverflow.com/q/22937618
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52236353
linked to: http://stackoverflow.com/q/44000278
accepted answer: http://stackoverflow.com/a/52236353
has comment: http://stackoverflow.com/comment/91421344
type: Question

http://stackoverflow.com/a/52247585
answers question: http://stackoverflow.com/q/52222085
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91484076
has comment: http://stackoverflow.com/comment/91483939
has comment: http://stackoverflow.com/comment/91484036
accepted answer of: http://stackoverflow.com/q/52222085
score: 0
has body: pool.map is a blocking call, so instead of iterating over MAdict and calling pool.map you need to pass the iterable directly as an argument to pool.map: import pandas as pd from multiprocessing.dummy import Pool def moving_average(ma): return pd.Series.rolling(djia['Adj Close'], window=ma).mean() if __name__ == '__main__': N_WORKERS = 3 MA_DICT = {'MA50':50, 'MA100':100, 'MA200':200} djia = pd.read_csv('DJIA_OHLCV_test.csv') with Pool(N_WORKERS) as pool: results = pool.map(moving_average, iterable=MA_DICT.values()) # concatenate results and rename columns results = pd.concat(results, axis=1) results.columns = ['ma' + key for key in MA_DICT] djia = pd.concat([djia, results], axis=1) print(djia.tail())

http://stackoverflow.com/q/52218795
has comment: http://stackoverflow.com/comment/91387193
score: 0
has comment: http://stackoverflow.com/comment/91386028
tagged with: image-processing
has comment: http://stackoverflow.com/comment/91386840
type: Question
has comment: http://stackoverflow.com/comment/91387257
has body: I would like to remove vertical line from an image (an example). I took a 2D FFT and try to apply a mask to suppress the line. Nonethelesse the approch is not very efficient, because i lose an important part of information. How can i improve the treatment of FFT data? In FFT, how find the line? My piece of code : import numpy as np import matplotlib.pyplot as plt from skimage import io from skimage import data, img_as_float Path_input = "C:\\Users\\yoyo\\Desktop\\" imggray = img_as_float(data.astronaut())[:,:,0]*255 #opening image imggray[:,254:255] = 0 #force a vertical line plt.imshow(imggray);plt.show() imfft = np.fft.fft2(imggray) mags = np.abs(np.fft.fftshift(imfft)) angles = np.angle(np.fft.fftshift(imfft)) visual = np.log(mags) visual2 = (visual - visual.min()) / (visual.max() - visual.min())*255 plt.imshow(visual2);plt.show() mask = io.imread(Path_input + 'mask_astro.png')[:,:,0] mask = (mask &lt; 100) visual[mask] = np.mean(visual) newmagsshift = np.exp(visual) newffts = newmagsshift * np.exp(1j*angles) newfft = np.fft.ifftshift(newffts) imrev = np.fft.ifft2(newfft) newim2 = np.abs(imrev).astype(np.float32) plt.imshow(newim2);plt.show() ----- EDIT LATER ---- My "real" image: https://image.noelshack.com/fichiers/2018/36/5/1536312281-test.png
has title: Remove a line in image with FFT
has comment: http://stackoverflow.com/comment/91386764
has answer: http://stackoverflow.com/a/52219106
answer count: 1
has comment: http://stackoverflow.com/comment/91386231
tagged with: fft
has comment: http://stackoverflow.com/comment/91386084
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52126659
tagged with: python
has comment: http://stackoverflow.com/comment/91206040
has comment: http://stackoverflow.com/comment/91204575
has answer: http://stackoverflow.com/a/52127949
linked to: http://stackoverflow.com/q/47038538
has comment: http://stackoverflow.com/comment/91204288
type: Question
has body: I was hoping somebody would be able to help me. I am trying to store a list of saved images from MatPlotLib as a dataframe (or a list) and then add it to an existing dataframe (effectively creating small barcharts for each entry in the dataframe e.g. databars). I have managed to save the images successfully with a loop. There are 242 images. How can I show these images in a column in a dataframe. I want it to be easy to append it to my existing dataframe to show visually the number of zero values in this dataset. My code gives errors that it NoneType object is not iterable. This is my code. (Top half just here for clarification as to what q1 and q2 are.) Thanks. import csv import pandas as pd import matplotlib.pyplot as plt import numpy as np import sys q1 = pandas.read_csv("data\q1.csv") #dataframe q1.apply(lambda x: x.str.strip() if x.dtype == "object" else x) #strip whitespace q1 = q1.dropna() code = q1.loc[:,"Code"] region = q1.loc[:,"Region"] name = q1.loc[:,"Name"] heads = list(q1.columns.values) #creates list of header values nz = (q1 == 0).sum(axis=1) #count number of zero values in rows q2 = q1'Code','Region','Name' q2 = q2.assign(nz=nz.values) samples=[] y=1 for val in q2['nz']: val = val/q2['nz'].max() * 100 plt.barh(val, width = val, color="blue") plt.xlim((0,100)) plt.yticks([0]) plt.axis('off') x = plt.savefig("value" + str(y) + ".png", bbox_inches='tight') samples.append(x) plt.close() y = y + 1 imgdf = pandas.DataFrame.from_records(samples) q3 = q2.append(imgdf)
has comment: http://stackoverflow.com/comment/91205482
linked to: http://stackoverflow.com/q/46107348
tagged with: matplotlib
tagged with: image
has title: How can I add a list of saved images into an existing dataframe in pandas?
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/91204505
has comment: http://stackoverflow.com/comment/91205634
has comment: http://stackoverflow.com/comment/91205808
type: UnansweredQuestion

http://stackoverflow.com/comment/119146500
has text: @c0dezer019 This answer was for an older version, there have been some breaking changes since then, including renaming server to guild
comment on: http://stackoverflow.com/a/52156497
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52194346
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52194212
has body: You can use the invoke method of the Group object to invoke it directly from another coroutine: from discord.ext import commands bot = commands.Bot(command_prefix='!') @bot.group(pass_context=True) async def online(ctx): await bot.send_message(ctx.message.channel, "Group invoked") @bot.command(pass_context=True) async def invoker(ctx): await online.invoke(ctx) bot.run("Token")
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91338488
upvote count: 1
answers question: http://stackoverflow.com/q/52194212
score: 1

http://stackoverflow.com/q/52185208
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91323784
accepted answer: http://stackoverflow.com/a/52185519
has comment: http://stackoverflow.com/comment/91329423
score: 1
has comment: http://stackoverflow.com/comment/91333753
has body: I need to rebuild absolute frequencies from relative frequencies knowing the sample size. This should be easy but absolute frequencies and sample size are numpy.int64, relative frequencies are numpy.float64. I know floating-point decimal values generally do not have an exact binary representation and we can experience some loss of precision. This seems to be the case, the floating-point operation is producing unexpected results and I can't trust the rebuilt absolute frequencies. Sample code to replicate the error: import pandas as pd import numpy as np absolutes = np.arange(100000, dtype=np.int64) #numpy.int64 sample_size = absolutes.sum() # numpy.int64 relatives = absolutes / sample_size #float64 # Rebuilding absolutes from relatives rebuilt_float = relatives * sample_size #float64 rebuilt_int = rebuilt_float.astype(np.int64) df = pd.DataFrame({'absolutes': absolutes, 'relatives': relatives, 'rebuilt_float': rebuilt_float, 'rebuilt_int': rebuilt_int}) df['check_float'] = df['absolutes'] == df['rebuilt_float'] df['check_int'] = df['absolutes'] == df['rebuilt_int'] print('Failed FLOATS: ', len(df[df['check_float'] == False])) print('Failed INTS:', len(df[df['check_int'] == False])) print('Sum of FLOATS:', df['rebuilt_float'].sum()) print('Sum of INTS:', df['rebuilt_int'].sum()) Is it possible to solve the problem using numpy without casting every number to a decimal?
favorite count: 0
has answer: http://stackoverflow.com/a/52187741
type: Question
answer count: 2
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/52187741
has comment: http://stackoverflow.com/comment/91324064
has answer: http://stackoverflow.com/a/52185519
tagged with: numpy
downvote count: 0
tagged with: floating-accuracy
tagged with: comparison
has comment: http://stackoverflow.com/comment/91346271
has comment: http://stackoverflow.com/comment/91375290
has title: How to fix numpy floating-point operations producing inexact results?

http://stackoverflow.com/comment/91222050
has text: @zvone *middle allows me to average the middle items only(ignoring first and last element)
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52136002

http://stackoverflow.com/q/52241632
favorite count: 0
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91432118
tagged with: recurrent-neural-network
upvote count: 1
has answer: http://stackoverflow.com/a/52241648
downvote count: 1
tagged with: tensorflow
type: Question
has body: I am working with tensorflow in python now. And I've met an error which says init() got an unexpected keyword argument 'state_istuple' Do you have any ideas of it?
has title: __init__() got an unexpected keyword argument 'state_istuple'
has comment: http://stackoverflow.com/comment/91431840
accepted answer: http://stackoverflow.com/a/52241648
tagged with: lstm
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91431782

http://stackoverflow.com/comment/91277578
has text: @sathyz I deleted index =str and it should work know, thanks!
comment on: http://stackoverflow.com/q/52163734
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91343120
comment on: http://stackoverflow.com/q/52196843
score: 0
type: QuestionComment
has text: Are you trying to concatenate strings and variables? Does 'Text'+str(var) not work or is it not allowed for some reason?
type: Comment

http://stackoverflow.com/q/52205270
type: Question
has title: Problems with running xgboost in Python
accepted answer: http://stackoverflow.com/a/52205469
answer count: 1
downvote count: 0
tagged with: xgboost
favorite count: 0
has body: In running xgboost with Python I run into exceptions: For a reproducible example: import sklearn from sklearn import datasets data, labels = sklearn.datasets.load_diabetes(return_X_y= True) labels = (labels &gt; 100) * 1 X_train = data[:300, :] y_train = labels[:300] X_test = data[300:,:] y_test = labels[300:] dtrain = xgb.DMatrix(data = X_train, label = np.array(y_train), feature_names =['age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6']) dtest = xgb.DMatrix(data = X_test, label = np.array(y_test), feature_names = ['age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6']) param = {'colsample_bytree': 0.7, 'eta': 0.3, 'gamma': 3.0, 'max_depth': 6, 'min_child_weight': 4.0, 'objective': 'binary:logistic', 'reg_alpha': 0.3, 'reg_lambda': 0.3, 'silent': 0, 'subsample': 0.8} watchlist = [(dtest, 'eval'), (dtrain, 'train')] num_boost_round = 100 bst = xgb.train(params = param, watchlist = watchlist , dtrain = dtrain, num_boost_round = num_boost_round, \ early_stopping_rounds = True) This results in the exception: TypeError: train() got an unexpected keyword argument 'watchlist' If I remove watchlist I get another exception: bst = xgb.train(params = param, dtrain = dtrain, num_boost_round = num_boost_round, \ early_stopping_rounds = True) IndexError: list index out of range
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52205469
upvote count: 1

http://stackoverflow.com/q/52189166
possible better answer: http://stackoverflow.com/a/52190991
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52190991
has comment: http://stackoverflow.com/comment/91981405
type: Question
answer count: 2
has title: NotImplementedError: Wrong number or type of arguments for overloaded function Quantlib Python
tagged with: quantlib
score: 0
has answer: http://stackoverflow.com/a/52192008
has body: I am new to QuantLib and have just installed Quantlib and Quantlib-Python. I have MS Visual Studio 2017 and 2.7.15 64 bit. I am trying to work through the examples in Goutham Balaraman's blog (http://gouthamanbalaraman.com/blog/quantlib-basics.html). However, I am encountering an error. Code: # schedule object can be used to construct a list of dates such as coupon payments date1 = ql.Date(1, 1, 2015) date2 = ql.Date(1, 1, 2016) tenor = ql.Period(ql.Monthly) calendar = ql.UnitedStates schedule = ql.Schedule(date1, date2, tenor, calendar, ql.Following, ql.Following, ql.DateGeneration.Forward, False) schedule Error: --------------------------------------------------------------------------- NotImplementedError Traceback (most recent call last) &lt;ipython-input-5-cae31a33e500&gt; in &lt;module&gt;() 4 tenor = ql.Period(ql.Monthly) 5 calendar = ql.UnitedStates ----&gt; 6 schedule = ql.Schedule(date1, date2, tenor, calendar, ql.Following, ql.Following, ql.DateGeneration.Forward, False) 7 schedule c:\users\papu\envs\quantlib\lib\site-packages\QuantLib\QuantLib.pyc in __init__(self, *args) 9419 9420 def __init__(self, *args): -&gt; 9421 this = _QuantLib.new_Schedule(*args) 9422 try: 9423 self.this.append(this) NotImplementedError: Wrong number or type of arguments for overloaded function 'new_Schedule'. Possible C/C++ prototypes are: Schedule::Schedule(std::vector&lt; Date,std::allocator&lt; Date &gt; &gt; const &amp;,Calendar const &amp;,BusinessDayConvention const,boost::optional&lt; BusinessDayConvention &gt;,boost::optional&lt; Period &gt; const,boost::optional&lt; DateGeneration::Rule &gt;,boost::optional&lt; bool &gt;,std::vector&lt; bool,std::allocator&lt; bool &gt; &gt; const &amp;) Schedule::Schedule(std::vector&lt; Date,std::allocator&lt; Date &gt; &gt; const &amp;,Calendar const &amp;,BusinessDayConvention const,boost::optional&lt; BusinessDayConvention &gt;,boost::optional&lt; Period &gt; const,boost::optional&lt; DateGeneration::Rule &gt;,boost::optional&lt; …
has comment: http://stackoverflow.com/comment/91331071
accepted answer: http://stackoverflow.com/a/52192008
tagged with: python

http://stackoverflow.com/comment/91536444
comment on: http://stackoverflow.com/q/52203280
type: Comment
has text: Even if the answer is empty, you should get an http return code. It's more likely a apache or nginx issue, check the webserver logs in real time
score: 0
type: QuestionComment

http://stackoverflow.com/a/52178758
accepted answer of: http://stackoverflow.com/q/52178595
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52178595
has comment: http://stackoverflow.com/comment/91307694
type: Answer
has comment: http://stackoverflow.com/comment/91307891
has comment: http://stackoverflow.com/comment/91307847
score: 2
upvote count: 2
has body: Pylint thinks that myvar is a constant by convention, because it is global (declared on module level). Generally, you should not be writing code like this on a module level, wrap it in a function instead: def main(): i = 0 while i &lt; 4: myvar = i i = i + 1 if __name__ == '__main__': main()
has comment: http://stackoverflow.com/comment/91307975

http://stackoverflow.com/comment/91674664
type: QuestionComment
has text: @Robert I've seen this tutorial before, but it didn't really explain why they do not using stacking anymore. I found what I was looking for in the paper I posted above.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52221103

http://stackoverflow.com/q/52157214
has comment: http://stackoverflow.com/comment/91268793
type: Question
has comment: http://stackoverflow.com/comment/91265965
has comment: http://stackoverflow.com/comment/91264953
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/91266323
has answer: http://stackoverflow.com/a/52180886
has comment: http://stackoverflow.com/comment/91267309
tagged with: python-2.7
tagged with: importerror
answer count: 2
tagged with: python-import
has comment: http://stackoverflow.com/comment/91265209
has comment: http://stackoverflow.com/comment/91267327
favorite count: 0
has body: I have gone through numerous answers and tried most of them as well but still facing the same issue My structure -- backend -- app -- __init__.py -- utils.py -- models.py -- pytest -- test_utils.py` Now I want to import utils into the test_utils to be able to call the function and test it. My init.py is not empty and my test_utils.py looks like this import sys, os.path sys.path.insert(0 ,(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) + '/app/')) from utils import test_function def test_test_function(): a = test_function(5) assert a == 5 I checked my sys path is also pointing to correct directory but keep getting this error and I am using Python 2.7 in Linux ImportError while importing test module '/home/richie/Documents/Project/backend/pytest/test_utils.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: ../virenv/local/lib/python2.7/site-packages/six.py:709: in exec_ exec("""exec _code_ in _globs_, _locs_""") test_utils.py:3: in &lt;module&gt; from utils import test_function ../app/utils.py:15: in &lt;module&gt; from models import Users, Accounts ../app/models.py:2: in &lt;module&gt; from app import db E ImportError: No module named app
type: UnansweredQuestion
has title: Import error from different directory in python (Err - No module named app)
tagged with: python
has comment: http://stackoverflow.com/comment/91265940
has comment: http://stackoverflow.com/comment/91265692
has comment: http://stackoverflow.com/comment/91266004
tagged with: pytest
has answer: http://stackoverflow.com/a/52158692
downvote count: 2

http://stackoverflow.com/comment/91326900
type: Comment
comment on: http://stackoverflow.com/a/52188494
type: AnswerComment
has text: @deceze Certainly, yours is more transparent for a beginner and, adding the condition to the generator, teaches another aspect :)
score: 0

http://stackoverflow.com/q/52248287
has comment: http://stackoverflow.com/comment/91444850
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/91444498
has title: How do I find text after a given key word?
score: -2
has comment: http://stackoverflow.com/comment/91445005
has comment: http://stackoverflow.com/comment/91445193
type: Question
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52248384
has body: I am practicing my programming skills (in Python) and I realized that I don't know what to do when I need to find a value that is unknown but introduced by a key word. I am taking the information for this off a website where in the page source it says, '"size":"10","stockKeepingUnitId":"(random number)"' How can I figure out what that number is. This is what I have so far -- def stock(): global session endpoint = '(website)' reponse = session.get(endpoint) soup = bs(response.text, "html.parser") sizes = soup.find('"size":"10","stockKeepingUnitId":')
favorite count: 0
has comment: http://stackoverflow.com/comment/91444470
has comment: http://stackoverflow.com/comment/91444576
has comment: http://stackoverflow.com/comment/91444500
has comment: http://stackoverflow.com/comment/91444538
tagged with: python

http://stackoverflow.com/comment/91383120
type: Comment
comment on: http://stackoverflow.com/q/52216271
score: 0
has text: @Aran-Fey I'll try, thanks a lot :)
type: QuestionComment

http://stackoverflow.com/comment/91233315
score: 0
type: AnswerComment
has text: When I use random.shuffle(), the terminal prints 'None'. Am I wasting my time trying to solve it with filtering and recursion?
comment on: http://stackoverflow.com/a/52141713
type: Comment

http://stackoverflow.com/q/52224285
tagged with: python
accepted answer: http://stackoverflow.com/a/52250360
has title: How to fix shift and scaling errors in an FFT-powered differentiation program?
type: AnsweredQuestion
upvote count: 2
type: Question
tagged with: numpy
tagged with: discrete-mathematics
linked to: http://stackoverflow.com/q/48133518
has answer: http://stackoverflow.com/a/52250360
score: 2
answer count: 1
downvote count: 0
favorite count: 0
has body: So I am trying, like many others before me, to sift through all the celestial alignments of phase shifts and normalization coefficients necessary to make differentiation via Fourier transform work. I am trying to use as little code as possible, making total use of numpy functionality to keep the code clean while using its array operations, which, I was told, are faster than explicit python loops. From line 106 of the table of Functional relationships, One-dimensional, in the section about Important Fourier Transforms of the Wikipedia article on Fourier Transforms, I get that the Fourier transform has this property where differentiation in real space is equivalent to multiplication in frequency space such that d^nf/dx^n = ifft[F*(i*w)^n], where F is the fourier transform of f. Looking for a more solid reference to define the what the w would be in d^nf/dx^n = ifft[F*(i*w)^n], I found a PDF paper on the mathematics of differentiating using DFT. In the paper, the author discusses that there are infinitely many of the so-called trigonometric interpolations for a given function and shows a way to obtain to "less wiggly" solution, which is unique. So I used his definitions and wrote a small python code to do the differentiations. The code I came up is this one (pay attention to the last two lines, since they will change) N = 51 a = 0 b = 2*np.pi X = np.linspace(a,b, N) L = abs(b-a) TwoPiOverL = 2.0*np.pi/L freqs = np.fft.fftfreq(N,1./N) # THESE COME FROM [1] # D1 = TwoPiOverL*freqs*1j D2 = -(TwoPiOverL*freqs)**2 #=========================# S = np.sin(X) fftS=np.fft.fft(S) C = np.cos(X) # COMPUTING THE DERIVATIVES # Y1 = np.fft.ifft(D1*fftS).real Y2 = np.fft.ifft(D2*fftS).real In the figures of the graphs generated, the notation ~d/dx sin means the derivative of the sine function evaluated according to the Fourier Transform multiplication, instead of the analytical expression. Test 1 First Test, using only the definitions found in the PDF: So the first test was a mess. The…
tagged with: fft
tagged with: differentiation

http://stackoverflow.com/q/52141240
tagged with: image
has comment: http://stackoverflow.com/comment/91232252
downvote count: 0
answer count: 1
favorite count: 0
has title: OpenCv inversion: BGR to HSV then back to BGR - shouldn't I get the same image?
has answer: http://stackoverflow.com/a/52141348
tagged with: python
has body: For example, when I run this: import cv2 import numpy as np from collections import Counter # load image, calculate some basic stats path = 'path/to/my/image.png' bgr_img = cv2.imread(path) h, w, c = bgr_img.shape print("There are %d entries in this %d channel image" % (h*w*c, c)) # convert and then invert, we should get the same image bgr_img2 = cv2.cvtColor(cv2.cvtColor(bgr_img, cv2.COLOR_BGR2HSV), cv2.COLOR_HSV2BGR) print("all entries match: %s" % np.all(bgr_img == bgr_img2)) # hmm, we don't. let's see where the differences are mismatches = np.where(bgr_img != bgr_img2) print("there are %d mismatched entries" % len(mismatches[0])) print("mismatches are along the following channels: %s" % Counter(mismatches[2])) # ok, clearly lots of them. maybe they're all just off by 1 or 2? mm = zip(mismatches[0], mismatches[1], mismatches[2]) differences = [] for x, y, c in mm: diff = bgr_img[x, y, c] - bgr_img2[x, y, c] differences.append(diff) print(differences) I get the following output: There are 1228800 entries in this 3 channel image all entries match: False there are 524511 mismatched entries mismatches are along the following channels: Counter({1: 270572, 0: 253939}) [1, 1, 1, 254, 1, 254, 1, 3, 1, 3, 1, 3, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 1, 3, 1, 3, 1, 3, 1, 254, 1, 254, 254, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, ...] I see a couple possibilities. First is that BGR -> HSV conversion isn't strictly invertible. Other is that I'm using OpenCV incorrectly. Which is it?
type: AnsweredQuestion
tagged with: hsv
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52141348
tagged with: opencv

http://stackoverflow.com/a/52199779
has body: you can convert your data type to object like this : def set_label(data_all, Labels, hc): loc_1=len(data_all[0]) labels= Labels insert_h = np.insert(data_all,loc_1,labels,axis=1) label_store =[] for i in range(len(labels)): hmax = labels[i] if hmax &lt; hc: label_store.append(0) elif hmax &gt; hc: label_store.append(1) loc_2= len(insert_h[0]) #this is what I added to your code insert_h = np.insert(np.array(insert_h,dtype='O'),loc_2,np.array(labels,dtype = np.int),axis=1) return insert_h and your output would be like this : array([[0.111886399, 2.83619339, 3.14394233, 1.0, 1], [0.229317271, 1.87929947, 3.14713896, 1.0, 1], [0.0369530173, 3.525601, 5.05051823, 1.5, 1], [0.156559513, 2.10847705, 3.8871538, 1.5, 1], [0.00244876157, 6.02824866, 10.2350953, 5.0, 5], [0.00938766706, 4.8969895, 6.28692713, 5.0, 5]], dtype=object) or when you want to select your label and convert it to one hot convert labels type to integer : np.array('your selected array',dtype = np.int)
answers question: http://stackoverflow.com/q/52196699
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/a/72057616
has comment: http://stackoverflow.com/comment/127337831
answers question: http://stackoverflow.com/q/52163423
downvote count: 0
score: 1
has body: How-to create a link using BeautifulSoup with label, attrs and target import bs4 def a_href(url, label='', target='_blank', **kwargs): soup = bs4.BeautifulSoup('') combined_attrs = dict(target=target, href=url, **kwargs) tag = soup.new_tag(name='a', attrs=combined_attrs) tag.string = label return str(tag) # or tag.prettify() for better formatting Tests class TestAHref(TestCase): def test_simple_link(self): self.assertEqual('', a_href('www.ya.com')) def test_link_with_attrs(self): self.assertEqual('XYZ', a_href('ya.com', x=1, y=2, target='_self', label='XYZ'))
type: Answer
has comment: http://stackoverflow.com/comment/127332746
upvote count: 1

http://stackoverflow.com/comment/91260858
has text: Functions are first order citizens in Python. This means you can not just define functions, but assign them as variables, and pass them as arguments to other functions. They are truly objects. You can for example write a plotting function which takes a function as one of its arguments. Then you do `def f(x):` and pass `f` to the plotting function. Might this achieve what you want?
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52155194

http://stackoverflow.com/q/52182901
score: 1
type: Question
tagged with: numpy
has title: Seeking explanation to Dask vs Numpy vs Pandas benchmark results
accepted answer: http://stackoverflow.com/a/52184787
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/52184787
answer count: 1
favorite count: 0
tagged with: dask
has body: I am trying to benchmark the performance of dask vs pandas. def make_pandas(n): df = pd.DataFrame(np.random.randint(10, size=(n, 3))) return df def make_dask(n): df = da.from_array(np.random.randint(10, size=(n, 3)), chunks=10) return df def make_numpy(n): return np.random.randint(10, size=(n, 3)) def sum_pandas(x): return x[0].sum() def sum_dask(x): return x[1].sum() def sum_numpy(x): return x[2].sum() perfplot.show( setup=lambda n: [make_pandas(n), make_dask(n), make_numpy(n)], kernels=[sum_pandas, sum_dask, sum_numpy], n_range=[2**k for k in range(2, 15)], equality_check=False, xlabel='len(df)') Can someone explain the results: Increasing the chunks to 1000, 8000 and 10000 gives these respectively: Processor: Intel® Core™ i5-7300HQ CPU @ 2.50GHz × 4 Memory: 7.7 GiB Python: 3.5.2 pandas: 0.21.0 numpy: 1.13.1 dask: 0.19.0 Isn't dask supposed to parallelize and be better as size increases?
tagged with: python
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/52184270
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91319217
has comment: http://stackoverflow.com/comment/91320708
has comment: http://stackoverflow.com/comment/91319249
has comment: http://stackoverflow.com/comment/91320503
has comment: http://stackoverflow.com/comment/91319452
downvote count: 1
type: Question
tagged with: mongodb
tagged with: counter
linked to: http://stackoverflow.com/q/52029520
has comment: http://stackoverflow.com/comment/91320027
has comment: http://stackoverflow.com/comment/91319098
has comment: http://stackoverflow.com/comment/91324207
score: 0
has comment: http://stackoverflow.com/comment/91320985
has body: I have a following mongoDBschema- ObjectIDs are multiple entries in the database ,in which the further data is stored. ObjectId("a") posts [0] comments [0] comment fb_id [1] [2] [3] [4] ObjectId("b") ObjectId("c") I am trying to cumulatively add the sentiment value,I am assigning to the dictionary for each comment corresponding to every fb_id.I tried using counter method but it's values are emptying before entering another id's comment automatically. Earlier,I asked this question-Cumulatively add values to python dictionary and the output ,I received is below- Counter({'100002204201460': 0.0}) Counter({'100002204201460': 0.0, '100025548426588': -0.592}) Counter({'1490834948': 0.5792, '100002204201460': 0.0, '100025548426588': -0.592}) Counter is emptying itself before entering into another comment of same post. My implementation- for doc in result: dict_of_comments = Counter() for post in doc['posts']: # traverse each user's post if 'comments' in post: for com in post['comments']: s=com['comment'] vs=analyzer.polarity_scores(s) //sentiment analyser dict_of_comments[com['fb_id']] += vs['compound'] pprint.pprint(dict_of_comments) How to do it correctly,I just want to cumulatively add values without losing any of the values as currently ,I am loosing using Counter. Input in one of the objectID { "_id" : ObjectId("5b7fa2a745d12b10324d3a01"), "date_time" : "24, Aug 2018 11:44", "original_query" : "sanjeevnewar", "posts" : [ "comments" : [ { "comment" : "आशीष जी को कोटि कोटि प्रणाम।", "commentator" : "Amrit Kumar Deb", "fb_id" : "100002204201460" }, { "comment" : "Double standard is not going to work Stop ogling over Muslim women", "commentator" : "Akif Khan", "fb_id" : "100025548426588" } ] ] } Output ,if a standard dictionary is used without using Counter is as below {'100002204201460': 0.0} {'100002204201460': 0.0, '100025548426588': -0.296} This is just a sample output, not all values are included. But the issue is if my program encounters a same fb_id value(which is …
has title: Cumulatively add values to python dictionary without using Counter
favorite count: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52269158
has title: Cannot Export NDVI Layer To Google Drive
accepted answer: http://stackoverflow.com/a/52299374
tagged with: python
tagged with: google-earth-engine
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52299374
type: Question
has body: I wish to export NDVI layer as image to my Google Drive. I can run the code seamlessly but nothing is exported into my drive after the code is executed. Here is my code: import ee import ee.mapclient import datetime import ee.batch as batch ee.Initialize() roi_lat = 14.82762 roi_lon = 101.079659 ullat = roi_lat + 0.01 ullon = roi_lon - 0.01 lrlat = roi_lat - 0.01 lrlon = roi_lon + 0.01 geometry = ([ullon,ullat], [lrlon, ullat],[lrlon, lrlat],[ullon, lrlat]) l8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA') image = ee.Image( (l8.filterBounds(point) .filterDate(datetime.datetime(2018, 1, 1), datetime.datetime(2018, 12, 31)) .sort('CLOUD_COVER') .first() ) ) def NDVI(image): return image.expression('float(b("B5") - b("B4")) / (b("B5") + b("B4"))') ndvi = l8.map(NDVI).mean() visualization = ndvi.visualize({ 'min': 0, 'max': 1, 'palette': ['FFFFFF', 'CE7E45', 'DF923D', 'F1B555', 'FCD163', '99B718', '74A901', '66A000', '529400', '3E8601', '207401', '056201', '004C00', '023B01', '012E01', '011D01', '011301'] }) task_config = { 'description': 'NDVI', 'scale': 30, 'region':geometry } print("Starting to create a image") out = ee.batch.Export.image(visualization,'l8_ndvi', task_config) process = batch.Task.start(out) print("Process sent to cloud") If anyone has any knowledge. Please enlighten me where did I go wrong? Thanks.
has comment: http://stackoverflow.com/comment/91545575
tagged with: python-2.7
score: 0
answer count: 1

http://stackoverflow.com/a/52267934
has body: I'm assuming that you are using a for loop to iterate the string in question string = 'ABCD 1NAME 123456' for i in string: if i.isdigit(): print(i) You probably should use split(): string = 'ABCD 1NAME 123456' for i in string.split(): if i.isdigit(): print(i)
type: Answer
answers question: http://stackoverflow.com/q/52267712
score: 0

http://stackoverflow.com/comment/91261125
has text: That would also work for `99.10.2018Any text..` which is an invalid date...
comment on: http://stackoverflow.com/a/52155411
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91437357
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52244354
type: AnswerComment
has text: @ElectRocnic, by default, yes. You can override a bunch of stuff if you really want to but out of the box it exposes Django's built-in auth over API endpoints.

http://stackoverflow.com/comment/91502281
type: AnswerComment
has text: Right, so this line probably isn't the one causing memory problems. It's just the line where things finally fail because some part of the process is hogging memory. Did you run `top` and what did it show?
type: Comment
comment on: http://stackoverflow.com/a/52267375
score: 0

http://stackoverflow.com/comment/91365763
comment on: http://stackoverflow.com/q/52208153
score: 1
has text: Is your `y2` really what you mean, or should it have `level=[0]`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91260408
comment on: http://stackoverflow.com/q/52136511
has text: `if prd in retentinon_approval_log: if approval_check(roletype, prd, pth) == False:` is the same as `if prd in retentinon_approval_log and approval_check(roletype, prd, pth) == False:`. Is that what you asked for?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91376235
comment on: http://stackoverflow.com/q/52194145
score: 1
has text: @jpp - This problem is not just about merging, it also addresses the issue of having multiple values per row which must be handled some way.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91467786
type: QuestionComment
has text: That being said, I think it might be better to use an `annotate` here, this will result in performing a single query.
comment on: http://stackoverflow.com/q/52260091
score: 0
type: Comment

http://stackoverflow.com/q/52244188
tagged with: python-typing
favorite count: 0
type: UnansweredQuestion
tagged with: python
type: Question
tagged with: mypy
has comment: http://stackoverflow.com/comment/91436675
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/76761169
has title: Type annotation for a function returning a function taking args and kwargs
downvote count: 0
answer count: 1
has body: The following example code works at runtime, but is not accepted by mypy --strict: from typing import Any, Callable, TypeVar TypeT = TypeVar('TypeT') def log_call(msg: str) -> Callable[..., TypeT]: def do_call(func: Callable[..., TypeT], *args: Any, **kwargs: Any) -> TypeT: print(msg) return func(*args, **kwargs) return do_call def double(val: int) -> int: return 2 * val def plus(a: int, b: int) -> int: return a + b def plus_plus(a: int, b: int, c: int) -> int: return a + b + c result_1 = log_call('hi')(double, 1) result_2 = log_call('hi')(plus, 2, 3) result_3 = log_call('hi')(plus_plus, 2, 3, 4) result_4 = log_call('hi')(double, val=1) print(result_1) print(result_2) print(result_3) print(result_4) mypy output: test.py:26: error: Need type annotation for 'result_1' test.py:27: error: Need type annotation for 'result_2' test.py:28: error: Need type annotation for 'result_3' test.py:30: error: Need type annotation for 'result_4' test.py:32: error: Cannot determine type of 'result_1' test.py:33: error: Cannot determine type of 'result_2' test.py:34: error: Cannot determine type of 'result_3' test.py:35: error: Cannot determine type of 'result_4' Now instead of adding the type annotations to the result* variables, I would like to adjust the type annotation of the function, so the others can be deduced. This is my attempt: from typing import Any, Callable, TypeVar TypeT = TypeVar('TypeT') def log_call(msg: str) -> Callable[[Callable[..., TypeT], Any, Any], TypeT]: def do_call(func: Callable[..., TypeT], *args: Any, **kwargs: Any) -> TypeT: print(msg) return func(*args, **kwargs) return do_call def double(val: int) -> int: return 2 * val def plus(a: int, b: int) -> int: return a + b def plus_plus(a: int, b: int, c: int) -> int: return a + b + c result_1 = log_call('hi')(double, 1) result_2 = log_call('hi')(plus, 2, 3) result_3 = log_call('hi')(plus_plus, 2, 3, 4) result_4 = log_call('hi')(double, val=1) print(result_1) print(result_2) print(result_3) print(result_4) Howe…

http://stackoverflow.com/comment/91350586
score: 0
type: Comment
has text: hey, A small question. `for string in ['A','B']` this selects the data which is in the list. What if I want the data which does not contain these list ? help please.
comment on: http://stackoverflow.com/a/52198564
type: AnswerComment

http://stackoverflow.com/comment/91452891
score: 0
comment on: http://stackoverflow.com/q/52249803
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/20281372/how-to-deal-with-the-pyobject-from-c-in-python

http://stackoverflow.com/comment/91355168
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52194837
type: Comment
has text: I have edited and put the full code.

http://stackoverflow.com/a/52275334
upvote count: 3
has comment: http://stackoverflow.com/comment/91530386
has comment: http://stackoverflow.com/comment/91512115
has comment: http://stackoverflow.com/comment/91512134
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91581999
accepted answer of: http://stackoverflow.com/q/52262052
has comment: http://stackoverflow.com/comment/91582527
score: 3
answers question: http://stackoverflow.com/q/52262052
type: Answer
has body: If I was correct read docs, you can not create multiple headers. First possible solution is to move headers to values: import plotly import plotly.graph_objs as go trace = go.Table( header=dict(values=['Version', 'Baseline', 'Promo', 'VDP+']), cells=dict(values=[['', '08/20 to 08/27','08/13 to 08/20', '08/06 to 08/13',\ '07/30 to 08/06'], ['Current Month: Aug 18', '', '', '', ''], ['Current Month: Aug 18', '', '', '', ''], ['Current Month: Aug 18', '', '', '', '']])) data = [trace] plotly.offline.plot(data, filename = 'basic_table.html') Looks like: But you can not operate with them such as columns what is not great. Second possible solution is to specify prefix(or suffix - depends what would you like more): import plotly import plotly.graph_objs as go trace = go.Table( header=dict(values=['Version', '.Baseline', '.Promo', '.VDP+'], prefix = ['','Current_Month:_Aug_18', 'Current_Month:_Aug_18',\ 'Current_Month:_Aug_18'], ), cells=dict(values=[['08/20 to 08/27', '08/13 to 08/20', '08/06 to 08/13', \ '07/30 to 08/06'], ['', '', '', ''], ['', '', '', ''], ['', '', '', '']])) data = [trace] plotly.offline.plot(data, filename = 'basic_table.html') And in this case, you can add your columns as prefix or suffix. Looks like: Update: Yep, you can create an empty row (just do not specify headers): Update: Currently I found the way to get what you need: import plotly import plotly.graph_objs as go trace = go.Table( header=dict(values=[['Version', ''], ['Baseline', 'Current Month: Aug 18'], ['Promo', 'Current Month: Aug 18'], ['VDP+', 'Current Month: Aug 18']]), cells=dict(values=[['08/20 to 08/27', '08/13 to 08/20', '08/06 to 08/13', \ '07/30 to 08/06'], ['', '', '', ''], ['', '', '', ''], ['', '', '', '']])) data = [trace] plotly.offline.plot(data, filename = 'basic_table.html') Looks like: I can not hide one line but the whole lines of headers(add line = dict(width=0) after headers values): Or set the color of lines but for all the lines again (with same results as above)

http://stackoverflow.com/comment/91566558
comment on: http://stackoverflow.com/q/52195272
has text: Please refrain from completely rewriting questions in to new questions, because it undermines the existing answers. If you have a new question, ask it as such.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52138657
has body: i am trying to save my sql output to pandas dataframe, using that i have to apply some logic and output save it to table. how can i save the resultset to pandas dataframe. code : import pyodbc cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};" "Server=DESKTOP-XXXXX;" "Database=MOVIE_INFO;" "Trusted_Connection=yes;") cursor = cnxn.cursor() cursor.execute('SELECT * FROM MOVIE_SRC') for row in cursor: print('row = %r' % (row,) Thanks i tried another approach like import pyodbc import pandas as pd cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};" "Server=DESKTOP-XXXX;" "Database=MOVIE;" "Trusted_Connection=yes;") cnxn = cnxn.cursor() crsr = cnxn.cursor() for table_name in crsr.tables(tableType='TABLE'): print(table_name) cursor = cnxn.cursor() sql = "Select *" sql = sql + " From MOVIE" print(sql) cursor.execute(sql) data = pd.read_sql(sql, cnxn) but getting error AttributeError: 'pyodbc.Cursor' object has no attribute 'cursor' Please share your suggestion. Thanks
has title: sql output to pandas dataframe using python in pycharm IDE
linked to: http://stackoverflow.com/q/39835770
has comment: http://stackoverflow.com/comment/91227485
tagged with: pandas
linked to: http://stackoverflow.com/q/12047193
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91227738
favorite count: 0
has comment: http://stackoverflow.com/comment/91227248
tagged with: python
has comment: http://stackoverflow.com/comment/91227419
has comment: http://stackoverflow.com/comment/91227487
has answer: http://stackoverflow.com/a/52139891
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91228982
score: 1
has comment: http://stackoverflow.com/comment/91227709
accepted answer: http://stackoverflow.com/a/52139891
upvote count: 1
type: Question

http://stackoverflow.com/a/52204207
has body: I strongly recommend @mootmoot 's approach with the context manager. This is not only easier to read, but it also catches exceptions when the file cannot be read for some reason. If you don't want to use a context manager, I would suggest you use the try-except commands to for your function. It is unsafe if you do it like @Adam Merki suggested because there will be no guarantee that the file will be closed if an exception occurs while reading the file. Using try-except statements, your function could look like this: import sys def openfile(filename): f = open(filename, mode='r') try: print(f.read()) except: print('something went wrong') else: print('nothing went wrong') finally: f.close() if __name__ == '__main__': openfile(filename=sys.argv[1]) print('script has been executed')
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52200409

http://stackoverflow.com/comment/91273653
has text: @RayZen it may be like zero. One is also like zero in many ways, it is the multiplicative identity, for example, but one is not zero. NaN has properties different from zero as well, although some similar. But again, that is besides the point. It may or may not be similar to zero, but it is *not equal to zero*. Indeed, one unique fact about `nan` is that *it is not equal to anything, not even itself*;
score: 0
comment on: http://stackoverflow.com/q/52159341
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52259398
answers question: http://stackoverflow.com/q/52259270
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52259270
score: 3
type: AcceptedAnswer
upvote count: 3
type: Answer
has body: repeat, join, len order_id = df.order_id.values.repeat(df['items'].str.len()) items = pd.DataFrame(np.concatenate(df['items']).tolist()) items.assign(order_id=order_id) color item order_id 0 blue 1 A 1 red 2 A 2 green 3 B 3 pink 2 B Comprehension pd.DataFrame([{**{'order_id': o}, **i} for o, I in df.values for i in I]) color item order_id 0 blue 1 A 1 red 2 A 2 green 3 B 3 pink 2 B

http://stackoverflow.com/q/52156031
tagged with: python-3.x
has body: I am trying to generate random numbers that are used to generate a part of a world (I am working on world generation for a game). I could create these with something like [random.randint(0, 100) for n in range(1000)] to generate 1000 random numbers from 0 to 100, but I don't know how many numbers in a list I need. What I want is to be able to say something like random.nth_randint(0, 100, 5) which would generate the 5th random number from 0 to 100. (The same number every time as long as you use the same seed) How would I go about doing this? And if there is no way to do this, how else could I get the same behavior?
upvote count: 2
answer count: 5
accepted answer: http://stackoverflow.com/a/52156358
tagged with: python
has comment: http://stackoverflow.com/comment/91262369
type: AnsweredQuestion
downvote count: 3
has answer: http://stackoverflow.com/a/79275636
possible better answer: http://stackoverflow.com/a/52156337
type: Question
has answer: http://stackoverflow.com/a/52156337
has comment: http://stackoverflow.com/comment/91262404
score: -1
has answer: http://stackoverflow.com/a/52156358
linked to: http://stackoverflow.com/q/9023660
tagged with: random
has comment: http://stackoverflow.com/comment/91262708
has answer: http://stackoverflow.com/a/63662672
has comment: http://stackoverflow.com/comment/91262693
has answer: http://stackoverflow.com/a/52156433
has title: Generate the n-th random number with Python
favorite count: 0

http://stackoverflow.com/q/52229909
has answer: http://stackoverflow.com/a/52229939
type: AnsweredQuestion
upvote count: 7
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52229946
has title: Panda Python - Calculating what percentage of values are true and false out of total in boolean column
answer count: 2
tagged with: pandas
has body: Hello I have a boolean value with True and False. When I run a value_counts() like this df['column'].value_counts() I receive the following: True 10718 False 1105 Name: column, dtype: int64 Is there a way to calculate what % of the total is true and what % is false? Something like this: True 91% False 09% Name: column, dtype: int64 Thank you
favorite count: 0
score: 6
possible better answer: http://stackoverflow.com/a/52229939
tagged with: python
has answer: http://stackoverflow.com/a/52229946

http://stackoverflow.com/comment/91455398
has text: thank you very much for your reply! I wanted to find out where in the code you wrote me I should add the print command? In addition, I would be happy to understand, What is the time and space complexity of your function? Would you use this solution if it was a list of thousands of words? Thank you
score: 0
comment on: http://stackoverflow.com/a/52244929
type: Comment
type: AnswerComment

http://stackoverflow.com/a/52174667
answers question: http://stackoverflow.com/q/52174654
score: 0
type: Answer
has body: I think this will work, can you provide a specif example if not? full['DEM'] = full.groupby('state').mean()['demVote']

http://stackoverflow.com/comment/91448501
type: QuestionComment
has text: What does `\n` represent here? Is it a new line or a literal "\n"?
comment on: http://stackoverflow.com/q/52250198
score: 0
type: Comment

http://stackoverflow.com/a/52192037
score: 1
has comment: http://stackoverflow.com/comment/91345009
downvote count: 0
has comment: http://stackoverflow.com/comment/91344613
type: Answer
has comment: http://stackoverflow.com/comment/91344963
upvote count: 1
has body: Exceptions are used to keep the program running even though an error occurred. for file in glob.glob('*.exe'): try: subprocess.Popen(file) except Exception as e: print(file,' did not run properly.') print(e) continue This will alert the user that the '*.exe' did not run properly while keeping your code running.
answers question: http://stackoverflow.com/q/52191797
has comment: http://stackoverflow.com/comment/91343523

http://stackoverflow.com/a/52196273
has body: findContours is the function you are looking for. The code bellow explains how it works. import cv2 import numpy as np import matplotlib.pyplot as plt img = cv2.imread("./outline_rect.png") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) thresh = 255-thresh _, cnts, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) maxArea = 0 best = None for contour in cnts: area = cv2.contourArea(contour) if area &gt; maxArea : maxArea = area best = contour cv2.drawContours(img, [best], 0, (0, 0, 255), 3) while True: cv2.imshow("result", img) k = cv2.waitKey(30) &amp; 0xff if k == 27: break The result:
answers question: http://stackoverflow.com/q/52195622
score: 0
type: Answer

http://stackoverflow.com/q/52266350
downvote count: 0
accepted answer: http://stackoverflow.com/a/52266406
has title: How to convert a list of numbers to a list of letters, Python
tagged with: python
has comment: http://stackoverflow.com/comment/91480668
has body: New to python and I'm trying to code a encrypted message The alphabet has been rewritten as follows: cipher = [ "q", "a", "z", "w", "s", "x", "e", "d", "c", "r", "f", "v", "t", "g", "b", "y", "h", "n", "u", "j", "m", "i", "k", "o", "l", "p"] idx = ord ("d") - ord ("a") print(cipher[3]) OUTPUT: w input = str(input('Write Text: ')) #hello world used here input = input.lower() output = [] for character in input: number = ord(character) - 97 output.append(number) print(output) OUTPUT: [7, 4, 11, 11, 14, -65, 22, 14, 17, 11, 3] Not sure how to correspond these two... I've tried: print(cipher[output]) Returns a TypeError: list indices must be integers or slices, not list Thanks in advance
has answer: http://stackoverflow.com/a/52266406
favorite count: 0
tagged with: python-3.x
upvote count: 1
type: AnsweredQuestion
tagged with: list
score: 1
type: Question
answer count: 1

http://stackoverflow.com/comment/91268847
comment on: http://stackoverflow.com/a/52154352
score: 0
type: Comment
has text: Yeah I had to move the variables outside of the scope and it started working like a charm. :)
type: AnswerComment

http://stackoverflow.com/q/52209617
has title: How to convert dictionary into a specific format
has answer: http://stackoverflow.com/a/52209710
tagged with: string
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/52210269
upvote count: 2
score: 1
has answer: http://stackoverflow.com/a/52209702
has body: I have an output which is of below format: (u'Columns', [{u'Type': u'string', u'Name': u'recon_c+c'}, {u'Type': u'string', u'Name': u'data'}, {u'Type': u'string', u'Name': u'nui'}, {u'Type': u'bigint', u'Name': u'typ'}]) I wanted to convert it to below format: recon_c+c string, data string, nui string, typ bigint How to do this using python? Since I am trying for generic solution which in if I get further more keys:values also then the code can handle. Please let me know if any solution you guys have.
has comment: http://stackoverflow.com/comment/91368615
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52210514

http://stackoverflow.com/q/52259027
has body: I'm working on a Django(2) project in which I need to return a PNG image as HttpResponse when I return this image in the form of a zip archive it returns the image correctly, but when I return the PNG image directly it damaged the image. Here's my code: How it's writing the image: img_resized = cv2.resize(seg_image, dsize) cv2.imwrite(os.path.join(settings.BASE_DIR, 'img/MaskedImage.png'), img_resized) How it's returning the Image: response = HttpResponse(os.path.join(settings.BASE_DIR, 'img/MaskedImage.png'), content_type='image/png') response['Content-Disposition'] = 'attachment; filename=MaskedImage.png' return response It returns an Image with the name MaskedImage.pn but the image is damaged, not able to open. What can be wrong here? Thanks in advance!
type: Question
has answer: http://stackoverflow.com/a/52259058
has comment: http://stackoverflow.com/comment/91465527
score: 0
has title: Return PNG image from Django views is damaged
accepted answer: http://stackoverflow.com/a/52259058
answer count: 1
has comment: http://stackoverflow.com/comment/91465551
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: django-views

http://stackoverflow.com/a/52141552
has body: Evaluating the css using developer tools in chrome yields 4 elements. Click here for the image use the following css instead: go_ = driver.find_element_by_css_selector('#cdr_frm &gt; input.ksb.mini.cdr_go')
type: Answer
accepted answer of: http://stackoverflow.com/q/52141210
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/91233011
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91233096
answers question: http://stackoverflow.com/q/52141210

http://stackoverflow.com/a/52136757
has comment: http://stackoverflow.com/comment/96120298
has comment: http://stackoverflow.com/comment/91224825
has body: From np.transpose docs A view is returned whenever possible. meaning no extra memory is allocated for the output array. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; A = np.random.rand(2, 3, 4, 5) &gt;&gt;&gt; B = np.transpose(A, axes=(0, 3, 1, 2)) &gt;&gt;&gt; A.shape (2, 3, 4, 5) &gt;&gt;&gt; B.shape (2, 5, 3, 4) You can use np.shares_memory to check if B is a view of A: &gt;&gt;&gt; np.shares_memory(A, B) True So, you can safely transpose your data withnp.transpose.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52136678
answers question: http://stackoverflow.com/q/52136678
downvote count: 0
has comment: http://stackoverflow.com/comment/95573744
has comment: http://stackoverflow.com/comment/96120802
score: 8
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/91224850
has comment: http://stackoverflow.com/comment/91223161
has comment: http://stackoverflow.com/comment/95546098
has comment: http://stackoverflow.com/comment/95594150

http://stackoverflow.com/comment/91382222
comment on: http://stackoverflow.com/q/52216766
has text: Do you have an assert somewhere in your code? Can you post some part of it?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52148913
has comment: http://stackoverflow.com/comment/91252821
has body: The general answer is "wrap the field in a property (or other descriptor), ie: class MyModel(models.Model): _lazy = models.WhateverField( db_column="lazy", blank=True, null=True, default=None ) @property def lazy(self): if self._lazy is None: self._lazy = get_the_value_from_api_call(...) self.save(update_fields=["_lazy"]) return self._lazy # if you want to be able to set the property - else # ignore this part and `MyModel.lazy` will become # read-only @lazy.setter def lazy(self, value): self._lazy = value BUT I would definitly NOT allow this in my team - I do not expect a getter to do an HTTP request and update the database - and I strongly suggest you find a better (robust, reliable and predictable) way to solve the real problem which is, mainly, handling the API quota.
has comment: http://stackoverflow.com/comment/91249835
downvote count: 0
score: 1
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52147751

http://stackoverflow.com/comment/91329630
has text: thanks, Stephen & Juanpa!
type: Comment
comment on: http://stackoverflow.com/q/52177570
score: 0
type: QuestionComment

http://stackoverflow.com/q/52177621
has title: Read only models and displayed as a list in django admin?
upvote count: 3
accepted answer: http://stackoverflow.com/a/52206398
has answer: http://stackoverflow.com/a/62127015
tagged with: python
has comment: http://stackoverflow.com/comment/91306349
downvote count: 0
has answer: http://stackoverflow.com/a/52206398
has comment: http://stackoverflow.com/comment/91305633
linked to: http://stackoverflow.com/q/8265328
tagged with: django
has comment: http://stackoverflow.com/comment/91305398
type: Question
type: AnsweredQuestion
score: 3
tagged with: django-admin
answer count: 2
possible better answer: http://stackoverflow.com/a/62127015
has body: I want to display a model from db onto my django admin. What I want do with it is just simply display the details, no editing. is there a way to somehow "disable" the CRUD functions of a model in the django admin ? I can't seem to find a way. my current django version is 2.1.1. thanks for the help!
favorite count: 0

http://stackoverflow.com/q/52264963
tagged with: python
has answer: http://stackoverflow.com/a/52265009
accepted answer: http://stackoverflow.com/a/52265009
tagged with: telnet
upvote count: 3
type: AnsweredQuestion
score: 3
has title: Open interactive telnet session from Python
type: Question
has body: I am currently writing a small script in Python which reads some possible connections from a database (triple of node name, telnet IP address and telnet port) and present that to the user to choose to which node to connect. After this selection I want to open an interactive Telnet session, which can be used by the user as if he had manually connected using the telnet command. Somehow I probably will need an escape sequence for that. It only needs to work on Linux OS. I could just call telnet: # Open shell call(["telnet", selected_node['ip'], selected_node['port']]) That does work. However, I wonder if there might be a better solution.
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/68917022
score: 0
type: Answer
has body: you can use django-zero-settings, which may help you in some cases. checkout this answer https://stackoverflow.com/a/68916822/6484831
answers question: http://stackoverflow.com/q/52172366

http://stackoverflow.com/comment/91412438
type: Comment
type: QuestionComment
has text: Yeah, I accidentally tried to open the 'geckodriver' with notepad, and now the icon seems to be set to notepad permanently. It must have some kind of extension; it' can't just be 'geckodriver' with no extension. For instance, Google Chrome uses 'chromedriver.exe'. That makes sense, and it works fine when I try to use Google Chrome. I don't see how 'geckodriver' is going to do anything without some kind of conversion...I would think...
comment on: http://stackoverflow.com/q/52229912
score: 0

http://stackoverflow.com/a/52167912
score: 5
has body: Problem is there is sometimes double ", solution is change separator for match zero or more " before and after ,: df = pd.read_csv('ING_DAILY - ING_DAILY.csv', sep='["]*,["]*', engine='python') Then is necessary remove " from columns names and from first and last columns: df.columns = df.columns.str.strip('"') df.iloc[:, [0,-1]] = df.iloc[:, [0,-1]].apply(lambda x: x.str.strip('"')) print (df.head(3)) ISIN MIC Datum Open Hoog \ 0 NL0011821202 Euronext Amsterdam Brussels 04/09/2017 14.82 14.950 1 NL0011821202 Euronext Amsterdam Brussels 05/09/2017 14.91 14.920 2 NL0011821202 Euronext Amsterdam Brussels 06/09/2017 14.69 14.725 Laag Close Number of Shares Number of Trades Turnover Valuta 0 14.785 14.855 7482805 6970 1.113455e+08 EUR 1 14.585 14.655 15240971 12549 2.242653e+08 EUR 2 14.570 14.615 14851426 15303 2.175316e+08 EUR
upvote count: 5
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52166302
accepted answer of: http://stackoverflow.com/q/52166302
type: Answer
has comment: http://stackoverflow.com/comment/101641313

http://stackoverflow.com/comment/91206841
has text: The data in the link you posted does not seem to match the data in your image. Can you please post a link to the data in the image?
score: 0
comment on: http://stackoverflow.com/q/52114682
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91927252
has text: @ jezrael Column **F** is **Place** column. Now has not problem. I do not know why the error is not raise but at past problem alert about variable to be aggregate doesn't create. I decided to solve the problem at that time to select last of **Place** column --->> 'Place' : 'last' then the problem was gone.
comment on: http://stackoverflow.com/a/52253863
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91515485
has text: Also, what goes wrong when you try to run your `pivot_table` command?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52267321

http://stackoverflow.com/comment/91363625
has text: Rather than using python, did you try `wc -w v_i_m_utf8.txt`? It is a mature purpose-written program, probably in C.
score: 4
comment on: http://stackoverflow.com/q/52207136
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91381784
type: QuestionComment
has text: Why do you need a bitwise operator?
comment on: http://stackoverflow.com/q/52216489
score: 0
type: Comment

http://stackoverflow.com/a/52267305
has body: IIUC: new = old.copy() new'col1','col3' = -1 &gt;&gt;&gt; new col1 col2 col3 0 -1 2 -1 1 -1 3 -1 2 -1 4 -1 Or more generally, to change all columns besides col2 to -1: new = old.copy() new[list(set(new.columns) - {'col2'})] = -1
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52267256
downvote count: 0

http://stackoverflow.com/comment/91232756
comment on: http://stackoverflow.com/q/52141369
type: QuestionComment
has text: Why are you trying to start 2 chrome drivers here? Its possible the second chrome driver instance is crashing the first one and that is why you are getting this error.
score: 0
type: Comment

http://stackoverflow.com/a/58217078
downvote count: 0
upvote count: 2
type: Answer
score: 2
has body: The numberParser coroutine isn't yielding itself for routine Modify # code to send the input number to both the linear equations equation1.send(6.0) equation2.send(6.0) to # code to send the input number to both the linear equations while True : x = yield equation1.send(x) equation2.send(x)
answers question: http://stackoverflow.com/q/52116817

http://stackoverflow.com/a/52120544
has comment: http://stackoverflow.com/comment/91212382
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52120227
type: Answer
accepted answer of: http://stackoverflow.com/q/52120227
has body: Hope this helps.Import subprocess and sys. And then try something like this "command = subprocess.Popen(["powershell.exe","user_command.ps1"],stdout=sys.stdout) command.communicate()" Try putting your code into the .ps1 file
score: 0

http://stackoverflow.com/comment/91430485
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52240668
has text: So, it's like if I'm changing the upper bound on range, my answer varies. Any idea how can I replace the upper bound by exact number of words in the text?
score: 0

http://stackoverflow.com/q/52230792
tagged with: pandas
has comment: http://stackoverflow.com/comment/91411229
tagged with: findall
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52230866
tagged with: python
tagged with: regex
score: 2
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/52230866
type: Question
has body: Is there a more computationally efficient way in Pandas to get to the final output below? I only want the first occurrence, and it seems computationally inefficient to findall and then get the 0th element of the list, as below: Input: s= pd.Series(["David Matt Juan Peter David James", "Scott David Peter Sam David Ron", "Dan Phil David Sam Pedro David Mani"]) s_find= s.str.findall(r'David [A-za-z]*') print(s_find) Output: 0 [David Matt, David James] 1 [David Peter, David Ron] 2 [David Sam, David Mani] Input: s_find= s_find.str[0] print(s_find) Output: 0 David Matt 1 David Peter 2 David Sam
has title: Is there a more computationally efficient way to find the first occurrence matching a regular expression using Pandas?

numpy-ndarray
tags question: http://stackoverflow.com/q/52124584
tags question: http://stackoverflow.com/q/52212220
tags question: http://stackoverflow.com/q/52135891
tags question: http://stackoverflow.com/q/52134482
tags question: http://stackoverflow.com/q/52117418
tags question: http://stackoverflow.com/q/52126542
tag name: numpy-ndarray
tags question: http://stackoverflow.com/q/52232502
type: Tag
tags question: http://stackoverflow.com/q/52261119

http://stackoverflow.com/comment/91465673
score: 1
has text: @PranshTiwari Then you have no choice but to use South. You can't use Django migrations. This pretty much renders your question moot.
comment on: http://stackoverflow.com/q/52258913
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91188656
score: 0
type: Comment
type: QuestionComment
has text: I also changed the "return new_h, new_state" line in BasicLSTMCell to return new_h, new_state, i, j, f, o and in the example script changed the line number 128 to:
comment on: http://stackoverflow.com/q/52117900

http://stackoverflow.com/a/52120122
has comment: http://stackoverflow.com/comment/91191485
score: 2
downvote count: 0
has body: You could also use: Using a sub string: d= { "layers": {}, "definitionExpression": "(UPPER(Auto_Trash_Route) = UPPER('FRI-AA-02'))" } d['definitionExpression'][34:-3] #returns 'FRI-AA-02' using regular expressions: import re re.findall(r"(?&lt;=')[^']+(?=')",d['definitionExpression']) using split: d['definitionExpression'].split("'")[1] using regex with the format: re.findall(r"\w{3}-\w{2}-\d{2}",d['definitionExpression'])
has comment: http://stackoverflow.com/comment/91191945
has comment: http://stackoverflow.com/comment/91191425
has comment: http://stackoverflow.com/comment/91191639
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52119879
has comment: http://stackoverflow.com/comment/91191793
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91191700
answers question: http://stackoverflow.com/q/52119879
has comment: http://stackoverflow.com/comment/91191906
has comment: http://stackoverflow.com/comment/91191747
has comment: http://stackoverflow.com/comment/91191837
type: Answer

pandas-to-sql
tags question: http://stackoverflow.com/q/52188446
type: Tag
tag name: pandas-to-sql

http://stackoverflow.com/comment/91427879
has text: I have checked the GPU memory it does not change much. Only like about 2%.
type: QuestionComment
comment on: http://stackoverflow.com/q/52239489
score: 0
type: Comment

http://stackoverflow.com/a/52148166
answers question: http://stackoverflow.com/q/52148029
has comment: http://stackoverflow.com/comment/91246934
has comment: http://stackoverflow.com/comment/91247313
type: Answer
has comment: http://stackoverflow.com/comment/91249130
upvote count: 1
has body: the flow_from_dictionary says that 'it should contain one subdirectory per class' this is because the name of the subdirectory will be the label of the class, so if you were to have pictures of dogs and cats in the appropriate labelled directories, the labels would be dogs and cats, this is most probably the thing you are looking for, i remember using the function like this, i cannot say anything if its changed
has comment: http://stackoverflow.com/comment/91246531
score: 1
accepted answer of: http://stackoverflow.com/q/52148029
has comment: http://stackoverflow.com/comment/105363272
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52221136
type: Answer
answers question: http://stackoverflow.com/q/52220734
accepted answer of: http://stackoverflow.com/q/52220734
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: df['left_match'] = df.apply(lambda x:True if re.search(str(x['amount']).split('.')[0],x['inv_id']).start() ==0 else False,axis=1) df output: amount inv_id left_match 0 309.90 30990071218 True 1 3130.00 313000B20180501 True 2 17.35 13249261 100117 False

http://stackoverflow.com/comment/91367089
type: AnswerComment
type: Comment
has text: I personally do not use OpenCV, so i could only gather the respective methods for each step.
comment on: http://stackoverflow.com/a/52167973
score: 0

http://stackoverflow.com/q/52201848
downvote count: 0
has comment: http://stackoverflow.com/comment/91352735
linked to: http://stackoverflow.com/q/394809
favorite count: 0
tagged with: python-internals
tagged with: ternary-operator
tagged with: python
upvote count: 11
has answer: http://stackoverflow.com/a/52201982
type: AnsweredQuestion
tagged with: python-3.x
has title: How is ternary operator implemented in Python
tagged with: cpython
linked to: http://stackoverflow.com/q/3091316
has answer: http://stackoverflow.com/a/52202089
has body: I understand that conditional expressions (or ternary operators) are lazy in Python. They represent conditional execution rather than conditional selection. In other words, only one of a or b is evaluated in the following: c = a if condition else b What I'm interested to know is how this is implemented internally. Does Python convert to an if statement as below and, if so, at what stage does this conversion occur? if condition: c = a else: c = b Or is the ternary operator actually a distinct and separate expression, defined entirely separately? If so, can I access the CPython code for conditional expressions? I've looked at the following which explain what the ternary operator does, but none of them make clear how they are implemented: Does Python have a ternary conditional operator? Putting a simple if-then-else statement on one line python ? (conditional/ternary) operator for assignments Is there an equivalent of C’s ”?:” ternary operator? Conditional expressions Edit: You can assume CPython reference implementation.
type: Question
possible better answer: http://stackoverflow.com/a/52202007
accepted answer: http://stackoverflow.com/a/52201982
has answer: http://stackoverflow.com/a/52202007
score: 11
has comment: http://stackoverflow.com/comment/91352881
answer count: 3
linked to: http://stackoverflow.com/q/2802726

http://stackoverflow.com/q/52249755
score: -4
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/91447732
downvote count: 4
upvote count: 0
tagged with: spyder
answer count: 1
has comment: http://stackoverflow.com/comment/91447666
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91448032
has comment: http://stackoverflow.com/comment/91447767
tagged with: python
has answer: http://stackoverflow.com/a/52249813
has comment: http://stackoverflow.com/comment/91447726
type: AnsweredQuestion
has body: Solved: Thanks for your helps. i'm working dictionary and hash codes in one page, and there was a block problem. i thought, my logic is wrong but i checked all page, and i fixed blocks. its works fine right now. Here's my problem: d = {} d['a'] = 'alpha' d['b'] = 'beta' missing_key = 'x' in d if missing_key == True: print ("The key, you are looking for was successfully found!") else: print ("The key, you are looking for was not found!") print ("Here are keys in database:") for k, r in enumerate(d.keys(), start=1) print ("Key {}: {}".format(k, r)) that for condition works perfectly. but i cant run that if condition. Where am i doing wrong ? Thanks for your help. Getting this error: File "C:/Python/dictionary-hash.py", line 33 if missing_key == True: IndentationError: unexpected indent also i'm using "Python 3.6" and "Anaconda Spyder"
accepted answer: http://stackoverflow.com/a/52249813
has comment: http://stackoverflow.com/comment/91447925
has comment: http://stackoverflow.com/comment/91447659
type: Question
has title: Python: if condition for an another function result?
tagged with: if-statement
has comment: http://stackoverflow.com/comment/91447670

http://stackoverflow.com/q/52238137
has title: Can't find elements on modal windows (ui-draggable dialog)
has body: I'm using selenium to click on images and copy their keywords. However, when I choose an image, a modal windows appears (as shown in the image) I'm trying to get the text using driver.find_element_by_xpath, but none of the elements on the modal dialog are available. Selenium can't find any of them. Although, the elements on the back of the page (behind the modal dialog) are fine. The problem is that the elements on the modal dialog are not there. Any help is appreciated!
has comment: http://stackoverflow.com/comment/91426816
type: Question
linked to: http://stackoverflow.com/q/7534622
has comment: http://stackoverflow.com/comment/91428153
score: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91428163
tagged with: selenium
tagged with: python
has comment: http://stackoverflow.com/comment/91424902

http://stackoverflow.com/q/52113360
tagged with: pandas
has comment: http://stackoverflow.com/comment/91177195
has comment: http://stackoverflow.com/comment/91178060
answer count: 1
has title: Check any element of an array inside a list
has comment: http://stackoverflow.com/comment/91178291
has comment: http://stackoverflow.com/comment/91177573
has comment: http://stackoverflow.com/comment/91177957
has comment: http://stackoverflow.com/comment/91178055
tagged with: python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52114014
has comment: http://stackoverflow.com/comment/91178145
has comment: http://stackoverflow.com/comment/91177776
has body: Assume I got an array, created by a pandas dataframe with array = df.index.values and looks like following: array array(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], dtype=object) and I got a python list looks like following: list = ['AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'A'] Looking for a function, which does following: If any element of array is also in list, give me True. If not give me False. PS: I am not looking for finding the element. Just want to know if such element exist.
type: Question
has comment: http://stackoverflow.com/comment/91177845
has comment: http://stackoverflow.com/comment/91178030
tagged with: arrays
has comment: http://stackoverflow.com/comment/91177890
has comment: http://stackoverflow.com/comment/91177552
tagged with: any
accepted answer: http://stackoverflow.com/a/52114014
linked to: http://stackoverflow.com/q/740287
score: 0

http://stackoverflow.com/comment/91417470
type: Comment
type: QuestionComment
has text: 1979, this port probably is already opened in your server, and it couldn't bind your socket into it. check with `netstat -ntlp` if this port is already there.
score: 0
comment on: http://stackoverflow.com/q/52234324

music21
type: Tag
tags question: http://stackoverflow.com/q/52196356
tag name: music21

http://stackoverflow.com/comment/91184862
score: 0
comment on: http://stackoverflow.com/q/52116952
has text: @E.Serra, the OP *is already* using `communicate()` to read from both pipes -- indeed, that's in the title itself. `communicate()` *requires* `stdout=PIPE` and `stderr=PIPE` to capture that content.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52235134
score: 1
answers question: http://stackoverflow.com/q/52234917
accepted answer of: http://stackoverflow.com/q/52234917
has comment: http://stackoverflow.com/comment/91419940
upvote count: 1
type: AcceptedAnswer
has body: w, h = window.winfo_screenwidth(), window.winfo_screenheight() w, and h are now holding the value of the screen height and width, say 1280, and 920 window.geometry("%dx%d+0+0" % (w, h)) Then it is a straightforward python string formatting (the old fashion way): window.geometry("1280x920+0+0") which is a string that tkinter can parse. (welcome to the 1990'es)
type: Answer
has comment: http://stackoverflow.com/comment/91419854
downvote count: 0

http://stackoverflow.com/comment/91185152
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52116978
has text: I guess you could use the `s` format specifier (which generates a single value) and re-unpack that value as integers/shorts/whatever. But I don't know if that qualifies as a "better" way though

http://stackoverflow.com/comment/91208773
type: Comment
comment on: http://stackoverflow.com/a/52129178
has text: I'm sorry but, which default you means? Thanks
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91184838
has text: Can you use `strace` to determine the specific syscall that's blocking? (or `sysdig` to trace both the Python interpreter and its child at the same time with much less overhead).
score: 0
comment on: http://stackoverflow.com/q/52116952
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52237781
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52235098
answers question: http://stackoverflow.com/q/52235098
type: Answer
score: 2
downvote count: 0
has body: Although I have have no idea what a "creepy http response" is, the proper syntax for a Solr query is to use the q argument: http://localhost:8983/solr/&lt;collectionname&gt;/select?q=id:abc123

http://stackoverflow.com/q/52140641
score: 2
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/52140735
favorite count: 0
tagged with: python-internals
type: Question
upvote count: 2
tagged with: python
answer count: 1
tagged with: python-descriptors
has title: function descriptor on builtin types like dict.fromkeys behaves different to a normal method
has answer: http://stackoverflow.com/a/52140735
has body: Why does the function descriptor for dict.fromkeys function differently then other normal functions. First of all you can't access __get__ like this: dict.fromkeys.__get__ you have to get it from the __dict__. (dict.__dict__['fromkeys'].__get__) And then it doesn't work like any other function because it will only let itself get bound to a dict. This works fine what I expected: class Thing: def __init__(self): self.v = 5 def test(self): print self.v class OtherThing: def __init__(self): self.v = 6 print Thing.test Thing.test.__get__(OtherThing()) this however does something unexpected: #unbound method fromkeys func = dict.__dict__["fromkeys"] but it's description differs from a normal unbound function to looks like: &lt;method 'fromkeys' of 'dict' objects&gt; instead of: &lt;unbound method dict.fromkeys&gt; which was what I this works as expected: func.__get__({})([1,2,3]) but you can't bind it to something else I understand It wouldn't work but that doesn't usually stop us: func.__get__([])([1,2,3]) This fails with a type error from the function descriptor...: descriptor 'fromkeys' for type 'dict' doesn't apply to type 'list' Why does python differentiate builtin type functions and normal functions like this? And can we do this too? Can we make a function that will only be bound to the type it belongs to?
tagged with: python-2.7

http://stackoverflow.com/comment/91332482
type: QuestionComment
has text: You can try this `ids = resultSet.find_element_by_tag_name('id')`
comment on: http://stackoverflow.com/q/52191290
score: 0
type: Comment

http://stackoverflow.com/q/52148959
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91247590
has body: I have an enormous set of data about people store in a nested dictionary. The outer dictionary has the key is the name of a person and the value is another dictionary contains all information about that person (features, such as email, phone, number, salary, ...). The inner dict keys are the features names (so 'email' and so on), and the value is the value of the feature (so 'abcde@gmail.com'). I know that all people have the same number of features. How can I count how many features there are? When I do this, I only get the number of people: print(len(enron_data))
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52149013
has title: How to count the keys in one of a large number of nested dictionaries
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/15479928
tagged with: dictionary
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/52149013

http://stackoverflow.com/a/52509250
has comment: http://stackoverflow.com/comment/91960577
has comment: http://stackoverflow.com/comment/92042770
type: Answer
has comment: http://stackoverflow.com/comment/91999887
has body: Most likely your LSTM is learning to guess roughly what its previous input value was (modulated a bit). That's why you see a "shift". So let's say your data looks like: x = [1, 1, 1, 4, 5, 4, 1, 1] And your LSTM learned to just output the previous input for the current timestep. Then your output would look like: y = [?, 1, 1, 1, 4, 5, 4, 1] Because your network has some complicated machinery it is not quite this straightforward but in principle the "shift" you see is caused by this phenomenon.
downvote count: 1
score: 3
has comment: http://stackoverflow.com/comment/92019983
has comment: http://stackoverflow.com/comment/91959777
has comment: http://stackoverflow.com/comment/93145480
upvote count: 4
has comment: http://stackoverflow.com/comment/92000825
has comment: http://stackoverflow.com/comment/92054074
answers question: http://stackoverflow.com/q/52252442

http://stackoverflow.com/comment/91487450
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52265811
has text: Thank you for your answer. The problem is, that my whole code is in python. I am not using any kv file for the `playground.py`.
type: AnswerComment

http://stackoverflow.com/a/52128860
has comment: http://stackoverflow.com/comment/91210314
has comment: http://stackoverflow.com/comment/91211751
type: Answer
has body: Since there is already an input layer in VGG16 you don't need to define a new Input layer in this case. Just use the existing one: decode_features = decode_model.output # ... final_model = models.Model(inputs=[decode_model.input], outputs=[conv_6]) Update: If you want to prevent the weights of VGG16 to be modified, explicily freeze all of its layers using trainable parameter: for layer in decode_model.layers: layer.trainable = False Just make sure you do this before compiling the final model.
answers question: http://stackoverflow.com/q/52119988
has comment: http://stackoverflow.com/comment/91210150
score: 0
has comment: http://stackoverflow.com/comment/91210370

http://stackoverflow.com/q/52145755
linked to: http://stackoverflow.com/q/47006652
upvote count: 1
has answer: http://stackoverflow.com/a/52146035
type: Question
has answer: http://stackoverflow.com/a/52146025
tagged with: numpy
answer count: 3
downvote count: 0
score: 1
has body: I have a dataset of images for Key point detection. Each Image got labeled with one keypoint (x|y). I use numpy to flip images for data augmentation. I flip an Image horizontal with this code: img = img[:, ::-1] And vertical with this code img = img[::-1] So far so good. But I have to also recalculate the keypoints (labels) ( [85 35]) I know its basic math but i havent campe up with a solution. Thanks in Advance.
favorite count: 0
has title: Calculate new Position of coordinates with numpy
has answer: http://stackoverflow.com/a/52145985
type: UnansweredQuestion
tagged with: python
tagged with: data-augmentation

http://stackoverflow.com/comment/91220695
has text: You will need python interpreter to run python code. You will not be able to launch python from chrome extensions. If you launch python from outside chrome extension can talk to external process.
score: 0
comment on: http://stackoverflow.com/q/52129856
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91317174
has text: The vertical positions seem pretty arbitrarily defined. It should actually simply be `i` itself. `plt.text(v+0.2, i, str(round(v, 2)), color='steelblue', va="center")`
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52183192
type: AnswerComment

http://stackoverflow.com/q/52119336
has title: How to input dataset to the Swarm algorithms in SwarmPackage of Python and how to extract the optimized feature list to give input to the classifiers?
has comment: http://stackoverflow.com/comment/91189887
tagged with: optimization
score: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91190558
tagged with: machine-learning
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91190282
has comment: http://stackoverflow.com/comment/91189709
has body: The description of the SwarmPackagePy library on Github writes: Every algorithm has arguments listed below: n: number of agents function: test function lb: lower limits for plot axes ub: upper limits for plot axes dimension: space dimension iteration: number of iterations Every algorithm has methods listed below: get_agents(): returns a history of all agents of the algorithm get_Gbest(): returns the best position of algorithm Where do we give our dataset as input and how do we extract the optimized feature subset to give input to the classifiers?

http://stackoverflow.com/q/52152943
tagged with: oracle-database
tagged with: python
has comment: http://stackoverflow.com/comment/91297452
has title: Python and Oracle DB - "Error DPI-1050: Oracle Client library must be at version 11.2 or higher"
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91263908
upvote count: 3
has answer: http://stackoverflow.com/a/52156681
has comment: http://stackoverflow.com/comment/91302060
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/57126313
linked to: http://stackoverflow.com/q/49450646
has answer: http://stackoverflow.com/a/57126313
tagged with: database
has comment: http://stackoverflow.com/comment/91295973
has comment: http://stackoverflow.com/comment/91263795
answer count: 2
accepted answer: http://stackoverflow.com/a/52156681
tagged with: cx-oracle
favorite count: 0
has body: Some days ago, I was asked to develop a Python application capable of connecting to a Oracle DB. Since I already have an Oracle client installed (version 12.2.0), I just pip installed cx_Oracle and tried to establish a connection using below code: import pandas as pd import cx_Oracle connection = cx_Oracle.connect('username/password@service_as_described_in_tnsnames.ora') cur=connection.cursor() input("Press Enter to continue...") cur.execute('select* from MY_PRETTY_TABLE') for line in cur: print() cur.close() connection.close() But when trying to run it, I got the error "DPI-1050: Oracle Client library must be at version 11.2 or higher". After googling it, I found this answer, and tried to change my code to: my_dsn = cx_Oracle.makedsn("host",port,sid="sid") connection = cx_Oracle.connect(user="user", password="password", dsn=my_dsn) cursor = connection.cursor() querystring = "SQL query" cursor.execute(querystring) But still, same error. It's important to notice that I have already used Oracle DB client in this same machine, to connect a DB with Power BI. Also, if it can be helpful, my paths are setted as: C:\instantclient_12_1 C:\Users\oracle2\product\12.1.0\client_1 C:\Users\oracle2\product\12.1.0\client_1\bin C:\Users\oracle\product\12.2.0\dbhome_1\bin

http://stackoverflow.com/q/52134512
has comment: http://stackoverflow.com/comment/91219206
favorite count: 0
has comment: http://stackoverflow.com/comment/91219158
has comment: http://stackoverflow.com/comment/91219110
score: 6
tagged with: python
has answer: http://stackoverflow.com/a/52134628
has body: Since Python is implemented in C, I am confused how the developers managed to make the Python builtin len function run on any sequence in constant time, O(1), while C's string function strlen runs in linear time, O(n). What is the secret behind Python's builtin len functions's time complexity? If we were to write program in C, would it be best practice to copy Python's code for len if we ever wanted to a fast C program involves sequence length?
has comment: http://stackoverflow.com/comment/91219311
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91219201
linked to: http://stackoverflow.com/q/1115313
has comment: http://stackoverflow.com/comment/91330492
has title: What is the secret behind Python's len() builtin time complexity of O(1)
upvote count: 7
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52134628
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/91219086
has answer: http://stackoverflow.com/a/52134543
has comment: http://stackoverflow.com/comment/91221285
answer count: 2
tagged with: time-complexity
possible better answer: http://stackoverflow.com/a/52134543

http://stackoverflow.com/comment/91256220
comment on: http://stackoverflow.com/q/52152512
has text: please update sample input with some dummy values which can give better idea... and also volume_dict2['num_comments'][count].append(volume_dict['num_comments']) what do u mean by `[count]` ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91184787
comment on: http://stackoverflow.com/q/52116500
score: 0
has text: That said I think this is what you are looking for: http://python-future.org/translation.html (If I am not mistaken)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91245417
has text: Possible duplicate of [Python: Expected an indented block](https://stackoverflow.com/questions/21764912/python-expected-an-indented-block)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52140256
score: 1

http://stackoverflow.com/comment/91216970
score: 1
comment on: http://stackoverflow.com/q/52133259
has text: In the first one you never return a value. In the second one you return immediately.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91433820
comment on: http://stackoverflow.com/q/52169226
has text: @rocksportrocker that thread solves a problem that I don't have: dubugging python. What I need is readline support.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91362029
score: 3
has text: Are you referring to a file that is in a local github that you want to change, commit and push?
comment on: http://stackoverflow.com/q/52206432
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91260499
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52154963
has text: But how to get from the text representation to the actual emotion? Is there something like a dictionary?
type: Comment

http://stackoverflow.com/a/52225481
score: 0
has comment: http://stackoverflow.com/comment/91400408
type: Answer
has body: How about using a Flask server that handles the communication between the 2 programs. You could define custom endpoints that would be able to grab the data as well as send it to the discord script. @app.route('/ep1', methods = ['GET','POST']) def ep1(): if request.method == 'POST': #do something for a POST request. else: #do something for a GET request. You can use this structure to construct something that listens for changes and then publishes those to the discord bot. Also hosting this server on heroku is something that you might want to consider
answers question: http://stackoverflow.com/q/52225311

http://stackoverflow.com/comment/91212476
score: 2
comment on: http://stackoverflow.com/q/52130982
type: Comment
type: QuestionComment
has text: For one, you should never create more than one instance of `Tk`. If you need more than one window, create instances of `Toplevel`.

http://stackoverflow.com/a/52241036
answers question: http://stackoverflow.com/q/52235013
type: Answer
has body: If you are getting 'permission denied' error using: pip install pandas try typing this in a terminal: pip install pandas --user This will install the library to the 'Python user install directory for your platform' which should not require admin rights to read or write to. For more details type: pip install --help
score: 0

http://stackoverflow.com/a/52311082
accepted answer of: http://stackoverflow.com/q/52261814
answers question: http://stackoverflow.com/q/52261814
has body: Update - I found the solution problem was with sqllite3 database. I moved to postgresql Everything works fine now!
upvote count: 1
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/52196342
tags question: http://stackoverflow.com/q/52135293
tags question: http://stackoverflow.com/q/52211886
tags question: http://stackoverflow.com/q/52198449
tags question: http://stackoverflow.com/q/52225467
tag name: google-oauth
tags question: http://stackoverflow.com/q/52167804

http://stackoverflow.com/a/52210063
answers question: http://stackoverflow.com/q/52144108
downvote count: 0
type: Answer
upvote count: 1
score: 1
has body: Building off of @judoole's answer, you could extend GoogleCloudStorageToBigQueryOperator directly. class MyGoogleCloudStorageToBigQueryOperator(LoggingMixin, GoogleCloudStorageToBigQueryOperator): def execute(self, context): self.logger.info('Inside task {task_id}'.format(task_id=context['task_id'])) super().execute(context) More generally, you could write a mixin class that would automatically do this type of logging for a variety of operators. class LogTaskExecutionMixin(object): def execute(self, context): self.logger.info('Inside task {task_id}'.format(task_id=context['task_id'])) super().execute(context) class MyGoogleCloudStorageToBigQueryOperator( LogTaskExecutionMixin, LoggingMixin, GoogleCloudStorageToBigQueryOperator ): pass The thinking in both of these approaches is that you define a new operator that writes a log message before execution but is otherwise identical to the operator that you have extended.

http://stackoverflow.com/comment/91429201
score: 1
has text: MDS is not a clustering algorithm, and I didn't get how you are trying to use it. The example in the link you posted works because it has a **target** variable (a label, `y`), your code doesn't have one.
type: QuestionComment
comment on: http://stackoverflow.com/q/52188561
type: Comment

http://stackoverflow.com/comment/91207468
has text: you just want to print last names right ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52128407

http://stackoverflow.com/q/52215002
possible better answer: http://stackoverflow.com/a/52222711
score: 1
has answer: http://stackoverflow.com/a/52222711
answer count: 3
tagged with: python-3.5
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52218720
has body: I have tried and researched a lot of times but still could not find it. I want to make a command that deletes a selected role in the server. Here is what I came up with (Don't currently care about permissions): @bot.command(pass_context=True) async def delrole(ctx, role: discord.Role): await bot.delete_role(role) await bot.say("The role {} has been deleted!".format(role.name)) If you could help that would be awesome. I used role: discord.Role and delete_role(). Thank you for reading. If you have a solution, feel free to comment it. NOTICE: This post was for the old version of discord.py and will no longer work. If you are looking for an equivalent solution for the rewrite (v1) version of discord.py, you can use the following code: @bot.command(pass_context=True) async def delrole(ctx, *, role_name): role = discord.utils.get(ctx.message.guild.roles, name=role_name) if role: try: await role.delete() await ctx.send("The role {} has been deleted!".format(role.name)) except discord.Forbidden: await ctx.send("Missing Permissions to delete this role!") else: await ctx.send("The role doesn't exist!")
tagged with: python
has answer: http://stackoverflow.com/a/68962245
has title: Discord.py, how do I delete a role?
upvote count: 1
accepted answer: http://stackoverflow.com/a/52218720
type: Question
type: AnsweredQuestion
tagged with: discord.py

http://stackoverflow.com/q/52217512
upvote count: 0
tagged with: shell
has answer: http://stackoverflow.com/a/52217608
favorite count: 0
tagged with: linux
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91395653
tagged with: python
has title: Script that can automatically download new data from the server to my local backup
downvote count: 2
has answer: http://stackoverflow.com/a/52217936
type: Question
score: -2
has body: I have an application running on linux server and I need to create a local backup of it's data. However, new data is being added to the application after every hour and I want to sync my local backup data with server's data. I want to write a script (shell or python) that can automatically download new added data from the linux server to my local machine backup. But I am newbie to the linux envoirnment and don't know how to write shell script to achieve this. What is the better way of achieving this ? And what would be the script to do so ?
answer count: 2
tagged with: backup

http://stackoverflow.com/q/52218089
downvote count: 1
type: Question
has body: How can I avoid that AWS Glue writes empty objects to S3? I have a Glue Job that writes the resulting dynamic frame to S3: dynamic_frame = # result of Glue job processing glue_context.write_dynamic_frame.from_options( frame = dynamic_frame, connection_type = 's3', connection_options = {'path': 's3://some-bucket/some-path'}, format = 'json') However, when I check the bucket content in S3, I see not just the data but also many objects that has size 0 B. How can I prevent this? I have tried using the DropNullFields class (see below), but that did not help. dynamic_frame = # result of Glue job processing non_null_fields = DropNullFields.apply(dynamic_frame) glue_context.write_dynamic_frame.from_options( frame = non_null_fields, connection_type = 's3', connection_options = {'path': 's3://some-bucket/some-path'}, format = 'json')
tagged with: aws-glue
score: 0
answer count: 1
tagged with: amazon-web-services
favorite count: 0
has answer: http://stackoverflow.com/a/52724305
type: UnansweredQuestion
tagged with: python
has title: AWS Glue - prevent empty exports to S3
upvote count: 1

http://stackoverflow.com/comment/91205823
has text: I want to slap myself. Lol, thanks. I must have copied some of the code from the top of my script when I put it in my function and forgot to change it.
comment on: http://stackoverflow.com/a/52125774
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52143835
answers question: http://stackoverflow.com/q/52143710
score: 0
type: Answer
has body: Or use sys.stdout: import sys mat=[] r,c=map(int,input().split()) x=0 bool_=False for i in range(r): if bool_: print() bool_=True for j in range(c): x=x+1 mat.append(x) sys.stdout.write('%s '%mat[i])

http://stackoverflow.com/q/52269680
accepted answer: http://stackoverflow.com/a/52269898
tagged with: statistics
has title: scipy.optimize.curve_fit producing nonsensical curve fits
favorite count: 0
tagged with: machine-learning
tagged with: curve-fitting
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52269898
possible better answer: http://stackoverflow.com/a/52269969
has answer: http://stackoverflow.com/a/52269969
has body: I am trying to fit a curve to some generated data that resemble an exponential function when plotted. I am using scipy.optimize.curve_fit as it seems like it is the best (and best documented) for the job. The actual data are newly generated each time I run the code, but here is an example set: import pandas import scipy.optimize as opt x1 = [0.4145392937447818, 0.7807888116968482, 0.7903528929788539, 1.5081613036989836, -0.295895237606155, -0.0855307279546107, 1.0523973736479486, -0.6967509832843239, -0.30499200990688413, 1.1990545631966807, -1.270460772249312, 0.9531042718153095, 1.5747175535222993, -0.6483709650867473, 0.47820180254528477, 1.14266851615097, 0.6237953640100202, 0.0664027559951128, 0.877280002485417, 0.9432317053343211, 1.0367424879878504, -0.6410400513164749, 1.667835241401498, -0.20484029870424125, 2.887026948755316] y1 = [0.718716626591187, 0.579938466590508, 0.722005637974309, 1.61842778379047, 0.331301712743162, 0.342649242449043, 1.14950611092907, 0.299221762023701, 0.345063839940754, 1.08398125906313, 0.315433168226251, 1.3343730617376, 1.32514210008176, 0.308702648499771, 0.495749985226691, 0.406025683910759, 0.445087968405107, 0.423578575247177, 0.816264419038205, 1.16110461165631, 1.81572974380867, 0.420890068255763, 0.821468286117842, 0.416275933630732, 4.7877353794036] data = pandas.DataFrame({"Pi_values": x1, "CO2_at_solubility": y1}) Then, I do the curve fitting business... ##Define curve fitting def func(x, m, c, c0): return c0 + m**x * c #draw the figure fig, ax1 = plt.subplots() plt.xlabel('Pi Parameter') plt.ylabel('CO2 wt%') #plot generated data #tried converting pandas columns to np arrays based on an issue another user was having, but it does not help x1 = data["Pi_values"].values y1 = data["CO2_at_solubility"].values # Curve fitting with scipy.optimize.curve_fit popt, pcov = opt.curve_fit(func, x1, y1) # Use the optimized parameters to plot the best fit plt.plot(x1, y1, 'o', x1, func(x1, *popt)) And here is the very weird resul…
tagged with: scipy
type: Question
upvote count: 4
answer count: 2
downvote count: 0
score: 4

http://stackoverflow.com/q/52209941
has body: I want to alter values on a back end e-commerce platform via HTTP POST requests(The platform has no public facing API). This is working great when I send the full request to the correct url. payload ={ 'CourseName': 'Example ', 'CourseID': '34 ', 'mode': 'add ', 'TableCode': '20', 'Variations':' ', 'ValueToUpdate':' ', } Except my payload has significantly more parameters than this. Every time I update a product I don't want to be filling the payload with the current data on the system for that particular product then making my changes. Is it possible to just pass the parameters you want to change? payload = { 'CourseID':'34' 'mode':'update', 'ValueToUpdate':'info' } My attempts have resulted in 500 Internal server errors. Below are the request headers. Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: en-GB,en-US;q=0.9,en;q=0.8 Cache-Control: max-age=0 Connection: keep-alive Content-Length: 861 Content-Type: application/x-www-form-urlencoded
tagged with: python-requests
tagged with: http
type: Question
has comment: http://stackoverflow.com/comment/91370748
has comment: http://stackoverflow.com/comment/91371149
has comment: http://stackoverflow.com/comment/91371403
has comment: http://stackoverflow.com/comment/91370567
score: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91370106
has comment: http://stackoverflow.com/comment/91371616
answer count: 0
has title: Sending less parameters in HTTP POST request than required

http://stackoverflow.com/comment/92022986
type: QuestionComment
comment on: http://stackoverflow.com/q/52269281
has text: @user308827: then take into account that this library *could have other incompatibilities with Windows* that go beyond `os.environb`.
score: 0
type: Comment

http://stackoverflow.com/comment/91336569
comment on: http://stackoverflow.com/q/52182757
score: 0
type: Comment
type: QuestionComment
has text: I don't understand....do i need to set 'msg.payload = 1.23456' ? and then it will send that to debug node?

http://stackoverflow.com/comment/91397204
type: Comment
has text: @TejasJoshi. I understood the problem. You have to run it in console not IDLE.
comment on: http://stackoverflow.com/a/52136781
type: AnswerComment
score: 0

http://stackoverflow.com/q/52186420
type: Question
tagged with: python
answer count: 1
upvote count: 1
has title: Use shift function in pandas Dataframe function
downvote count: 0
tagged with: dataframe
type: UnansweredQuestion
has body: I want to create a function which compares different rows within a Pandas dataframe. My current function looks like this: def f(row): if row['A'].shift(1) == row['B']: val = 0 else: val = 1 return val I receive the following error message: AttributeError: ("'numpy.float64' object has no attribute 'shift'", 'occurred at index 2006-02-28 00:00:00') I understand that the problem occurs in the first row of the dataframe because there is no row which can be shifted. Does anyone know how to rewrite the funtion? Any help is appreciated.
tagged with: pandas
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52186520

http://stackoverflow.com/a/52230336
has body: You need something like this: try: # Load page browser.get("http://192.168.1.1/index.html") # Wait 10 seconds before element can be located on the page # For example, &lt;div class="example"&gt; -- first div with class "example" WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, ".//div[@class='example'][1]"))) except Exception as e: # Catch an exception in case of element unavailability print ("Page load error: {}".format(e.message))
score: 0
answers question: http://stackoverflow.com/q/52230128
type: Answer

http://stackoverflow.com/a/52194135
type: AcceptedAnswer
has body: You can directly use the image_proc/crop_decimate nodelet. You can configure it using dynamic_reconfigure to set up ROI or interpolation. However, since these are software operations, interpolation methods should be handled with care (but fastest NN method is standard anyway) since you have a real time application.
has comment: http://stackoverflow.com/comment/91372524
has comment: http://stackoverflow.com/comment/91371334
answers question: http://stackoverflow.com/q/52192049
type: Answer
accepted answer of: http://stackoverflow.com/q/52192049
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91370178
has comment: http://stackoverflow.com/comment/91369669
upvote count: 1

http://stackoverflow.com/comment/91310389
score: 0
type: Comment
type: QuestionComment
has text: add ` sites : {{ sites }} ` in your base template and check what you really get. If it's what you expect, then add the same snippet in `nav.html`.
comment on: http://stackoverflow.com/q/52179044

http://stackoverflow.com/comment/91321813
type: Comment
comment on: http://stackoverflow.com/q/52185995
score: 0
has text: Oh wow >.> You're right! I had a seperate file in there called "ssl.py" and it was conflicting. I feel like such an idiot. Thank you so much. I uninstalled everything for this!
type: QuestionComment

http://stackoverflow.com/a/52130220
has body: According to my knowledge, the best way I found to evaluate image classification accuracy is by K-fold cross validation. One can choose any value of K for cross validation however, i would prefer a value of 10 to make sure the evaluation on the test data is not biased and completely random. So when you compute the cross validation of each Kth fold, you end up getting 4 values of false positives, false negatives, true positives and true negatives. After that, one can build the confusion matrix by taking the average of each these values.
answers question: http://stackoverflow.com/q/52129782
score: 0
type: Answer

http://stackoverflow.com/comment/91276940
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52162330
type: Comment
has text: This will take a long time in computation on big data as there are a lot of loops. Is it possible to may be reduce time by introducing dictionary as datastructure and using set operations?

http://stackoverflow.com/comment/91375632
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52212118
has text: Your question title is wrong. You are not converting binary to hex - you are converting hex to binary (string `'ab'` is hex, whereas number `0xab` is binary)

http://stackoverflow.com/comment/91452592
comment on: http://stackoverflow.com/q/52252477
score: 0
type: Comment
type: QuestionComment
has text: @jezrael As you can see I am trying to do diff = float(diff1)/float(mod) so that I can carry out further operations so I really dont know how to tell you the expected output

http://stackoverflow.com/q/52224364
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52224771
type: AnsweredQuestion
has body: I've been working on Django project. Currently, user can upload only one image but now I want to change it so user can upload some images. models.py is like this. class Entry(models.Model): photo = models.ImageField(...) I am thinking of just adding photo2 and photo3 inside Entry model. But I'm wondering if there's a better way to do it. I don't want to delete images that are already uploaded. Anyone who could give me tips? Also, I don't like the file upload form's design and some people use just button-like form. I also want to know how to create button-like form.
accepted answer: http://stackoverflow.com/a/52224771
type: Question
has title: Django; What is preferable way to upload some images?
score: 0
answer count: 1

http://stackoverflow.com/comment/91395055
type: AnswerComment
has text: @johzi It would arguably be very hard to follow a piece of code if you couldn't be sure whether a line that says `raise` will or won't `raise`. There's no discernible difference between `raise foo()` and `raise bar()`, where `foo` is an exception type and will cause a raise, and `bar` being a function which may or may not return `None` and may or may not cause an exception to be raised and the following code to be executed or not.
type: Comment
comment on: http://stackoverflow.com/a/52222701
score: 0

http://stackoverflow.com/comment/91439714
type: Comment
comment on: http://stackoverflow.com/q/52245767
score: 1
type: QuestionComment
has text: Try to omit `|$` in the regex

http://stackoverflow.com/comment/110399704
has text: is it similar to an ensemble of trees? How the new points will be plotted after using the three classifiers? I can't understand this : Now with these predicted values a model is trained ?? If a classifier predicts a label then how can we use it in meta classifier, plz explain, Thanks!
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/56555200
score: 0

http://stackoverflow.com/q/52229367
tagged with: data-conversion
type: Question
duplicate of: http://stackoverflow.com/q/5552555
tagged with: encoding
has comment: http://stackoverflow.com/comment/91408443
linked to: http://stackoverflow.com/q/5552555
has comment: http://stackoverflow.com/comment/91408575
score: 0
has title: Python3 using UTF-8 data from bytes
tagged with: utf-8
tagged with: python-3.x
linked to: http://stackoverflow.com/q/49756071
answer count: 0
type: UnansweredQuestion
has body: I am using Python 3.7. I have data being read from two files. Both contain UTF-8 data (well, technically...). One is properly "encoded" into UTF-8 while the other was written as a decoded bytestream. # 'ba' is the on-disk form of the first (correctly-encoded) file &gt;&gt;&gt; ba = b'\xc3\xb6' &gt;&gt;&gt; ba b'\xc3\xb6' &gt;&gt;&gt; ba.decode() 'ö' # 'bb' is the on-disk form of the incorrectly-encoded second file &gt;&gt;&gt; bb = b'\xf6' &gt;&gt;&gt; bb b'\xf6' # 'bs' is the unicode version of the same byte value as bb &gt;&gt;&gt; bs = '\xf6' &gt;&gt;&gt; bs 'ö' # If I try to decode ba, I get the correct value. &gt;&gt;&gt; ba.decode() 'ö' &gt;&gt;&gt; ba.decode() == bs True # But if I try to decode bb, I get an encoding error. &gt;&gt;&gt; bb.decode() == bs Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 0: invalid start byte How do I turn bb from an incorrectly-encoded bytes object into a correctly-decoded str object? I am okay with making an assumption that bb is UTF-8 decoded data blob instead of garbage. I have already done a little bit of searching to try to solve it myself. It's honestly rather difficult to filter the Python2.x cruft from Google results though. I did find this answer helpful since it mentions the "unicode-escape" encoding which appears to do what I want it to do: &gt;&gt;&gt; bb.decode('unicode-escape') 'ö' &gt;&gt;&gt; bb.decode('unicode-escape') == bs True However, it is not clear to me what side effects that 'unicode-escape' might present outside of this specific scenario. It seems to indicate that it reads escaped encodings, but I don't believe b'\xf6' is escaped: I believe it is a single byte represented as hex to the python interpreter. I would assume that an escaped encoding would be something like b'\\xf6', which should be four bytes: ASCII backslash, ASCII 'x', ASCII 'f', and ASCII '6'. &gt;&gt;&gt; bc b'\\xf6' &gt;&gt;&gt; bc.d…
tagged with: python

http://stackoverflow.com/q/52234914
type: Question
downvote count: 0
has title: Access axes object in seaborn lmplot
favorite count: 0
upvote count: 8
tagged with: data-visualization
answer count: 1
accepted answer: http://stackoverflow.com/a/52234951
linked to: http://stackoverflow.com/q/25212986
score: 8
tagged with: seaborn
has body: Most seaborn plotting functions (e.g. seaborn.barplot, seaborn.regplot) return a matplotlib.pyplot.axes when called, so that you can use this object to further customize the plot as you see fit. However, I wanted to create an seaborn.lmplot, which doesn't return the axes object. After digging through the documentation of both seaborn.lmplot and seaborn.FacetGrid (which lmplot uses in it's backend), I found no way of accessing the underlying axes objects. Moreover, while most other seaborn functions allow you to pass your own axes as a parameter on which they will draw the plot on, lmplot doesn't. One thing I thought of is using plt.gca(), but that only returns the last axes object of the grid. Is there any way of accessing the axes objects in seaborn.lmplot or seaborn.FacetGrid?
tagged with: python
type: AnsweredQuestion
tagged with: matplotlib
duplicate of: http://stackoverflow.com/q/25212986
has answer: http://stackoverflow.com/a/52234951

http://stackoverflow.com/q/52229486
upvote count: 0
answer count: 1
favorite count: 0
tagged with: postgresql
has title: How to pass data to jinja templet
accepted answer: http://stackoverflow.com/a/52236020
tagged with: python
type: AnsweredQuestion
has body: I might be tired after long hours of punching on keyboard but I'm currently unable to move any further. Here is the code: elif request.form["submit"] == "blah": cursor.execute('''SELECT * FROM "Table_x"''') results = cursor.fetchall() for record in cursor: results.append(record) return "Showing all:" + str(results) + render_template("index.html") Based on the above, output on rendered template gives me a nasty looking list of tuples. [(1, 'Dummy1', 'dummy1', 1), (2, 'Dummy2', 'dummy2', 2), (3, 'Dummy3', 'dummy3', 3)] How can I change return or results variable (or both) so that each tuple in the list would print in separate line ?
has comment: http://stackoverflow.com/comment/91408634
tagged with: jinja2
downvote count: 1
type: Question
score: -1
has answer: http://stackoverflow.com/a/52236020
tagged with: flask
has comment: http://stackoverflow.com/comment/91408659

http://stackoverflow.com/a/52166657
type: Answer
downvote count: 0
has body: A distinction is made because when you define a @property on a class, that property object becomes an attribute on the class. Whereas when you define attributes against an instance of your class (in your __init__ method), that attribute only exists against that object. This might be confusing if you do: &gt;&gt;&gt; dir(LineItem) ['__class__', ..., '__weakref__', 'subtotal', 'weight'] &gt;&gt;&gt; item = LineItem("an item", 3, 1.12) &gt;&gt;&gt; dir(item) ['__class__', ..., '__weakref__', 'description', 'price', 'subtotal', 'weight'] Notice how both subtotal and weight exist as attributes on your class. I think it's also worth noting that when you define a class, code under that class is executed. This includes defining variables (which then become class attributes), defining functions, and anything else. &gt;&gt;&gt; import requests &gt;&gt;&gt; class KindOfJustANamespace: ... text = requests.get("https://example.com").text ... while True: ... break ... for x in range(2): ... print(x) ... 0 1 &gt;&gt;&gt; KindOfJustANamespace.text '&lt;!doctype html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;title&gt;Example Domain...' A @decorator is just "syntactic sugar". Meaning @property over a function if the same as function = property(function). This applies to functions defined inside a class as well, but now the function is part of the class's namespace. class TestClass: @property def foo(self): return "foo" # ^ is the same as: def bar(self): return "bar" bar = property(bar) A good explanation of property in Python can be found here: https://stackoverflow.com/a/17330273/7220776
score: 3
answers question: http://stackoverflow.com/q/52162720
upvote count: 3

http://stackoverflow.com/comment/91413220
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52231908
has text: Please add this limitation to the question because it makes your expected solution possible.
score: 0

http://stackoverflow.com/comment/91320190
score: 1
has text: I highly doubt they wanted a list as output. `[x for x in val]` is... pointless when you could just use `list(val)`, and only the `vat[2:]` slice would need converting.
type: AnswerComment
comment on: http://stackoverflow.com/a/52185123
type: Comment

http://stackoverflow.com/a/58853787
has body: Okay, so your problem is solved. To be noted, you had done 2 things wrong here. First, you missed a bracket on line 8 and Second one is that you should apply {} to update the dictionary. Let me show you the correct code: butikk = { "melk": 14.9, "broed": 24.9, "yoghurt": 12.9, "pizza": 39.9 } ny_vare = input("Skriv inn en matvare og prisen: ") ny_vare_pris = float(input("Hvor mye koster varen? ")) ny_vare1 = input("Skriv inn en matvare: ") ny_vare1_pris = float(input("Hvor mye koster varen? ")) butikk.update({ny_vare: ny_vare_pris}) butikk.update({ny_vare1: ny_vare1_pris}) print(butikk) Now you will get your desired output.
type: Answer
answers question: http://stackoverflow.com/q/52216652
downvote count: 1
upvote count: 0
score: -1

http://stackoverflow.com/q/52268592
has comment: http://stackoverflow.com/comment/91513816
has body: I'm trying to send a parameter to read_sql function using Pandas but it returns empty dataframe. The same code works perfectly when I use Ms SQL Server engine. Do I make a mistake in parameter provision? The other problem is that when I change '=' to 'like' the query works. Here is my code: import sqlalchemy import pandas as pd import base64 sqliteengine = sqlalchemy.create_engine('sqlite:///Quotes.db') query = "SELECT * FROM OHLCTable WHERE nSymbol = ? ORDER BY Date" self.df = pd.read_sql_query(query, sqliteengine, params= [base64.b64encode(self.listWidget.currentItem().text().encode('utf-8')).decode('ascii')]) and here is my table schema
has comment: http://stackoverflow.com/comment/91500665
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/91513435
score: 0
tagged with: pandas
tagged with: sqlite
has title: Sending parameters to sqlalchemy read_sql with pandas and sqlite connection

http://stackoverflow.com/q/52143915
score: 0
answer count: 1
has body: I have a 4d numpy array with shape: (5500, 350, 350, 3) These represent 5500 images of size 350x350 pixels, with the 4th dimension being a number from 0 to 255 representing the RGB values of each pixel. I want to scale these to be between 0 and 1 (ie. divide by 255) for all 5500 images. How should this be done?
has comment: http://stackoverflow.com/comment/91237901
accepted answer: http://stackoverflow.com/a/52143999
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: numpy
has title: Python: Scaling all 4th dimension values in a 4d array?
has answer: http://stackoverflow.com/a/52143999
has comment: http://stackoverflow.com/comment/91237645

http://stackoverflow.com/a/52150628
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91255603
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52147266
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52147266
has body: You can use argparse.Remainder (explanation in the last bullet point here in the doc): import argparse VERSION = "1.0" parser = argparse.ArgumentParser(description='Argparse test') parser.add_argument('-v', '--version', help='Print version', action='version', version=VERSION) parser.add_argument('-a', '--analyse', help='Analyse command execution', nargs=argparse.REMAINDER, action='append') args = parser.parse_args() if args.analyse: print(args.analyse)
has comment: http://stackoverflow.com/comment/91255192
has comment: http://stackoverflow.com/comment/91252436
type: Answer

http://stackoverflow.com/q/52152464
downvote count: 1
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/91256371
score: 0
answer count: 1
has title: Convert normal Python script to REST API
accepted answer: http://stackoverflow.com/a/52152695
favorite count: 0
has body: Here I have an excel to pdf conversion script. How can I modify it to act as a REST API? import os import comtypes.client SOURCE_DIR = 'D:/projects/python' TARGET_DIR = 'D:/projects/python' app = comtypes.client.CreateObject('Excel.Application') app.Visible = False infile = os.path.join(os.path.abspath(SOURCE_DIR), 'ratesheet.xlsx') outfile = os.path.join(os.path.abspath(TARGET_DIR), 'ratesheet.pdf') doc = app.Workbooks.Open(infile) doc.ExportAsFixedFormat(0, outfile, 1, 0) doc.Close() app.Quit()
tagged with: python
has answer: http://stackoverflow.com/a/52152695
type: AnsweredQuestion
upvote count: 1

http://stackoverflow.com/q/52189093
has comment: http://stackoverflow.com/comment/91330326
has comment: http://stackoverflow.com/comment/91329028
type: Question
has comment: http://stackoverflow.com/comment/91329200
tagged with: mnist
tagged with: recurrent-neural-network
tagged with: lstm
score: 0
has comment: http://stackoverflow.com/comment/91328172
answer count: 1
tagged with: keras
has title: Simple LSTM training with return_sequences=True in Keras
has body: I am trying to train a simple LSTM based RNN model in Keras using return_sequences. As I want all the timestep output. Here is the code I am using: model = Sequential() model.add(LSTM(10, return_sequences = True, input_shape = (8, 8))) model.add(Activation('softmax')) model.compile(loss = 'categorical_crossentropy', optimizer = adam, metrics = ['accuracy']) model.fit(X_train, y_train, batch_size = 1, epochs = 1000, verbose = 1) But I get the following error: model.fit(X_train, y_train, batch_size = 1, epochs = 1000, verbose = 1) File "C:\Program Files\Anaconda3\lib\site-packages\keras\models.py", line 1002, in fit validation_steps=validation_steps) File "C:\Program Files\Anaconda3\lib\site-packages\keras\engine\training.py", line 1630, in fit batch_size=batch_size) File "C:\Program Files\Anaconda3\lib\site-packages\keras\engine\training.py", line 1480, in _standardize_user_data exception_prefix='target') File "C:\Program Files\Anaconda3\lib\site-packages\keras\engine\training.py", line 113, in _standardize_input_data 'with shape ' + str(data_shape)) ValueError: Error when checking target: expected activation_1 to have 3 dimensions, but got array with shape (1437, 10) But the same code works fine when I change the line from: model.add(LSTM(10, return_sequences = True, input_shape = (8, 8))) to: model.add(LSTM(10, return_sequences = False, input_shape = (8, 8))) I am assuming I will have to change the Activation('softmax') layer definition, but not sure how. Can someone help me in resolving this? TIA
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52203109

http://stackoverflow.com/q/52214776
accepted answer: http://stackoverflow.com/a/52214971
tagged with: python
type: AnsweredQuestion
tagged with: matplotlib
has body: I'm kind of new in coding and thus in python so this may sound quite dumb, but what are the main differences between .subplot() and .subplots() methods from matplotlib in python? I didn't find this explanation anywhere else and after reading the documentation from https://matplotlib.org/ I inferred that with both methods you can create as many figures and plots as you want...so for me both of them seem to be quite the same thing and they just differ the way you can handle plots, axes, etc...or am I wrong? Btw, I am using python3 in jupyter notebook if it makes any difference.
type: Question
score: 30
has answer: http://stackoverflow.com/a/77970485
has answer: http://stackoverflow.com/a/52214971
has title: Python - matplotlib - differences between subplot() and subplots()
possible better answer: http://stackoverflow.com/a/77970485
answer count: 2
tagged with: windows
downvote count: 0
favorite count: 0
tagged with: jupyter-notebook
tagged with: python-3.x
upvote count: 30

http://stackoverflow.com/comment/91429573
has text: Thank you, I was being super dense and just assuming that community_id was the same thing as my field communityID bleh.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52240351
score: 0

http://stackoverflow.com/comment/91439896
comment on: http://stackoverflow.com/a/52243880
score: 0
type: AnswerComment
type: Comment
has text: @ArpitSvt I didn't understand why exactly Django doesn't know where to redirect as it works fine with the class 'Seminary', but not with 'Paper'. As you can see I want to work with get_absolute_url. But Django won't accept it in case of the class 'Paper', and I don't know why.

http://stackoverflow.com/q/52216654
accepted answer: http://stackoverflow.com/a/52216813
score: 0
upvote count: 1
answer count: 1
favorite count: 0
tagged with: sftp
tagged with: python
type: AnsweredQuestion
has body: I am using the following code to download files, def download_dir(remote_dir, local_dir): import os os.path.exists(local_dir) or os.makedirs(local_dir) dir_items = sftp.listdir_attr(remote_dir) for item in dir_items: # assuming the local system is Windows and the remote system is # os.path.join won't help here, so construct remote_path manually remote_path = remote_dir + '/' + item.filename local_path = os.path.join(local_dir, item.filename) if S_ISDIR(item.st_mode): download_dir(remote_path, local_path) else: sftp.get(remote_path, local_path) download_dir("/home","C:\\Users\\ShareM\\Desktop") How can I download it to a folder with DateStamp? For example, if I download today, the folder it downloads to should be named 07/09/2018.
downvote count: 1
has title: Downloading All Files from SFTP folder to local folder with Date using Python
type: Question
has answer: http://stackoverflow.com/a/52216813

http://stackoverflow.com/q/52230706
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91410970
has title: How do I split a list when items (ints) are 1 away from each other?
type: Question
duplicate of: http://stackoverflow.com/q/2154249
upvote count: 1
has comment: http://stackoverflow.com/comment/91410979
has body: I have a list such as [6,6,2,6,6,7,5,2,0,5,6]. I can enumerate it to get the list [(0,6),(1,6),(2,2),(3,6),(4,6),(5,7),(6,5),(7,2),(8,0),(9,5),(10,6)] very easily. Then, what I want is to save the values of every index which has a 2nd value >= 5; that is, the output of that would be [0, 1, 3, 4, 5, 6, 9, 10]. I can do this very well so far. Now, what I desire is to parse this in this fashion: [(0,1),(3,4,5,6),(9,10)] Separating the items into groups where the difference between any two adjacent items is exactly 1. My code so far: histo = [6,6,2,6,6,7,5,2,0,5,6] histo = list(enumerate(histo)) abarrote = [x[0] for x in histo if x[1] &gt;= 5] #Out[1]: [0, 1, 3, 4, 5, 6, 9, 10] #Desired output: [(0,1),(3,4,5,6),(9,10)] Thanks in advance.
favorite count: 0
has comment: http://stackoverflow.com/comment/91410987
linked to: http://stackoverflow.com/q/2154249
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91269181
score: 0
type: Comment
type: QuestionComment
has text: data at https://s3-ap-southeast-1.amazonaws.com/bsy/iportal/images/Annual-report-2017-18_324BCC06D8C6765F2F6C750DD9CD8C63.pdf and i want to Fetch Balance sheet at random page.
comment on: http://stackoverflow.com/q/52125052

http://stackoverflow.com/q/52157576
favorite count: 0
has title: PyJWT raises Signature verification failed
has body: I'm trying to verify JWT which issued by ThingsBoard. But verification was failed with Signature verification failed My test code is at below. def test_jwt_decoding(): jwt_options = { 'verify_signature': True, 'verify_exp': True, 'verify_nbf': False, 'verify_iat': True, 'verify_aud': False } token = 'eyJhbGciOiJIUzUxMiJ9.[binary].N1Ms0LA7WtOel1pg6lTMRNDJosY3qfR6Q4SVuAUwmDPmTj4uYnKU0B-9Wdlqmg4HQRUXa23edOTU-TnAxfBoyg' try: jwt.decode( token, 'thingsboardDefaultSigningKey', algorithms=['HS512'], options=jwt_options ) assert True except Exception as err: print(str(err)) assert False I checked the signature was verified at jwt.io Only difference was secret base64 encoded on at jwt.io I'm gussing secret base64 encoded made this differences. What should I do for that?
tagged with: python
score: 10
has answer: http://stackoverflow.com/a/52158126
type: AnsweredQuestion
upvote count: 10
type: Question
tagged with: jwt
tagged with: thingsboard
accepted answer: http://stackoverflow.com/a/52158126
tagged with: pyjwt
answer count: 1
downvote count: 0

http://stackoverflow.com/a/52383097
upvote count: 7
answers question: http://stackoverflow.com/q/52253791
type: Answer
downvote count: 0
score: 7
has body: You must be using flask-sqlalchemy, behind the scenes, it uses the declarative extension to define your models. By subclassing a sqlalchemy declarative base class, sqlalchemy will generate Table and mapper for you, newly created table info stores in the corresponding Metadata obj. db.create_all() actually is metadata.create_all(), which will only create tables stored in the metadata. Therefore, before you try to create a table with metadata.create_all, you have to store the info of that table into the metadata registry first, which equals to define a declarative base subclass. In python, this means to get your class definition code executed, which in turns, import the module the classes defined.

http://stackoverflow.com/comment/91462313
comment on: http://stackoverflow.com/a/52257323
type: Comment
has text: Well I see nothing wrong with the parsing code, so we're back to guessing games.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52120850
has answer: http://stackoverflow.com/a/52120994
has answer: http://stackoverflow.com/a/52121229
has comment: http://stackoverflow.com/comment/91193360
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91193138
favorite count: 0
has title: Python Search a text file for keyword and print the associated line for multiple keywords
type: UnansweredQuestion
tagged with: python
tagged with: text-extraction
has comment: http://stackoverflow.com/comment/91192943
has comment: http://stackoverflow.com/comment/91192979
has body: I'm trying to search a .txt file that contains a lot of extraneous information for just a few keywords that contain the most important information. I would like to find the words and print out the line that word is in. I'm fairly new to python and thought I had it figured out but I don't know how to scale my current code for multiple keywords. fileName = input("Paste file name here") with open(fileName) as inputFile: data = inputFile.readlines() inputFile.close() for i, line in enumerate(data): searchPhrase1 = input("what phrase are you looking for?") if searchPhrase1 in line: for l in data[i:i:3]: print (l) print
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/q/52252054
tagged with: python-3.6
accepted answer: http://stackoverflow.com/a/52252884
has comment: http://stackoverflow.com/comment/91474486
has answer: http://stackoverflow.com/a/52252298
has answer: http://stackoverflow.com/a/52268086
answer count: 7
tagged with: python-decorators
has answer: http://stackoverflow.com/a/52252884
favorite count: 0
upvote count: 37
has answer: http://stackoverflow.com/a/52252154
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52254895
has title: Same name functions in same class - is there an elegant way to determine which to call?
has answer: http://stackoverflow.com/a/52252933
type: Question
score: 37
has comment: http://stackoverflow.com/comment/91474517
has body: I am trying to do product version control in Python scripts for a specific reason, but I couldn't figure out how to do it in an elegant way. Currently, I am doing something like the below. However, the scripts are hard to maintain when version content is changed. class Product(object): def __init__(client): self.version = client.version # Get client version from another module def function(): if self.version == '1.0': print('for version 1.0') elif self.version == '2.0': print('for version 2.0') else: print(f'function not support {self.version}') Therefore, I want to do something like the below to separate the functions with the same name. class Product(object): def __init__(client): self.version = client.version # Get client version from another module def function(): print('for version 1.0') def function(): print('for version 2.0') I was thinking about to use decorator to achieve this: class Product(object): def __init__(client): self.version = client.version # Get client version from another module @version(1.0) def function(): print('for version 1.0') @version(2.0) def function(): print('for version 2.0') However, I failed to figure out how... it seems like a decorator cannot do this kind operation or I just don't understand how to. Is there a elegant way to do this?
has answer: http://stackoverflow.com/a/52265942
tagged with: version-control
possible better answer: http://stackoverflow.com/a/52252154
downvote count: 0

http://stackoverflow.com/comment/91556152
type: AnswerComment
comment on: http://stackoverflow.com/a/52266846
score: 0
type: Comment
has text: It looks like this: { "testcase_ID":"test_1A","description":"Some description","request_change_data": [ { "element_path": "[cars][0][car_model]", "element_value": "cx-9" } ] } ...

proxy
tags question: http://stackoverflow.com/q/52127287
type: Tag
tags question: http://stackoverflow.com/q/52141434
tags question: http://stackoverflow.com/q/52113219
tag name: proxy

http://stackoverflow.com/a/52246215
upvote count: 1
has body: First of all the line fig = figure(**fig_kw) calls the pyplot.figure function. This registers the figure inside the pyplot state machine. fig is a matplotlib.figure.Figure instance. Next, it's subplots method is called. This will essentially create an array and fill it will matplotlib.axes.Axes instances. Those are created with self.add_subplot. add_subplot will initialize the axes and store it as part of the figure's fig.axes array. So in total you have pyplot which stores the figures and each figure stores the axes in it. When calling plt.show() it will basically loop through all figures and show them. For each figure, all axes inside fig.axes will be drawn. If you have previously manipulated any of the axes by calling any of their methods, those will of course be taken into account because you manipulated exactly the axes object that is later also drawn.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52241042
answers question: http://stackoverflow.com/q/52241042
type: Answer
score: 1

http://stackoverflow.com/q/52245729
favorite count: 0
possible better answer: http://stackoverflow.com/a/52245878
tagged with: python
has answer: http://stackoverflow.com/a/52245878
type: AnsweredQuestion
tagged with: list
has body: I have started to create a password checker program for part of my assignment. It takes an initial input from the user, stores it in an external file, then takes another input and checks if both inputs match. If they match, it should return a printed message. However, it is not returning anything, even if they match. #storing passwords in an external file file = open("passwordlearn.csv", "a+") password = input("Please enter a password: ") file.write(password + "\n") file.close() #opening a connection to password.csv temp = open("passwordlearn.csv", "r") password = temp.read() temp.close() #splitting the string up eachPassword = password.split ("\n") #creating a list newlistthree=[] for eachItem in eachPassword: record = eachItem.split(",") newlistthree.append(record) print(newlistthree) #creating a list with the blank deleted newlistfour=[] for eachItem in eachPassword: record = eachItem.split(",") newlistfour.append(record) del newlistfour[-1] print(newlistfour) firstpassword = newlistfour.pop() print(firstpassword) #authentication passwordcheck = input("Please type your password again: ") if passwordcheck == firstpassword: print("Passwords Match. Please login.")
accepted answer: http://stackoverflow.com/a/52245850
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52245850
score: 0
has title: Python Password Checker Program - Comparison with .pop() value not working
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/91240779
type: QuestionComment
type: Comment
has text: kindly add the answers bellow so i can test, thanks
comment on: http://stackoverflow.com/q/52145497
score: 0

http://stackoverflow.com/a/52152924
downvote count: 0
answers question: http://stackoverflow.com/q/52152365
score: 4
has body: This code works fine dts = pd.read_csv('C:\DtsPMU\dts.csv', dtype=float , skiprows=60, nrows=75) The only problem is that it makes the row number 60 as the header, if you want the original header then use names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None. Duplicates in this list will cause a UserWarning to be issued. For example: if your file has 3 columns, then dts = pd.read_csv('C:\DtsPMU\dts.csv', dtype=float , skiprows=60, nrows=75, names=[0,1,2])
has comment: http://stackoverflow.com/comment/91258680
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/91257334

http://stackoverflow.com/a/52244610
downvote count: 0
has body: You can just use: df['new_column'] = df2[0].repeat(5).values with 5 being your resampling factor
answers question: http://stackoverflow.com/q/52244366
accepted answer of: http://stackoverflow.com/q/52244366
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91438295

http://stackoverflow.com/comment/118211425
has text: thank you. So mine is running like 24 hrs and going on.. here is my 2 Q ANY HELP PLZ https://stackoverflow.com/questions/66856883/fuzzy-matching-two-dataframes-columns-without-a-key-column-and-different-rows?noredirect=1#comment118183672_66856883
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52271721

http://stackoverflow.com/q/52130291
has comment: http://stackoverflow.com/comment/91211007
has answer: http://stackoverflow.com/a/52130454
has title: Python - addition to an existing row of a dataframe
tagged with: python
type: AnsweredQuestion
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91211004
type: Question
has body: Is there a way to add or subtract to an existing dataframe? For example, given the code below: import pandas as pd Apple= pd.DataFrame({'Product':['MacBook', 'iPhone', 'iPad', 'Apple Watch'], 'Inventory':['999', '333', '666', '190']}) Is there a way to add 150 to an existing inventory so that the number of Apple Watches is 340?
has answer: http://stackoverflow.com/a/52130360
has answer: http://stackoverflow.com/a/52130367
accepted answer: http://stackoverflow.com/a/52130360
upvote count: 2
possible better answer: http://stackoverflow.com/a/52130367
answer count: 3
tagged with: pandas
favorite count: 0

http://stackoverflow.com/a/52201690
has comment: http://stackoverflow.com/comment/91368606
answers question: http://stackoverflow.com/q/52182910
type: Answer
upvote count: 2
score: 2
has body: You can try to use a generator function which feeds the data into the pipline. Take a look at https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_generator
has comment: http://stackoverflow.com/comment/91381020
downvote count: 0

http://stackoverflow.com/comment/91249501
type: Comment
has text: @MysteryGuy - Sure, check now.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52149388

http://stackoverflow.com/a/52775545
has body: I don't know about negative binomial loss, but I do know how to implement a custom loss function def custom_loss(y_true, y_pred): ... loss = ... return loss Treat y_true and y_pred as tensors. (this means instead of using functions such as np.pow(y_true,2) you need to use functions from tensorflow or keras.backend) pass your custom loss function as compile argument model.compile(loss=custom_loss, optimizer='your favorite optimizer')
score: 1
answers question: http://stackoverflow.com/q/52205479
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91381467
has text: Thank you for the comment. Is the script directory not the same as the working directory? At least I am setting the working directory to be the same as the script directory when I'm invoking the Python script from the C++ program
comment on: http://stackoverflow.com/q/52209760
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91448023
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52249753
has text: @ggorlen Sorry, I have corrected the code.
score: 0

http://stackoverflow.com/q/52255642
has comment: http://stackoverflow.com/comment/91458639
duplicate of: http://stackoverflow.com/q/23294658
has comment: http://stackoverflow.com/comment/91459118
has comment: http://stackoverflow.com/comment/91460328
has comment: http://stackoverflow.com/comment/91458659
has answer: http://stackoverflow.com/a/52256014
linked to: http://stackoverflow.com/q/23294658
accepted answer: http://stackoverflow.com/a/52255753
has comment: http://stackoverflow.com/comment/91458771
tagged with: python
has comment: http://stackoverflow.com/comment/91458728
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91458780
has comment: http://stackoverflow.com/comment/91460219
has answer: http://stackoverflow.com/a/52255753
has comment: http://stackoverflow.com/comment/91458974
possible better answer: http://stackoverflow.com/a/52256014
has comment: http://stackoverflow.com/comment/91459309
type: AnsweredQuestion
score: -2
has title: How can i go back to the if statement in Python 3?
type: Question
upvote count: 2
answer count: 2
has body: I am making a Python program where I can work with files from any part of my computer. It's not done yet but I ran into a problem. This is my code: import os from os.path import join import subprocess def opening_file(lookfor): global store_1 for root, dirs, files in os.walk('/home/'): if lookfor in files: file = join(root, lookfor) store_1.append(join(root, lookfor)) if len(store_1) &lt;= 0: ask_1 = str(input("Your file was not found. Do you want to try again(Y/n)?:")) #This is where I have the problem elif len(store_1) &gt; 0: print("Your file was found") subprocess.call(["xdg-open", file]) #print(store_1) store_1 = [] print("Welcome to our program for working with files.") print("Press O for opening and editing a file, C for making a copy of a file. M for moving a file and R for renaming a file. If you are done working with the file, press F to end the program.") choice = str(input("Your choice:")) if choice == "O" or choice == "o": lookfor = input("File name(make sure to include the extension as well):") opening_file(lookfor) I want to know how can i go back to the if statement the user entered with his/her input when the file is not being found. Is there any way I can do this? I have googled but I cannot find a solution to my problem. My OS is Ubuntu 16.04.
downvote count: 4

http://stackoverflow.com/comment/91288322
comment on: http://stackoverflow.com/a/52152565
has text: @Brian Oakley: You are completely correct, of course. But with notebooks, only one tab is ever shown at any one time, so it should be possible to move the widget about from tab to tab when the user selected a new tab.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91467265
score: 0
type: AnswerComment
has text: I just added one, but it doesn't change a thing :/
comment on: http://stackoverflow.com/a/52259742
type: Comment

http://stackoverflow.com/a/52116903
downvote count: 0
has comment: http://stackoverflow.com/comment/91184770
has body: I'd recommend the python itsdangerous library. Here is a quick example: from itsdangerous import URLSafeSerializer s = URLSafeSerializer('secret-key') print(s.dumps([1, 2, 3, 4])) # 'WzEsMiwzLDRd.wSPHqC0gR7VUqivlSukJ0IeTDgo' print(s.loads('WzEsMiwzLDRd.wSPHqC0gR7VUqivlSukJ0IeTDgo')) # [1, 2, 3, 4] The secret-key can be shared between you and the other trusted party to decrypt the strings or columns. This does rely on serialization however and some python data types aren't easily serialized, but if you just need a column name or something like that, this could work well. I would like to add a qualification here that this process only obfuscates the data, but does not actually encrypt it. I did not fully understand that when I originally answered this question. This obfuscation may be enough for your needs, but please be aware! From the docs: The receiver can decode the contents and look into the package, but they can not modify the contents unless they also have your secret key. Docs
type: Answer
answers question: http://stackoverflow.com/q/52116171
upvote count: 7
has comment: http://stackoverflow.com/comment/91184902
score: 7
accepted answer of: http://stackoverflow.com/q/52116171
type: AcceptedAnswer

http://stackoverflow.com/q/52254618
has comment: http://stackoverflow.com/comment/91457416
score: 2
has body: I have the following pipelines, I want to get the features wights with respect to each class. I have three classes ('Fiction','None-fiction','None'). The classifier that I use is SVC. Book_contents= Pipeline([('selector', ItemSelector(key='Book')), ('tfidf',CountVectorizer(analyzer='word', binary=True, ngram_range=(1,1))), ]) Author_description= Pipeline([('selector', ItemSelector(key='Description')), ('tfidf', CountVectorizer(analyzer='word', binary=True, ngram_range=(1,1))), ]) ppl = Pipeline([('feats', FeatureUnion([('Contents',Book_contents), ('Desc',Author_description)])), ('clf', SVC(kernel='linear',class_weight='balanced')) ]) model = ppl.fit(training_data, Y_train) I have tried eli5 but I got error of mismatch between feature name and classifier. f1=model.named_steps['feats'].transformer_list[0][1].named_steps['tfidf'].get_feature_names() f2=model.named_steps['feats'].transformer_list[1][1].named_steps['tfidf'].get_feature_names() list_features=f1 list_features.append(f2) explain_weights.explain_linear_classifier_weights(model.named_steps['clf'], vec=None, top=20, target_names=ppl.classes_, feature_names=list_features) I got this error: feature_names has a wrong length: expected=47783, got=10528 How to get the rank of features wights with respect to each class? is their a way to do that without eli5?
upvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/91457539
has comment: http://stackoverflow.com/comment/91457664
linked to: http://stackoverflow.com/q/252703
has title: The features importance from scikit -learn pipeline (SVC)
tagged with: svm
has answer: http://stackoverflow.com/a/52367637
has comment: http://stackoverflow.com/comment/91457930
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has comment: http://stackoverflow.com/comment/91457115
has comment: http://stackoverflow.com/comment/91458179
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52122193
has comment: http://stackoverflow.com/comment/91195744
tagged with: python
score: 2
tagged with: python-3.x
tagged with: tkinter
type: UnansweredQuestion
type: Question
has title: Plotting a line using user tkinter inputs as coordinates with Matplotlib
tagged with: matplotlib
has body: I embed a Matplotlib line chart in my Tkinter GUI environment. My "experiment" basically takes two inputs (numbers) from the user and then it's supposed to use them to draw a line. However, I have no clue on how to plot a line graph based on the user inputs. Can someone please explain how to do it? Here is my code: from tkinter import * import tkinter as tk from tkinter import ttk import matplotlib.pyplot as plt import numpy as np root = tk.Tk() root.geometry('500x700') first_input = StringVar() second_input = StringVar() class Graph(): def linechart(): x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] y = [1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5] plt.plot(x, y) plt.xticks(np.arange(min(x), max(x)+1, 1.0)) plt.show() class Random(Graph): def __init__(self): self.label1 = None self.label2 = None self.userEntry = None def first_input(self): self.label1 = ttk.Label(text="Insert:") self.label1.pack() self.userEntry = ttk.Entry(textvariable=first_input) self.userEntry.pack() self.button_2 = Button(root, text="Enter", command=self.second_input) self.button_2.pack() def second_input(self): self.label2 = ttk.Label(text="Insert:") self.label2.pack() self.userEntry = ttk.Entry(textvariable=second_input) self.userEntry.pack() self.button_3 = Button(root, text="Enter", command=self.create_window) self.button_3.pack() def create_window(self): Graph.linechart() random = Random() button_1 = Button(root, text="random", command=lambda:random.first_input()) button_1.pack() root.mainloop()
upvote count: 3
answer count: 1
downvote count: 1
tagged with: tkinter-canvas
has answer: http://stackoverflow.com/a/52125462
favorite count: 0

http://stackoverflow.com/comment/91414972
score: 0
type: Comment
has text: I didn't check it yet but when you wrote you used a brute force I thought it will be slower.
type: AnswerComment
comment on: http://stackoverflow.com/a/52230645

http://stackoverflow.com/q/52187453
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91324903
has comment: http://stackoverflow.com/comment/91361203
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/91327369
has comment: http://stackoverflow.com/comment/91325364
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/54295477
score: 1
upvote count: 1
tagged with: tensorflow
type: Question
has title: I am using keras and I get an error message saying "No module named 'lstm'"
has answer: http://stackoverflow.com/a/69328993
tagged with: lstm
has body: I am trying to set up Keras with the following code: from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential import lstm, time #helper libraries Unfortunately it gives me two error message and I can't get my head around it: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/_bootstrap.py:205: RuntimeWarning: compiletime version 3.5 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.6 return f(*args, **kwds) and ModuleNotFoundError Traceback (most recent call last) ModuleNotFoundError: No module named 'lstm' Thanks in advance, Victor

http://stackoverflow.com/a/52280162
upvote count: 7
score: 7
downvote count: 0
type: Answer
has body: Well, the start of the string (this part data:image/jpeg;base64,) tells you it is base64 encoded. So, you need to strip all that off and find the start the image, which is /9j, and just grab the image part which is the rest of the string. b = b'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...' z = b[b.find(b'/9'):] Then you need base64 decode the result, and make it into a BytesIO object that PIL can read. Then read it into a PIL Image and save it: im = Image.open(io.BytesIO(base64.b64decode(z))).save('result.jpg') So, the entire code will look like: import base64 import io from PIL import Image # Initialise your data b = b'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...' z = b[b.find(b'/9'):] im = Image.open(io.BytesIO(base64.b64decode(z))).save('result.jpg') Keywords: image, image processing, base64, b64, encode, encoded, decode, decoded, PIL, Pillow, Python
answers question: http://stackoverflow.com/q/52258557

http://stackoverflow.com/comment/101864051
type: Comment
comment on: http://stackoverflow.com/a/57375054
score: 2
has text: seems this has problems later on if you try to use tf.keras and "pure" keras
type: AnswerComment

http://stackoverflow.com/comment/91333372
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52189926
has text: I edited with your code sugestion

http://stackoverflow.com/a/52202378
has body: For the specific example np.array(my_array) as it needs to run through all the elements of my_array, allocate memory and initialize the values, it takes place in linear time. There is a python module big_O that can be used to analyze the complexity of a function from its execution time. Refer to this link for more information
type: Answer
answers question: http://stackoverflow.com/q/52201990
score: 5
upvote count: 5
downvote count: 0

http://stackoverflow.com/comment/91233737
comment on: http://stackoverflow.com/q/52141874
type: Comment
type: QuestionComment
has text: I don't see the benefit of writing pseudo code alongside real code in a snippet this small. Either write pseudo code, or write real python. This snippet is easy enough to test! Try things out, see what works and what doesn't. By the time you've received an answer, you could've probably solved the issue by just _trying some stuff_.
score: 0

http://stackoverflow.com/comment/91386711
has text: Your proposed solution should work. Have you checked it?
comment on: http://stackoverflow.com/q/52219100
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91464450
comment on: http://stackoverflow.com/a/52258427
type: AnswerComment
has text: It's common for interactive programs to write to stderr instead of stdout. For example, `read -p "Type something: "` will display its prompt on stderr.
type: Comment
score: 1

http://stackoverflow.com/a/52249134
answers question: http://stackoverflow.com/q/52248402
score: 0
accepted answer of: http://stackoverflow.com/q/52248402
type: AcceptedAnswer
type: Answer
has body: It is my fault - sorry, the code is working fine, but the output was written to the script folder and I overlooked it. I modified the code to include an output directory selection. Here is the working code. import os from tkinter.filedialog import askopenfilename from tkinter import * from tkinter.filedialog import askopenfilename root = Tk() filename = askopenfilename(title="Please slect a file") #Select input file path = filedialog.askdirectory(initialdir=os.getcwd(), title="Please select a folder:") #Select output directory root.destroy() #Close the dialog box filename_n = 0 done = False with open (filename) as in_file: while not done: with open(os.path.join(path,f"out{filename_n}.dat"), "w") as out_file: while not done: try: line = next(in_file).strip() except StopIteration: done = True break if "EOD" in line: break else: out_file.write(line + '\n') filename_n += 1

http://stackoverflow.com/comment/91303212
type: QuestionComment
type: Comment
has text: @berkelem Thanks for your comment. However, I already thought of the filepath problem, and the `os.listdir() ` returns the files in the path including the one of my interest. Actually, I also tried to access the file through the `Atom` editor, but it's not accessible from there either.
comment on: http://stackoverflow.com/q/52142443
score: 0

http://stackoverflow.com/a/53072307
has body: I have the same error, my provisional solution is to import inside on_connect method. import paho.mqtt.client as mqtt from .tasks import * def on_connect(client, userdata, flags, rc): from .models import Room print("Connecting to CloudMQTT broker: "+ mqtt.connack_string(rc)) room_mqtt = [(room.get_mqtt_topic(), 1) for room in Room.objects.all()] client.subscribe(room_mqtt) client = mqtt.Client() client.on_connect = on_connect
type: Answer
answers question: http://stackoverflow.com/q/52165489
score: 5
upvote count: 5
downvote count: 0

http://stackoverflow.com/a/52182611
answers question: http://stackoverflow.com/q/52181613
upvote count: 1
has body: The reason for the syntax error is that the minus sign is an illegal character in a package or module name. Typically packages will use underscores in the actual package names, or have a nested structure, as in this case: import google.cloud.bigquery as bq
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/52270868
linked to: http://stackoverflow.com/q/15138614
has answer: http://stackoverflow.com/a/52271045
tagged with: url
has title: Reading URL does not show its contents
accepted answer: http://stackoverflow.com/a/52271132
possible better answer: http://stackoverflow.com/a/52271045
has answer: http://stackoverflow.com/a/52271070
tagged with: http://stackoverflow.com/tag/html
tagged with: python
answer count: 4
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/52270926
type: Question
linked to: http://stackoverflow.com/q/49939123
has answer: http://stackoverflow.com/a/52271132
linked to: http://stackoverflow.com/q/8049520
has body: I'm trying to read a URL exactly as has been suggested here. However, I don't get the same contents in the output as what I see on the site itself. myfile = f.read() link = "http://www.primatiming.com/#/participant/11/40/37380" f = urllib.request.urlopen(link) myfile = f.read() print(myfile) b' \n \n \n \n primatiming \n \n\n \n \n \n \n \n \n \n' I was wondering if someone could suggest any ways of reading this page? The reason for doing this is that I simply want to download the tables in the site from multiple pages within the primetiming url so that I could do some data analysis on them. Thank you.
duplicate of: http://stackoverflow.com/q/49939123

http://stackoverflow.com/a/52137943
answers question: http://stackoverflow.com/q/52137832
has comment: http://stackoverflow.com/comment/91225765
type: Answer
upvote count: 1
score: 1
has body: you can directly iterate it using for loop. import numpy as np a = np.array([[11, 12, 13, 14], [15, 16, 17, 18], [19, 20, 21, 22]]) b = list() for i in range(a.shape[0]): b.append(a[i].reshape(2,2)) for itr in b: print(b[i])
has comment: http://stackoverflow.com/comment/91225986
downvote count: 0

http://stackoverflow.com/q/52227707
tagged with: tuples
has body: I got a Tuple out of range on my battleships program. The reason I got confused is I'm not using a tuple, unless I'm wrong and I'm willing to be corrected. Tuples are not mutable and the dictionary this is referring to has items added to it upon starting the program. I am a beginner so if I have made a stupid mistake please don't judge! from random import randint #empty list to generate the board. board = [] messages = { "win" : "Nooo you won!", "lose" : "Not my ship haha", "out" : "Oops, that's not even in the ocean.", "repeat" : "You guessed that one already" } ships = { 'shiprows' : [0] 'shipcols' : [0] } #generate board and append to board[] As of now it is a 10*10 grid. for x in range(0, 10): board.append(["O"] * 10) #prints the board every turn. def print_board(board): for row in board: print(" ".join(row)) print_board(board) #computer chooses where to put battleships' rows def random_row1(board): return randint(0, len(board) - 1) def random_col1(board): return randint(0, len(board) - 1) #calling above two functions and storing their values for 5 ships. #creating variables for 5 ships. vars = 0 for vars in range(0, 5): print(vars) if len(ships.keys()) &gt;= 4: while ships["shiprow{}".format(vars - 2)] == ships["shiprow{}".format(vars - 1)] and ships["shipcol{}".format(vars - 2)] == ships["shipcol{}".format(vars - 1)]: ships["shiprow{}".format(vars)] = random_row1(board) ships["shipcol{}".format(vars)] = random_col1(board) ships["shiprow{}".format(vars)] = random_row1(board) ships["shipcol{}".format(vars)] = random_col1(board) else: ships["shiprow{}".format(vars)] = random_row1(board) ships["shipcol{}".format(vars)] = random_col1(board) #program itself turn = 0 #enforces four turns before game over. Will possibly extend to unlimited with multiple ships. print(ships) for turn in range(20): turn = turn + 1 print ("Turn {}".format(turn)) print ("Ships Left: {}".format(int(len(ships.keys()) / 2))) guess_row = int(input("Guess Row: ")) guess_col = int(input("Guess C…
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52229531
type: Question
has comment: http://stackoverflow.com/comment/91404907
has title: Python 3 - Tuple out of range error. But I'm using a dictionary?
has comment: http://stackoverflow.com/comment/91404971
accepted answer: http://stackoverflow.com/a/52227824
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/52227824
favorite count: 0
possible better answer: http://stackoverflow.com/a/52229531

http://stackoverflow.com/comment/104007944
has text: `TypeError: parser_f() got an unexpected keyword argument 'a_filter'`
type: AnswerComment
type: Comment
score: 2
comment on: http://stackoverflow.com/a/52135531

http://stackoverflow.com/comment/91432162
comment on: http://stackoverflow.com/q/52241827
score: 0
type: Comment
has text: But the code creates a new column in the dataframe whose name is based on another column.
type: QuestionComment

timeit
tag name: timeit
type: Tag
tags question: http://stackoverflow.com/q/52144105

http://stackoverflow.com/q/52169712
has answer: http://stackoverflow.com/a/52169902
type: Question
has title: Getting quantity of issues through github.api
tagged with: github-api
answer count: 2
tagged with: python
has body: My task is to get the number of open issues using github.api. Unfortunately, when I parsing any repositories, I get the same number - 30. import requests r = requests.get('https://api.github.com/repos/grpc/grpc/issues') count = 0 for item in r.json(): if item['state'] == 'open': count += 1 print(count) Is there any way to get a real quantity of issues?
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52169886
score: 0
type: UnansweredQuestion

http://stackoverflow.com/a/62788608
has comment: http://stackoverflow.com/comment/111035724
score: 0
answers question: http://stackoverflow.com/q/52235799
type: Answer
has body: import subprocess with open("mac.txt","rw") as f: # mac.txt is the text file with mac address for line in f.readlines(): print (line) print ("************") process=subprocess.Popen(['macsearch', line],stdout=subprocess.PIPE) out=process.communicate() """ using process.communicate to save the output.""" for o in out: print o print ('\n')

http://stackoverflow.com/a/52167774
upvote count: 3
type: Answer
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/52163305
accepted answer of: http://stackoverflow.com/q/52163305
type: AcceptedAnswer
has body: You have 2 errors: on_btn_clicked is a method of the class so it must have as the first parameter the instance, that is, self. the connection is with the name of the function without evaluating, in your case the slot on_action_clicked you are evaluating it, so you are getting it printed at the beginning, for it there are 2 possible solutions: use partial or use a lambda function. self.btn = self.window.findChild(QPushButton, 'pushButton') self.btn.clicked.connect(self.on_btn_clicked) self.action_save = self.window.findChild(QAction, 'action_save_state') self.action_save.triggered.connect(partial(self.on_action_clicked, 'action clicked')) # self.action_save.triggered.connect(lambda: self.on_action_clicked('action clicked')) # use lambda function self.window.show() def on_action_clicked(self, txt): print(txt) def on_btn_clicked(self): print('button clicked')

http://stackoverflow.com/comment/100362547
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52121069
type: QuestionComment
has text: I ended up with kivy

http://stackoverflow.com/q/52222929
possible better answer: http://stackoverflow.com/a/52223033
tagged with: pandas
has answer: http://stackoverflow.com/a/52223033
has title: How to select a table based on its header from an Excel spreadsheet that contains multiple tables?
tagged with: python
has comment: http://stackoverflow.com/comment/91394789
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91396074
has comment: http://stackoverflow.com/comment/91396597
type: Question
has body: I am trying to interact with a spreadsheet and I have imported it using: InitialImportedData = pd.read_excel(WorkbookLocation, SheetName) The problem is that the spreadsheet I am importing from contains multiple tables, and I only want to use one of them. Is there a way to remove all the rows and columns before a specific value? The table I am looking for has a header Premium. how do I get the table I want as a dataframe rather than all of them with loads of NaN's scattered in my frame? Is there a way to locate a string in a dataframe and slice it based on that? It is the only one labelled Premium. edit I was able to find the location of the start of my table using: I solved this in a different way, perhaps useful for people who want to slice up dataframes that they didn't read in through excel. for x in range (InitialImportedData.shape[1]): try : list(InitialImportedData.iloc[:,x]).index('Premium') print list(InitialImportedData.iloc[:,x]).index('Premium'),x except: pass By converting to a list I was able to look where the value sat. I have not worked out how to slice my data correctly at the end. I can use: InitialImportedData.iloc[20:,4:] to create a dataset which Starts in the corner I need (it happens to be at 20,4) but I have not found a way to slice the end of the table so it doesn't bring in extra information from the worksheet. I have included an example dataset below: Unnamed: 0 Unnamed: 1 Unnamed: 2 Unnamed: 3 Unnamed: 4 \ 0 NaN Table 1 NaN NaN NaN 1 NaN Header1 Header2 NaN NaN 2 NaN 9.88496 2.29552 NaN NaN 3 NaN 7.36861 2.6275 NaN NaN 4 NaN 5.34938 8.37391 NaN NaN 5 NaN 8.77608 3.70626 NaN NaN 6 NaN 7.37828 2.62692 NaN NaN 7 NaN 6.82297 9.59347 NaN NaN 8 NaN 7.6804 7.38528 NaN NaN 9 NaN 2.07633 3.76247 NaN NaN 10 NaN NaN NaN NaN NaN 11 NaN NaN NaN NaN NaN 12 NaN NaN NaN NaN NaN 13 NaN NaN NaN NaN NaN 14 NaN NaN NaN NaN NaN 15 NaN NaN NaN NaN NaN 16 NaN NaN NaN NaN NaN 17 NaN NaN NaN NaN NaN 18 NaN NaN NaN NaN NaN 19 NaN NaN Premium NaN NaN 20 NaN NaN Fin…
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91395436
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52223222
accepted answer: http://stackoverflow.com/a/52223222

http://stackoverflow.com/comment/93194979
comment on: http://stackoverflow.com/a/53141558
type: Comment
has text: Thanks. I will try and let you know
score: 1
type: AnswerComment

http://stackoverflow.com/a/52169380
has comment: http://stackoverflow.com/comment/91366329
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91366062
type: Answer
has body: It may be that your www-data user does not have access to port 51712 (or whichever port Choregraphe's virtual nao is using - it may change between sessions, have you checked that?). Maybe you can try running telnet 127.0.0.1 51712 from your PHP code - if that doesn't work, qimessaging won't be able to connect to that port either.
accepted answer of: http://stackoverflow.com/q/52157381
has comment: http://stackoverflow.com/comment/91336981
answers question: http://stackoverflow.com/q/52157381

http://stackoverflow.com/q/52246659
has body: Context: I am creating a tkinter project that includes face recognition. Because import face_recognition, cv2takes a long time, to make it more convenient, this has been placed in a thread (I know tkinter doesn't like threads but they are very useful). E.g. import tkinter def thread_import (): global face_recognition, cv2 import face_recognition, cv2 if __name__ == '__main__': threading.Thread (target = thread_import).start () My question is that is there a way to lower the impact of the import. Due to the thread hogging CPU time, my tkinter window can behave unresponsively. I don't mind if it takes slightly longer but I don't really want to go into all the library files to add time.sleep (x). Many thanks in advance.
has comment: http://stackoverflow.com/comment/91441649
has comment: http://stackoverflow.com/comment/91441601
tagged with: import
has comment: http://stackoverflow.com/comment/91441637
type: Question
has answer: http://stackoverflow.com/a/52264110
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91441665
type: UnansweredQuestion
tagged with: cpu-time
tagged with: python
has comment: http://stackoverflow.com/comment/91470091
has title: Python reduce import CPU impact

http://stackoverflow.com/comment/91291840
type: Comment
comment on: http://stackoverflow.com/a/52151123
type: AnswerComment
has text: Thank you for your answer, It's very helpful. However, I have found some problem when I tried your method. Some of my item2 disappear Ex. I have 5 row I want to return all 5 row of my similarity but when my result returns only 2 row. I'm not sure why but I guest may groupby function. How can I change my method? I would like to return every row of my similarity.
score: 0

http://stackoverflow.com/q/52232476
score: 0
tagged with: selenium
tagged with: web-scraping
answer count: 1
type: UnansweredQuestion
has title: Selenium Web driver is not able to find the div class in Google Chrome webstore
tagged with: google-chrome-extension
has body: I want to crawl some data from Google Chrome Website. But I am facing a problem whenever trying to use selenium webdriver. When I use following code I get an error stating that this element doesn't exist in the site. button = driver.find_element_by_class_name("a-d-l-L") Snapshot of the website: And also, how to get data from a pop up window (this window comes up when I press a button). Following screen can be found on the next page. I want to store the data that is showing in the pop up message.
type: Question
tagged with: python
tagged with: selenium-chromedriver
has answer: http://stackoverflow.com/a/56343239

http://stackoverflow.com/comment/91213803
has text: @MitchelPaulin I've successfully programmed the aforementioned problems and was progressing smoothly until I got stuck at this one
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52131390
type: QuestionComment

http://stackoverflow.com/comment/91427197
score: 2
has text: "all hours in row=4 should be considered overtime" -- Are you sure this is what you want to do? It sounds like you are double-counting overtime. e.g. for emp1, the overtime sums to 10 hours, which is correct whether it is examined on a weekly basis (50 - 40 = 10) or a daily basis (10 - 8 = 2, for each of 5 days).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52239093

http://stackoverflow.com/q/52152125
tagged with: stomp
answer count: 1
has title: How to read messages from Activemq queues using python and STOMP
score: 0
tagged with: python
has body: I access queues(activemq) using the link http://10.41.248.10:8161/admin/queues.jsp. I wanted to read the message from the queue name:Notificationqueue. I wanted to use python and STOMP. The username and password to the queue is admin/admin. Please help me step by step to get the message from queue name:Notificationqueue. Below is my code, please help to complete the code #!/usr/bin/env python import time import sys import stomp class MyListener(object): def on_error(self, headers, message): print 'received an error %s' % message def on_message(self, headers, message): print 'received a message %s' % message conn = stomp.Connection(host_and_ports=[('10.41.248.10', 61616)]) conn.set_listener('', MyListener()) conn.start() conn.connect("admin","admin",wait=True) conn.subscribe(destination='queue://Notificationqueue', id = '1', ack='auto') time.sleep(2) conn.disconnect() When I run this, I get the error, No handlers could be found for logger "stomp.py" conn.connect("admin","admin", wait=True) File "C:\Python27\lib\site-packages\stomp\connect.py", line 164, in connect Protocol11.connect(self, *args, **kwargs) File "C:\Python27\lib\site-packages\stomp\protocol.py", line 340, in connect self.transport.wait_for_connection() File "C:\Python27\lib\site-packages\stomp\transport.py", line 327, in wait_for_connection raise exception.ConnectFailedException() ConnectFailedException . Please help in completing this code at the earliest. Do ask me if you need more information
type: UnansweredQuestion
tagged with: activemq-classic
has answer: http://stackoverflow.com/a/54717038
type: Question

http://stackoverflow.com/q/52134716
accepted answer: http://stackoverflow.com/a/52134837
favorite count: 0
has comment: http://stackoverflow.com/comment/91219657
possible better answer: http://stackoverflow.com/a/52134853
has answer: http://stackoverflow.com/a/52134853
tagged with: python
type: AnsweredQuestion
score: 2
type: Question
answer count: 2
has body: everybody. I am currently working to merge the csv files. For example, you have files from filename1 to filename100. I used the following code to combine 100 files and the following error occurred: I'll put the code up first. import csv fout=open("aossut.csv","a") # first file: for line in open("filename1.csv"): fout.write(line) # now the rest: for num in range(2,101): f = open("filename"+str(num)+".csv") f.next() # skip the header for line in f: fout.write(line) f.close() # not really needed fout.close() And the following error occurred when the above file was executed: File "C:/Users/Jangsu/AppData/Local/Programs/Python/Python36-32/tal.py", line 10, in &lt;module&gt; f.next() # skip the header AttributeError: '_io.TextIOWrapper' object has no attribute 'next' I've been working on it for a few days, and I don't know what to do.
upvote count: 3
has title: AttributeError: '_io.TextIOWrapper' object has no attribute 'next'?
tagged with: http://stackoverflow.com/tag/csv
downvote count: 1
has answer: http://stackoverflow.com/a/52134837

http://stackoverflow.com/comment/91449272
comment on: http://stackoverflow.com/q/52250029
type: Comment
type: QuestionComment
has text: Does it mean that I have to pass `X_scaler = preprocessing.StandardScaler()` in between the train and the model, save it somehow in TF in the session?
score: 0

http://stackoverflow.com/a/52220427
type: Answer
has body: I assume you mean you have a literal string like \xe4\xb8\x89 and you want to convert this into the character 三. It's very strange that there isn't a straightforward way to do this. The best i can come up with is: s = '\\xe4\\xb8\\x89' print(bytes.fromhex(s.replace('\\x', '')).decode('utf-8')) # prints 三
score: 0
answers question: http://stackoverflow.com/q/52219324

http://stackoverflow.com/comment/91251826
has text: `from folder2.file3 import getNumbers()` is invalid syntax: you should use `from folder2.file3 import getNumbers`. By the way, if you run your program from the `root` folder then the import in `file2.py` works fine: I know this is not what you asked, but you might want to consider structuring your program that way if you can (it makes your program more modular/better encapsulated).
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52150763
score: 1

http://stackoverflow.com/a/52143676
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52143318
has body: I don't fully understand but, the efficient-est way (at least i think is): if any(i in x for i in {'a', 'b', 'c']): print ("a" or "b" or "c") But to get it do: if any(i in x for i in {'a', 'b', 'c'}): print ([i for i in {'a', 'b', 'c'} if i in x])

http://stackoverflow.com/comment/91339013
score: 0
comment on: http://stackoverflow.com/a/52194686
type: Comment
has text: You should probably copy-paste the recipe there. Not that it's likely to disappear from the docs any time soon, but still. Also, the OP is using 2.7, so better to link the 2.x docs. But otherwise, yeah, hard to beat this.
type: AnswerComment

http://stackoverflow.com/comment/91447074
type: QuestionComment
has text: @MoRe, you can use the second image as original for testing. the original (image.jpg) is a 25x25 size from the second one
score: 0
comment on: http://stackoverflow.com/q/52249114
type: Comment

http://stackoverflow.com/q/52171593
has answer: http://stackoverflow.com/a/52172848
tagged with: pip
tagged with: python
tagged with: pipenv
type: AnsweredQuestion
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/52171756
has answer: http://stackoverflow.com/a/58582592
has answer: http://stackoverflow.com/a/75990476
tagged with: virtualenv
has title: How to install dependencies from a copied pipfile inside a virtual environment?
upvote count: 82
accepted answer: http://stackoverflow.com/a/52172848
answer count: 7
score: 81
has answer: http://stackoverflow.com/a/65907152
favorite count: 0
has answer: http://stackoverflow.com/a/78937911
has answer: http://stackoverflow.com/a/52171756
has body: The problem originates when I start by cloning a git project that uses pipenv, so it has a Pipfile + Pipfile.lock. I want to use a virtual environment with the project so I run pipenv shell. I now have a virtual environment created and I am inside the virtual environment. The project obviously has a lot of dependencies (listed in the Pipfile). I don't want to have to go through the list in the Pipfile one by one and install them using pipenv install &lt;package_name&gt;. Is there a pipenv/pip command that installs all the packages from a Pipfile I already have? Or maybe I need to set up the environment differently than running pipenv shell?
has answer: http://stackoverflow.com/a/64510892

http://stackoverflow.com/q/52160520
has comment: http://stackoverflow.com/comment/91270648
possible better answer: http://stackoverflow.com/a/52160588
type: AnsweredQuestion
score: 1
has title: Sentence Splitting in Python and making it an Ordered Dict
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52160619
has body: I want to split my text and store it to make an ordered dict For example: 1.This is my text. 2.This is 2nd Text. I want to split the numbers and text and store it in a ordered dict like Ordered Dict "1":"This is my text" "2":"This is 2nd text" I tried . split but it didn't work for me. How to do this? d = OrderedDict() text_data = [ "1.This is my text.","2.This is 2nd text"] for i, f in enumerate(text_data): id = f.split('.') d[id] = text_data[i] print(i, " :: ", id, " =&gt;\n", d[id], "\n" + "*" * 100 + "\n") Where am I going wrong? To make an OrderedDict
has answer: http://stackoverflow.com/a/52160588
has answer: http://stackoverflow.com/a/52160619
has answer: http://stackoverflow.com/a/52160941
answer count: 3
downvote count: 0
favorite count: 0
tagged with: python

http://stackoverflow.com/a/52251399
accepted answer of: http://stackoverflow.com/q/52251298
answers question: http://stackoverflow.com/q/52251298
type: AcceptedAnswer
score: 1
type: Answer
upvote count: 1
has body: you need a comma to make args a tuple, like this: mythread= threading.Thread( target=my_function name="thread1", args=("This is one variable from main",)) This is because threading.Thread() expects args to be some iterable and enumerates it to get all args to pass to your function. The expression ("string") is equal to just "string" - and it IS an iterable, resulting in ("s", "t", "r", "i", "n", "g"). Not what you wanted. To tell Python that ("string") is a one-element tuple and not a parenthesized expression, do ("string",).
downvote count: 0

http://stackoverflow.com/comment/91301615
has text: those are all required signatures. That is not the problem here.
score: 0
comment on: http://stackoverflow.com/q/52175326
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91397502
comment on: http://stackoverflow.com/a/52214736
has text: Glad it helped. Now that you're getting into the more powerful Django ORM features, it's time for you to read the docs on `.distinct()` and plan to do a lot of edge case testing. Thar be dragons
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91432605
type: Comment
has text: I have python 3.6.4 and OpenCV 3.4.1 and it works. Can you share your code? `tracker = cv2.TrackerKCF_create()`
comment on: http://stackoverflow.com/q/52232165
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91387044
comment on: http://stackoverflow.com/q/52219190
has text: Unfortunately I can't, it is confidential. I have created this to provide an example.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91212517
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52127514
has text: what did that error say?

http://stackoverflow.com/q/52247465
duplicate of: http://stackoverflow.com/q/1680528
favorite count: 0
type: Question
tagged with: python
has title: Why is 'is' returning true for a different instance in Python
has body: This is a python beginner question: class MyClass: variable = "test" def function(self): print("test") X = MyClass() Y = MyClass() print (X.variable == Y.variable) // expected true, works print (X.variable is Y.variable) // expected false, but return true; why? Since there are two instances of the class, why is the second test with 'is' returning true since the variables should be difference instances?
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52247511
linked to: http://stackoverflow.com/q/68645
linked to: http://stackoverflow.com/q/1680528
has comment: http://stackoverflow.com/comment/91442890
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52247502
type: UnansweredQuestion

http://stackoverflow.com/comment/91285792
has text: Why not try to use ```exclude``` param in your ```Meta``` class, pass it a tuple of not required fields.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52167706
score: 0

http://stackoverflow.com/a/52240807
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/91517181
type: Answer
has body: Briefly, you want to iterate through the file line by line and parse the values with open('data.bin') as f: for line in f: parts = line.split() # split the line on whitespace if parts[0] == 'mlon': # whatever variable you want to process a = int(parts[1]) # convert next two params from strings to integers b = int(parts[2]) desc = ' '.join(parts[2:]) # join the rest back together as the description print(a, b, desc)
downvote count: 1
answers question: http://stackoverflow.com/q/52240763

http://stackoverflow.com/comment/91247474
score: 0
type: AnswerComment
has text: agha man chanta soal az deploy kardane django daram . mituni hal koni vasam ?
comment on: http://stackoverflow.com/a/52147420
type: Comment

http://stackoverflow.com/comment/91429862
score: 0
comment on: http://stackoverflow.com/q/52239990
type: Comment
type: QuestionComment
has text: *Provided answer does not help at all. It just shows the same things that I've been trying* but you haven't really shown us what you've tried, you've just tossed out a few lines of code that won't compile (indentation matters). Your question has been closed because based on the few details shared it is similar enough that the scope of the problem (combining strings from a sequence/list) is addressed by the other answer.

http://stackoverflow.com/q/52260690
has answer: http://stackoverflow.com/a/52387876
type: Question
tagged with: screenshot
score: 0
tagged with: selenium
tagged with: web-scraping
answer count: 1
has title: Taking screenshots from part of the web page with python and selenium
has comment: http://stackoverflow.com/comment/91469162
has comment: http://stackoverflow.com/comment/91470358
accepted answer: http://stackoverflow.com/a/52387876
has comment: http://stackoverflow.com/comment/91470621
has body: I have been able to catch screenshots as pngs of some elements such the one with following code from selenium import webdriver from PIL import Image from io import BytesIO from os.path import expanduser from time import sleep # Define url and driver url = 'https://www.formula1.com/' driver = webdriver.Chrome('chromedriver') # Go to url, scroll down to right point on page and find correct element driver.get(url) driver.execute_script('window.scrollTo(0, 4100)') sleep(4) # Wait a little for page to load element = driver.find_element_by_class_name('race-list') location = element.location size = element.size png = driver.get_screenshot_as_png() driver.quit() # Store image as bytes, crop it and save to desktop im = Image.open(BytesIO(png)) im = im.crop((200, 150, 700, 725)) path = expanduser('~/Desktop/') im.save(path + 'F1-info.png') This outputs to: Which is what I want but not exactly how I want. I needed to manually input some scrolling down and as I couldn't get the element I wanted (class='race step-1 step-2 step-3') I had to manually crop the image too. Any better solutions?
type: AnsweredQuestion
tagged with: python

http://stackoverflow.com/comment/91232021
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52141100
has text: Also you are mentioning 4 lists that you do not use, and then make refernce to variables called `list1` and so without showing their definition. Are you not missing sth out there?
type: Comment

http://stackoverflow.com/comment/91459228
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/52256001
has text: `map` creates a new iterable, which you put in `Final_Outcome_in_int`. You even named it correctly. No reason to expect `pab` to change type.
type: Comment

http://stackoverflow.com/comment/91254790
score: 0
type: Comment
has text: `. virtualenvwrapper.sh` works because bash searches the source file in the `$PATH` (exactly like `which`). And I recommend lazy loading: `source virtualenvwrapper_lazy.sh`, it's much faster.
comment on: http://stackoverflow.com/a/52147420
type: AnswerComment

http://stackoverflow.com/comment/91486765
has text: It's improper way to handle hidden elements. User won't modify HTML DOM manually via dev-tools to make element visible.
type: Comment
comment on: http://stackoverflow.com/a/52269518
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91261646
score: 0
type: AnswerComment
has text: probably a vague question, but I have another similar DataFrame with similar type of data in the rows. When I do the same thing on this DataFrame, I get a KeyError on the column names. Any idea why that's the case? I can give a small sample of the dataset if it is possible somehow.
type: Comment
comment on: http://stackoverflow.com/a/52132728

http://stackoverflow.com/a/52164314
has body: Files are iterators over their lines, so you can just use next(f) to get the first line AND move the iterator pointer to the second one. Then (in the with block) you can pass the opened file f to numpy.loadtxt(), so it only starts reading from the second line: import numpy as np fname = 'bla.txt' with open(fname) as f: first = next(f) a, b, c, d = [float(x) for x in first.split()] myarray = np.loadtxt(f) # no skiprows here
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52164047
type: Answer
answers question: http://stackoverflow.com/q/52164047

http://stackoverflow.com/q/52263594
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/91475089
score: 1
upvote count: 1
has body: Is there a regex that can take this string: "This is [D&gt;aa &lt;D] a [A&gt;bb &lt;A] test [D&gt;ccc cc &lt;D]." and return this: "This is a [A&gt;bb &lt;A] test." So essentially deletes everything that starts with [D&gt; and ends with &lt;D]. This can't be straight forward because these pairs pop up multiple times, so using the regex [[D&gt;].*[&lt;D]] returns: "This is ."
type: Question
has answer: http://stackoverflow.com/a/52263667
has title: Regex to delete between pairs of strings, but not delete everything when multiple pairs
has comment: http://stackoverflow.com/comment/91475102
answer count: 3
has comment: http://stackoverflow.com/comment/91475087
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52264334
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52263665
has comment: http://stackoverflow.com/comment/91475063

http://stackoverflow.com/q/52263492
possible better answer: http://stackoverflow.com/a/52263605
has answer: http://stackoverflow.com/a/52263514
answer count: 3
has body: from django.contrib import admin from django.urls import path import main.views urlpatterns = [ path('', main.views.index, name="index"), path('story/', main.views.story, name="story"), path('haxs/', main.views.haxs, name="haxs"), path('contact/', main.views.contact, name="contact"), path('admin/', admin.site.urls), ] . home our story haxs contact us I am working on a python django website and my urls are not working properly. I have included my urls.py and the nav links which are the same on each page. From home I can go to all the other pages and from the other pages I can go back to home. My problem is when I go from for example: haxs to contact it does not work and the code url becomes "http://127.0.0.1:8000/haxs/story/" when it should just be "http://127.0.0.1:8000/story/" . It is like that with our story/haxs/contact, I can not go between them pages. How do I fix this?
favorite count: 0
has title: Python Django urls not working how they should?
tagged with: python
accepted answer: http://stackoverflow.com/a/52263514
has answer: http://stackoverflow.com/a/68541073
upvote count: 2
score: 1
tagged with: django
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52263605
type: AnsweredQuestion
tagged with: django-urls

http://stackoverflow.com/comment/91236667
has text: How does that faraway `e` is produced? Will calling `str(e)` under Python3 always work and calling `unicode(e)` under Python 2 also works? If that's the case I just force `str = unicode` under a Python 2 environment and forget about it. If that exception is produced through certain heuristics on the running Python environment, that may get tricky because that's premature optimization on the library's part.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52143333
score: 0

http://stackoverflow.com/q/52119981
tagged with: pygame
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has body: I am using Python 3.6.5 on win32 and I want to find the center of my sprite to position it on the x axis exactly how I want it to be. I there any way to do this? Extra information: pip version 18.0, Computer Dell Inspiron 15, 3000 Series. I loaded the sprite using the pygame.image.load() function.
tagged with: image
has title: How to find sprite center in pygame python
type: Question
has comment: http://stackoverflow.com/comment/91191120
downvote count: 0
tagged with: python-3.6
favorite count: 0
has answer: http://stackoverflow.com/a/52154046
answer count: 1

http://stackoverflow.com/a/52224622
has body: try this (indentation may be broken): driver.find_element_by_partial_link_text('Next').click() #sleep(15)# you can use explicit wait time as below WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//td[@style='font-weight:bold;']//parent::tr")) rows = driver.find_elements_by_xpath("//td[@style='font-weight:bold;']//parent::tr")) for i in rows: text= i.text print text
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52223302

http://stackoverflow.com/a/52185636
downvote count: 0
score: 7
has body: resample by month considers last day of month irrespective of column dates. df2 = df_daily.resample('M').agg({'Open':'first', 'High':'max', 'Low': 'min', 'Close':'last'}) Output: Open High Low Close Date 2010-01-31 55.15 60.3 45.6 51.70 2010-02-28 51.80 54.1 50.5 51.95 You can change the index to last day present in the column: df2 = df_daily.resample('M').agg({'Open':'first', 'High':'max', 'Low': 'min', 'Close':'last'}) idx = df_daily.reset_index().groupby(df_daily.index.to_period('M'))['Date'].idxmax() df2.index = df_daily.iloc[idx].index print(df2) Output: Open High Low Close Date 2010-01-29 55.15 60.3 45.6 51.70 2010-02-03 51.80 54.1 50.5 51.95 If you only want to groupby year and month use: df3 = df_daily.groupby([df_daily.index.year,df_daily.index.month]).agg({'Open':'first', 'High':'max', 'Low': 'min', 'Close':'last'}) df3.index.names= ['Year', 'Month'] print(df3) Output: Open High Low Close Year Month 2010 1 55.15 60.3 45.6 51.70 2 51.80 54.1 50.5 51.95
upvote count: 7
answers question: http://stackoverflow.com/q/52184181
has comment: http://stackoverflow.com/comment/91324676
type: Answer

http://stackoverflow.com/q/52195269
has answer: http://stackoverflow.com/a/52195377
tagged with: python-2.7
answer count: 3
tagged with: pandas
upvote count: 1
has title: Key error "Date not in index" only when adding Date to index
favorite count: 0
has comment: http://stackoverflow.com/comment/91343589
has body: This one is baffling given how simple the code is, and yet it's giving the same error on separate Linux and OSX boxes. If df.set_index('Date', inplace=True) is run, then plot(x='Date') returns KeyError: "['Date'] not in index" -- But if df.set_index() is commented out, the error goes away. import pandas as pd import matplotlib.pyplot as plot df = pd.read_csv('historical_price_data.csv') # Seemingly makes no difference either way. df.columns = ['Date', 'Close'] df['Date'] = pd.to_datetime(df.Date, infer_datetime_format=True) # Uncommenting this line results in error (below) when plot(x='Date') is called. df.set_index('Date', inplace=True) # Seemingly makes no difference. # df.sort_index(inplace=True) # If set_index('Date') above, then plot(x='Date') returns KeyError: "['Date'] not in index" df'Date', 'Close'.plot(x='Date') plot.show() This is the data set I'm using: Date,Close 2018-08-29,7059.7 2018-08-28,7071.01 2018-08-27,6911.9 2018-08-26,6709.98 2018-08-25,6737.52 2018-08-24,6690.88 2018-08-23,6526.36 2018-08-22,6359.99 2018-08-21,6475.9 2018-08-20,6258.74
tagged with: python
has comment: http://stackoverflow.com/comment/91341859
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has answer: http://stackoverflow.com/a/52195336
possible better answer: http://stackoverflow.com/a/52195377
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/52195336
has answer: http://stackoverflow.com/a/52195410

http://stackoverflow.com/comment/91273554
score: 0
has text: Exactly how big is your CSV file? I just asking because sometimes the first bottleneck is the way you load your dataset.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52161437

http://stackoverflow.com/a/52217310
has comment: http://stackoverflow.com/comment/91514163
has body: Considering that many of your distance calculations will give zero weight after the exponential, you can probably drop a lot of your distances. Doing big chunks of distance calculations while dropping distances which are greater than a threshhold is usually faster with KDTree: import numpy as np from scipy.spatial import cKDTree # so we can get a `coo_matrix` output def gaussgrid(coords, sigma = 1, n = 64, side = 100, eps = None): x_ = np.linspace(-side/2,side/2,n) x,y,z = np.meshgrid(x_,x_,x_,indexing='ij') xyz = np.column_stack((x.ravel(),y.ravel(),z.ravel())) if eps is None: eps = np.finfo('float64').eps thr = -np.log(eps) * 2 * sigma**2 data_tree = cKDTree(coords) discr = 1000 # you can tweak this to get best results on your system values = np.empty(n**3) for i in range(n**3//discr + 1): slc = slice(i * discr, i * discr + discr) grid_tree = cKDTree(xyz[slc]) dists = grid_tree.sparse_distance_matrix(data_tree, thr, output_type = 'coo_matrix') dists.data = 1./np.sqrt(2*np.pi*sigma**2) * np.exp(-dists.data/(2*sigma**2)) values[slc] = dists.sum(1).squeeze() return values.reshape(n,n,n) Now, even if you keep eps = None it'll be a bit faster as you're still returning about 10% your distances, but with eps = 1e-6 or so, you should get a big speedup. On my system: %timeit out = sumofgauss(coords, xyz, 1.0) 1 loop, best of 3: 23.7 s per loop %timeit out = gaussgrid(coords) 1 loop, best of 3: 2.12 s per loop %timeit out = gaussgrid(coords, eps = 1e-6) 1 loop, best of 3: 382 ms per loop
type: Answer
has comment: http://stackoverflow.com/comment/91406833
score: 2
has comment: http://stackoverflow.com/comment/91406048
upvote count: 2
answers question: http://stackoverflow.com/q/52208434
accepted answer of: http://stackoverflow.com/q/52208434
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52116904
upvote count: 2
answers question: http://stackoverflow.com/q/52116817
has body: Since you're calling next on the decorated function, presumably you can only decorate a function if it's a generator or if it returns an iterator. numberParser does not contain a yield statement, and it doesn't return anything, so it doesn't meet those requirements. You should modify numberParser so it yields something, or so it returns an iterator.
has comment: http://stackoverflow.com/comment/91190200
has comment: http://stackoverflow.com/comment/91188476
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/q/52174460
score: 3
has answer: http://stackoverflow.com/a/52174487
has title: Python - Create a list of sets or set of sets?
has comment: http://stackoverflow.com/comment/91471145
has answer: http://stackoverflow.com/a/52174514
downvote count: 0
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/91299840
has answer: http://stackoverflow.com/a/52174515
favorite count: 0
has body: Need help with a homework exercise for a class I am auditing. The exercise is in association rule mining and I'm extremely stuck at one of the steps to organize the data. I have a string of data separated by line break (each line represents the items purchased by a customer): rawText = """fruit, bread, butter, soup fruit, yogurt, coffee whole milk, cream cheese, meat, vegetables""" How can I get this data into a set that looks like this (is this a list of sets?): [{‘fruit’, ‘bread’, ‘butter’, soup’}, {‘fruit’, ‘yogurt’, ‘coffee’}, {'whole milk', 'cream cheese', 'meat', 'vegetables'} ] I've tried to break the string by end of line: names_list = [y for y in (x.strip() for x in rawText.splitlines()) if y] my_set = set() for i in names_list: my_set.add(i) This obviously is not working. Perhaps I'm going about this the wrong way?
upvote count: 3
type: UnansweredQuestion
type: Question

http://stackoverflow.com/comment/91225750
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52138067
has text: please post the admin classes.
score: 0

performance
tags question: http://stackoverflow.com/q/52239271
tags question: http://stackoverflow.com/q/52119785
tags question: http://stackoverflow.com/q/52207136
tags question: http://stackoverflow.com/q/52146911
tags question: http://stackoverflow.com/q/52165652
tags question: http://stackoverflow.com/q/52242832
tags question: http://stackoverflow.com/q/52194820
tags question: http://stackoverflow.com/q/52221218
tags question: http://stackoverflow.com/q/52224945
tags question: http://stackoverflow.com/q/52141785
tags question: http://stackoverflow.com/q/52260212
tags question: http://stackoverflow.com/q/52133042
tags question: http://stackoverflow.com/q/52235742
tags question: http://stackoverflow.com/q/52141149
tags question: http://stackoverflow.com/q/52180678
tags question: http://stackoverflow.com/q/52142645
tag name: performance
tags question: http://stackoverflow.com/q/52119037
tags question: http://stackoverflow.com/q/52229863
tags question: http://stackoverflow.com/q/52234656
type: Tag
tags question: http://stackoverflow.com/q/52127854
tags question: http://stackoverflow.com/q/52267652
tags question: http://stackoverflow.com/q/52262686
tags question: http://stackoverflow.com/q/52225908

http://stackoverflow.com/a/52127982
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52127886
has comment: http://stackoverflow.com/comment/91206355
has comment: http://stackoverflow.com/comment/91206336
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52127886
has body: If you want to pass sound and difficulty to the mainLoop of SpaceInvaders, then make it so that mainLoop takes them as arguments, and then you will be able to send them: SpaceInvaders.SpaceInvaders().mainLoop(sound, difficulty) To answer the additional question "That's the issue, I don't want them in main loop, I want them in the SpaceInvaders class :(" - do this: SpaceInvaders.SpaceInvaders(sound, difficulty).mainLoop()

http://stackoverflow.com/comment/91410796
type: QuestionComment
has text: Why the `-1`? Tell us about the variables - arrays, shape, dtype, etc. I don't like to play guessing games.
score: 1
comment on: http://stackoverflow.com/q/52230570
type: Comment

http://stackoverflow.com/comment/91222049
type: QuestionComment
has text: please fix your indentation
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52136160

django-rest-auth
tag name: django-rest-auth
tags question: http://stackoverflow.com/q/52196220
type: Tag
tags question: http://stackoverflow.com/q/52114052
tags question: http://stackoverflow.com/q/52244141

http://stackoverflow.com/comment/91468814
type: Comment
has text: You are missing `'` for `NBA'`. change it to `df_check = ['MLB', 'NBA']` .
type: QuestionComment
comment on: http://stackoverflow.com/q/52260609
score: 0

http://stackoverflow.com/comment/91428834
type: AnswerComment
comment on: http://stackoverflow.com/a/52211381
score: 0
type: Comment
has text: I've managed to get my goals in the meanwhile, but thank you anyways!

http://stackoverflow.com/q/52130716
tagged with: scipy
answer count: 1
has body: Please forgive my noob-ish question, but I am a little confused as to why this warning occurs and what I can do to remedy it. I tried replacing df['Air Temp'] with df[tuple('Air Temp')] but it only raised more errors. CODE: import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("./data/elnino.csv") df.columns = [col.strip() for col in df.columns] df['Air Temp'] = pd.to_numeric(df['Air Temp'], errors = 'coerce') df['Sea Surface Temp'] = pd.to_numeric(df['Sea Surface Temp'], errors = 'coerce') ERROR: stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result. return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
type: UnansweredQuestion
tagged with: pandas
score: 3
downvote count: 0
favorite count: 0
has title: How to fix deprecation warning for using non-tuple sequence for multidimensional indexing
type: Question
has answer: http://stackoverflow.com/a/61966681
tagged with: python
has comment: http://stackoverflow.com/comment/91212376
upvote count: 3
has comment: http://stackoverflow.com/comment/91212420
has comment: http://stackoverflow.com/comment/91212483

http://stackoverflow.com/q/52135891
has comment: http://stackoverflow.com/comment/91228254
has comment: http://stackoverflow.com/comment/91221615
downvote count: 1
type: Question
has title: What is the need of ellipsis[...] while modifying array values in numpy?
has body: import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) for x in np.nditer(a, op_flags = ['readwrite']): x[...] = 2*x print 'Modified array is:' print a In the above code, why can't we simply write x=2*x instead of x[...]=2*x?
has comment: http://stackoverflow.com/comment/91265592
has answer: http://stackoverflow.com/a/52136068
accepted answer: http://stackoverflow.com/a/52136068
tagged with: numpy
tagged with: numpy-ndarray
has comment: http://stackoverflow.com/comment/91224161
has comment: http://stackoverflow.com/comment/91221633
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/91221654
linked to: http://stackoverflow.com/q/42190783

http://stackoverflow.com/comment/91447833
type: Comment
comment on: http://stackoverflow.com/a/52244459
score: 1
type: AnswerComment
has text: Thank you for your answer! Efficient and elegant way!

http://stackoverflow.com/comment/91457252
comment on: http://stackoverflow.com/q/52254886
has text: yes, such as 20130101 occurs 2 times ,so in column 'E' number is 2.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91510220
has text: @eyllanesc I hook up a lot of things to mousePressEvent. Right click menus, the left click for selection, that changes the color of the background of the selected node to white, and using the built in the setText rather than having to make a label and set it explicitly. I don't have any experience using QML, but you mean you can achieve the desired result just using overriding QWidgets.QWidget?
comment on: http://stackoverflow.com/q/52266968
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52176488
has comment: http://stackoverflow.com/comment/91303393
downvote count: 0
answers question: http://stackoverflow.com/q/52176478
has comment: http://stackoverflow.com/comment/91303340
upvote count: 2
has comment: http://stackoverflow.com/comment/91303399
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52176478
score: 2
has body: Option 1 Use map with set_index df2.columns = df2.columns.map(df1.set_index('french').english) print(df2) Option 2 Use rename with set_index: df2.rename(columns=df1.set_index('french').english.to_dict()) Both produce: an def sdsd 0 2 4 6 Order of the columns doesn't matter: df1 = pd.DataFrame({'french': ['un', 'deux', 'trois'], 'english': ['one', 'two', 'three']}) df2 = pd.DataFrame([[1,2,3]], columns=['trois', 'deux', 'un']) df2.rename(columns=df1.set_index('french').english.to_dict()) three two one 0 1 2 3 df2.columns.map(df1.set_index('french').english) # Index(['three', 'two', 'one'], dtype='object')

http://stackoverflow.com/q/52183201
has comment: http://stackoverflow.com/comment/91316274
downvote count: 1
has body: I'm trying to encode this: "LIAISONS Ã NEW YORK" to this: "LIAISONS à NEW YORK" The output of print(ascii(value)) is 'LIAISONS \xc3 NEW YORK' I tried encoding in cp1252 first and decoding after to utf8 but I get this: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 9: invalid continuation byte I also tried to encode in Latin-1/ISO-8859-2 but that is not working too. How can I do this?
type: Question
tagged with: encoding
has comment: http://stackoverflow.com/comment/91316259
has answer: http://stackoverflow.com/a/52183381
accepted answer: http://stackoverflow.com/a/52183381
has comment: http://stackoverflow.com/comment/91316315
score: 0
has title: Can't decode an improperly encoded string with Ã character
has comment: http://stackoverflow.com/comment/91316223
answer count: 1
tagged with: utf-8
favorite count: 0
tagged with: python
tagged with: mojibake
type: AnsweredQuestion
upvote count: 1

http://stackoverflow.com/comment/91457416
type: QuestionComment
comment on: http://stackoverflow.com/q/52254618
type: Comment
score: 0
has text: Hi @VivekKumar this code to access the steps from the pipeline in-order to get the features but I am not sure if this is the accurate way to do it

http://stackoverflow.com/a/52157004
type: Answer
score: -1
downvote count: 1
answers question: http://stackoverflow.com/q/52156868
has comment: http://stackoverflow.com/comment/91304388
upvote count: 0
has body: The best format for passing string parameters in Python is to use the format string method. You could do something like this: line_command = "imapsync --host1 {fromHost} --user1 {emails} --password1 '\"{passwords}\"' --host2 {toHost} --user2 {emails} --password2 '\"{passwords}\"' --ssl1 --no-modulesversion --ssl2".format(fromHost=fromHost, emails=emails, passwords=passwords, toHost=toHost) os.system(line_command)

http://stackoverflow.com/comment/91328850
type: Comment
type: QuestionComment
has text: It just worked, thanks a lot!
comment on: http://stackoverflow.com/q/52153594
score: 0

http://stackoverflow.com/a/52263302
has body: global is a "code smell": something that indicates undesirable code design. In this case, you're merely trying to create a resource for all instances of a class. The preferred tactic is a class attribute: lift the variable up one level, and all instances will share that single variable: class VariableScope(): _variableScope = '' def __init__(self, scope): self._scope = scope def __enter__(self): VariableScope._variableScope += self._scope x = VariableScope('mytest') x.__enter__() print(VariableScope._variableScope) y = VariableScope('add-to-scope') y.__enter__() print(VariableScope._variableScope) Output: mytest mytestadd-to-scope
accepted answer of: http://stackoverflow.com/q/52263110
upvote count: 3
answers question: http://stackoverflow.com/q/52263110
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91475155
downvote count: 0
score: 3

http://stackoverflow.com/q/52157261
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91264833
has body: I'm just curious how I would go about updating the image opened with the Zoom function WITHOUT calling the Zoom function again. Also if you know of any easier way to do what I'm doing, which is simply just trying to make a image "Zoom-able" with mouse wheel, then my ears are open lol. Any other comments on the code are appreciated, Thank You! Specifically this part right here: pictureVar = StringVar() pictureVar.set("a.png") Zoom(root, path=pictureVar.get()) pictureVar.set("b.png") The picture then gets opened using Image.open() here: class Zoom(Frame): ''' Simple zoom with mouse wheel ''' def __init__(self, mainframe, path): ''' Initialize the main Frame ''' Frame.__init__(self, master=mainframe) # Vertical and horizontal scrollbars for canvas vbar = AutoScrollbar(self.master, orient='vertical') hbar = AutoScrollbar(self.master, orient='horizontal') vbar.grid(row=0, column=1, sticky='ns') hbar.grid(row=1, column=0, sticky='we') # Open image self.image = Image.open(path) #&lt;------------------------!!!!!!!!!!! Here is the entire code though: import csv import os from tkinter import * from PIL import ImageTk, Image root = Tk() class AutoScrollbar(Scrollbar): ''' A scrollbar that hides itself if it's not needed. Works only if you use the grid geometry manager ''' def set(self, lo, hi): if float(lo) &lt;= 0.0 and float(hi) &gt;= 1.0: self.grid_remove() else: self.grid() Scrollbar.set(self, lo, hi) class Zoom(Frame): ''' Simple zoom with mouse wheel ''' def __init__(self, mainframe, path): ''' Initialize the main Frame ''' Frame.__init__(self, master=mainframe) # Vertical and horizontal scrollbars for canvas vbar = AutoScrollbar(self.master, orient='vertical') hbar = AutoScrollbar(self.master, orient='horizontal') vbar.grid(row=0, column=1, sticky='ns') hbar.grid(row=1, column=0, sticky='we') # Open image self.image = Image.open(path) # Create canvas and put image on it self.canvas = Canvas(self.master, highlightthickness=0, xscrollcommand=hbar.set, yscrollcommand=vbar…
type: Question
has comment: http://stackoverflow.com/comment/91264989
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/91264887
has title: How to update what image you open with image.open()
has comment: http://stackoverflow.com/comment/91265230
score: 0
tagged with: python-3.x
tagged with: python
tagged with: tkinter

http://stackoverflow.com/q/52216412
answer count: 1
has body: I am calling a imageServer and getting an x-genericbytedata-octet-stream in response. So i was wondering if i can convert it into some format which is manageable like ndarray. This is what i am getting in response ÿ Ç÷®£®¥Xøan Ð5£ï~KTþ$¹M«_ ü³þœÿ ˆk¡çÆHyAÏbG§ø A«÷g~ŒieÞÁn¦=Ÿüú i.¿†ö@µ2lí~¤ŸðjLóÉ&amp;,X.ó¿:ÿ õ¿*ìüTvèšƒzXÌñÓ\Â•Ÿû[X’iÌƒì€€0wOóÀ®ŸÆm·Ãú‘ÿ §?¡¬ª|f‘Øñx^àÁW\móVà„³Éä˜Óý’3úÔ­pë¬P2€2pGõö?Z’êàÛDÊ=­jÈ¶¤3ÝÝÜb”vägõ¯wÑß z‹8óøŠðy®¤U8³ÄIüÇå^ù§åt]0cìq?à³«Ð¸QñÔkVØ·fàú±ÿ I want to convert it into an ndarray so that I could use it in opencv. Thanks
tagged with: python
accepted answer: http://stackoverflow.com/a/52226389
type: AnsweredQuestion
type: Question
tagged with: opencv
tagged with: image
tagged with: numpy
score: 0
has answer: http://stackoverflow.com/a/52226389
has title: How do I convert the x-genericbytedata-octet-stream to some format which is readable/manageable

http://stackoverflow.com/comment/91180173
comment on: http://stackoverflow.com/q/52112788
type: QuestionComment
has text: Extract the date column and you can index into that too with I and j
score: 0
type: Comment

http://stackoverflow.com/comment/91191283
comment on: http://stackoverflow.com/q/52115532
has text: Thanks @rici, I was trying to make the question more clear. Won't change again. :-)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91228046
comment on: http://stackoverflow.com/a/52139043
has text: Yes, I mentioned in the question that I was after UserCode.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/52244500
score: 0
answers question: http://stackoverflow.com/q/52243467
has comment: http://stackoverflow.com/comment/91448012
has comment: http://stackoverflow.com/comment/91448110
has body: You have typo in the gaussian function which is not the same as the sample you mentioned. But it is not necessary to said as 'wrong', as it just affect the standard deviation value. Instead of np.exp(-np.power((x-dk)/sigma,2.) / 2.), it should be np.exp(-np.power((x-dk),2.) /( sigma / 2.)) Edit: And sigma should be 10^-3 to reproduce the sample provided. But right now I just use 10^-2, as small deviation make things a bit too sensitive. Sigma will be so small such that the gaussian function will be so sensitive to the sampling size. But fixing this won't give you the desired result, you will notice under 1000, the middle bar is still a bit lower. Why? First, you need to notice: Gaussian function is not for generating step function in primary purpose. Lets take a look for a more detail example about sampling, it is a bit related to statistic. N = 100 for i in range(50): y += 6*gaussian(x, i, np.power(10.,-3.)) What happens to this graph? Why there is a drop at the middle? The reason is that gaussian function is an approximation of probability. Lets say human being is wiped out by a new flu. Only 100 people survive, ok, now we choose 50 people out and check how many people is infected (1 of them is inflected). So what is the probability of choosing 50 people out of 50 people and how sure we call tell there is one group have someone inflected? Ans: 1, for sure you chose all 50 some of them must be inflected So what is the probability of choosing 25 people out of 50 people and how sure we call tell there is one group have someone inflected? Ans: 1/ nCr(50,25) ~= 0 By the way, this time the gaussian function is not a good approximation as for low sampling size. (Due to central limit theorem, wiki) N = 10000 I reduce some sampling point to save time, so for i in range(0, 10000, 100): y += 6*gaussian(x, i, np.power(10.,-3.)) That's the same, for choosing few thousand from few ten thousand it is still hard to tell the difference. For 100 sample, the probability difference o…
type: Answer
has comment: http://stackoverflow.com/comment/91442065

http://stackoverflow.com/a/52269274
has body: Initialize your model based on your parameters first. kmeans = KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=600,n_clusters=unique_cuisines, n_init=10, n_jobs=1, precompute_distances='auto',random_state=None, tol=0.0001, verbose=0) Once the model is initialized then you can try to fit the data. kmeans.fit(X_scaled)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52267654

http://stackoverflow.com/comment/91236963
type: QuestionComment
type: Comment
has text: what is `mean` and `std` you are using?
score: 0
comment on: http://stackoverflow.com/q/52120880

http://stackoverflow.com/q/52162165
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52162363
has body: I am trying to read the string representation of a nested list and convert it to a nested list in python. I have tried the following: l=input("enter nested list") result=eval(l) with input [[1],[2]] and result is the string I just entered so that if I print(l[0]) the result is '['. Any assistance would be appreciated.
score: 0
answer count: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91273840
has answer: http://stackoverflow.com/a/52162296
tagged with: python
has comment: http://stackoverflow.com/comment/91274092
accepted answer: http://stackoverflow.com/a/52162296
has comment: http://stackoverflow.com/comment/91273828
has comment: http://stackoverflow.com/comment/91274113
has title: python convert string representation of nested list of integers to nested list of integers
has answer: http://stackoverflow.com/a/52162363

http://stackoverflow.com/a/52203907
has body: OK. Python 2.7, Win 10. Your original file is plain ASCII, containing the exact unicode escapes ("\u####", 6 bytes, and "\U########", 10 bytes). Read the file and decode using 'unicode-escape': then you have a Python unicode string; let's call it your_unicode_string. To write a file, choose either: output_encoding = 'utf-8' or output_encoding = 'utf-16-le' and then: import codecs with codecs.open(output_filename, 'w', encoding=output_encoding) as fpo: # fpo.write(u'\ufeff') # for windows, you might want to write this at the start fpo.write(your_unicode_string) For your given python and os version and without any tampering, you won't be able to just print to the console and see emojis.
answers question: http://stackoverflow.com/q/52202924
type: Answer
has comment: http://stackoverflow.com/comment/91357213
has comment: http://stackoverflow.com/comment/91393444
score: 0
has comment: http://stackoverflow.com/comment/91357840

http://stackoverflow.com/comment/91339818
type: Comment
comment on: http://stackoverflow.com/a/52190008
score: 0
type: AnswerComment
has text: Perhaps give some comments on what you're doing to help the OP?

http://stackoverflow.com/q/52250710
type: UnansweredQuestion
score: 0
has answer: http://stackoverflow.com/a/52250907
has body: My dataframe is taken from a Excel file which formats their dates as e.g Jan 2018. I want to change to datetime such as 01-2018 or even as a string like 01/2018. I have two problems: When attempting to convert to datetime I have an out of bound error (nanosecond) twoyear_df['Date'] = twoyear_df['Date'].apply(lambda x: pd.to_datetime(x).strftime('%m/%Y')) When I try to convert them into strings with this: twoyear_df['Date'] = pd.to_datetime(twoyear_df['Date'], format='%m%Y') I get an ValueError: time data 'Sep 18' does not match format '%m%Y' (match) What should do? It seems like I am unable to change to datetime because of of the nanosecond problem and I am unable to change it to a string because I cannot change it datetime? I'm not sure how to provide a dataset as an example. I'll put a sample here Date Price Open High Low Change % 0 Sep 18 2.707 2.637 2.711 2.629 2.95% 1 Aug 18 2.629 2.669 2.686 2.587 -1.68% 2 Jul 18 2.674 2.524 2.690 2.508 5.61% 3 Jun 18 2.532 2.431 2.602 2.427 3.94% 4 May 18 2.436 2.492 2.598 2.299 -2.25% 5 Apr 18 2.492 2.278 2.508 2.234 9.78% 6 Mar 18 2.270 2.254 2.366 2.197 0.53% 7 Feb 18 2.258 2.157 2.286 1.947 5.07% 8 Jan 18 2.149 1.907 2.165 1.891 13.88% 9 Dec 17 1.887 1.790 1.927 1.746 5.42% I avoid use NaT as I need to do some time series analysis. I have a feeling that all the dates saved by excel has a nanosecond problem. Is there a way to bypass or just remove it entirely?
type: Question
tagged with: dataframe
answer count: 1
tagged with: pandas
tagged with: datetime
tagged with: python
has title: How do I covert an Excel Date in MMM-YYYY to datetime or strings?

http://stackoverflow.com/q/52188133
answer count: 4
score: -1
has comment: http://stackoverflow.com/comment/91325944
has answer: http://stackoverflow.com/a/52188202
downvote count: 1
has comment: http://stackoverflow.com/comment/91326003
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/91328545
has comment: http://stackoverflow.com/comment/91326049
has body: def SRM(stringToReverse): if len(stringToReverse) == 0 or stringToReverse==None : return return stringToReverse[len(stringToReverse) - 1] + SRM(stringToReverse[:len(stringToReverse) - 1] #print(temp, end='')enter code here SRM("MY NAME IS KHAN")
has comment: http://stackoverflow.com/comment/91326441
has comment: http://stackoverflow.com/comment/91328942
has comment: http://stackoverflow.com/comment/91325971
has answer: http://stackoverflow.com/a/52189337
has answer: http://stackoverflow.com/a/52221253
favorite count: 0
has comment: http://stackoverflow.com/comment/91325970
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91326043
tagged with: python
has answer: http://stackoverflow.com/a/52188210
has title: Python stringTypeError: must be str, not NoneType

http://stackoverflow.com/comment/92312937
has text: I am facing a similar problem. I am using Google Storage. I set up a function to be triggered when a file is uploaded to a bucket. I uploaded 5719 files and 5551 were processed. Logs show "connection "reset by peer" error. Could you figure out how to go about it? If so please share.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52129628

http://stackoverflow.com/q/52167220
has comment: http://stackoverflow.com/comment/91293471
has title: Run a code in python 2 in jupyter notebook in python 3
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91284692
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/91284869
has body: My jupyter notebook is runing python 3 and need to run a code writen in python 2. I remember that is possible in python 2 to make a call from the future and run a codenin python 3. Is it possible to do the reverse?
tagged with: python-2.7

http://stackoverflow.com/comment/91426161
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](//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.
comment on: http://stackoverflow.com/a/52238312

http://stackoverflow.com/comment/91398588
type: Comment
type: QuestionComment
has text: So is this really a question about grouping in SQLite?
comment on: http://stackoverflow.com/q/52224458
score: 0

http://stackoverflow.com/q/52176178
upvote count: 7
accepted answer: http://stackoverflow.com/a/54508548
type: Question
has comment: http://stackoverflow.com/comment/91302841
has body: I'm using Pytorch to classify a series of images. The NN is defined as follows: model = models.vgg16(pretrained=True) model.cuda() for param in model.parameters(): param.requires_grad = False classifier = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(25088, 4096)), ('relu', nn.ReLU()), ('fc2', nn.Linear(4096, 102)), ('output', nn.LogSoftmax(dim=1)) ])) model.classifier = classifier The criterions and optimizers are as follows: criterion = nn.NLLLoss() optimizer = optim.Adam(model.classifier.parameters(), lr=0.001) My validation function is as follows: def validation(model, testloader, criterion): test_loss = 0 accuracy = 0 for images, labels in testloader: images.resize_(images.shape[0], 784) output = model.forward(images) test_loss += criterion(output, labels).item() ps = torch.exp(output) equality = (labels.data == ps.max(dim=1)[1]) accuracy += equality.type(torch.FloatTensor).mean() return test_loss, accuracy This is the piece of code that is throwing the following error: RuntimeError: input has less dimensions than expected epochs = 3 print_every = 40 steps = 0 running_loss = 0 testloader = dataloaders['test'] # change to cuda model.to('cuda') for e in range(epochs): running_loss = 0 for ii, (inputs, labels) in enumerate(dataloaders['train']): steps += 1 inputs, labels = inputs.to('cuda'), labels.to('cuda') optimizer.zero_grad() # Forward and backward passes outputs = model.forward(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() if steps % print_every == 0: model.eval() with torch.no_grad(): test_loss, accuracy = validation(model, testloader, criterion) print("Epoch: {}/{}.. ".format(e+1, epochs), "Training Loss: {:.3f}.. ".format(running_loss/print_every), "Test Loss: {:.3f}.. ".format(test_loss/len(testloader)), "Test Accuracy: {:.3f}".format(accuracy/len(testloader))) running_loss = 0 Any help?
possible better answer: http://stackoverflow.com/a/64838681
has answer: http://stackoverflow.com/a/64838681
has answer: http://stackoverflow.com/a/52178638
answer count: 3
downvote count: 0
favorite count: 0
has title: Pytorch model accuracy test
has comment: http://stackoverflow.com/comment/91303870
tagged with: python
has answer: http://stackoverflow.com/a/54508548
type: AnsweredQuestion
tagged with: conv-neural-network
tagged with: pytorch
score: 7

http://stackoverflow.com/comment/91400310
type: Comment
comment on: http://stackoverflow.com/q/52225399
score: 0
type: QuestionComment
has text: @roganjosh I did not think It was a duplicate since they are doing something slightly different, and I don't know how to apply their answer to my problem.

http://stackoverflow.com/q/52150393
type: UnansweredQuestion
has title: How to access all variables in all databases from PLC (without specifying the name of database or variable)?
tagged with: python
has comment: http://stackoverflow.com/comment/91250944
tagged with: opc-ua
upvote count: 0
tagged with: plc
has answer: http://stackoverflow.com/a/52161872
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91250889
has comment: http://stackoverflow.com/comment/91250793
score: -2
has body: In the plc database i have a database named "status" which has a variable named "Temperature". Since I know the names, I access the value of this variable like this: from opcua import Client client = Client("url") client.connect() temperature = client.get_node("ns=3;s=\"status\".\"Temperature\"").get_value() Now how can I get this information without knowledge of database or variable name? I want a general code that takes everything from a given PLC url.
downvote count: 2
has comment: http://stackoverflow.com/comment/91251125
favorite count: 0
has answer: http://stackoverflow.com/a/52150931

http://stackoverflow.com/comment/91194000
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52121310
has text: Is the table that you want actually in the HTML, or is it generated by JavaScript code after the page is loaded? If the latter, then you can't scrape it this way; you either need to interpret the JS, drive a browser with something like Selenium, or read the JS code to figure out what APIs it's calling and call them directly from Python.
score: 0

http://stackoverflow.com/a/52137704
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52136632
has body: Solution new_tuples = [] for i in range(0, 5): for j in range(1, 16): new_tuples.append((i, j)) for i in new_tuples: print(i) Output (xenial)vash@localhost:~/python$ python3 text_seg.py (0, 1) (0, 2) (0, 3) (0, 4) (0, 5) (0, 6) (0, 7) (0, 8) (0, 9) (0, 10) (0, 11) (0, 12) (0, 13) (0, 14) (0, 15) (1, 1) Comments Would this approach satisfy your needs? You could interchange the numbers as desired but this, will allow you to have a list with the tuples store and be able to call them to print.

http://stackoverflow.com/comment/91500921
comment on: http://stackoverflow.com/a/52268095
has text: Thanks @Scott Boston, I didn't understand the use of df = df.set_index(0) g = df[1].lt(-22).mul(1).diff().bfill().ne(0).cumsum()
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91327622
comment on: http://stackoverflow.com/q/52188012
has text: Exactly. That is my point.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/52261223
type: Answer
answers question: http://stackoverflow.com/q/52246350
has body: One simple way would be to key (E1, E2) and (E3, E4) with the same key e.g PCollection then use CoGroupByKey.
score: 0

http://stackoverflow.com/a/52189216
has body: Some caveats first : in your data bins are ranges, in your algorithm they are numbers. You must redefine bins for that. Furthermore, min(bins[i]*h1[i], bins[i]*h2[i]) is bins[i]*min(h1[i], h2[i]), so the result can be obtained by : hists=pandas.read_clipboard(index_col=0) # your data bins=arange(-4,112,9) # try for bins but edges are different here mins=hists.min('rows') intersection=dot(mins,bins)
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52184242
upvote count: 1

http://stackoverflow.com/a/52186815
has body: If criteria is 1 or 0, or even True or False You can use mean groupby df.groupby('Grade').mean() Criteria Grade 0 1.000000 1 0.000000 2 0.666667 5 1.000000 set_index and mean df.set_index('Grade').mean(level=0) Criteria Grade 0 1.000000 1 0.000000 2 0.666667 5 1.000000 In the case that 'Criteria' are 'yes' and 'no' strings df Grade Criteria 0 0 yes 1 1 no 2 2 yes 3 2 no 4 5 yes 5 2 yes You can group the boolean evaluation df.Criteria.eq('yes').groupby(df.Grade).mean() Grade 0 1.000000 1 0.000000 2 0.666667 5 1.000000 Name: Criteria, dtype: float64 Use reset_index on any of these answers to get the desired dataframe
downvote count: 0
has comment: http://stackoverflow.com/comment/91329168
answers question: http://stackoverflow.com/q/52186250
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/comment/91220081
score: 0
comment on: http://stackoverflow.com/a/52135026
has text: I have accepted it as the answer, but sadly I do not have the required reputation for my upvote to be public :( may I ask why the additional conditions are necessary? Say if I reach a child node, wouldn’t the self.root if condition insert Node(val) there?
type: AnswerComment
type: Comment

tensorflow
tags question: http://stackoverflow.com/q/52218137
tags question: http://stackoverflow.com/q/52132450
tags question: http://stackoverflow.com/q/52172859
tags question: http://stackoverflow.com/q/52159239
tags question: http://stackoverflow.com/q/52180645
tags question: http://stackoverflow.com/q/52270892
tags question: http://stackoverflow.com/q/52223106
tags question: http://stackoverflow.com/q/52201565
tags question: http://stackoverflow.com/q/52112771
tags question: http://stackoverflow.com/q/52151673
tags question: http://stackoverflow.com/q/52159789
tags question: http://stackoverflow.com/q/52223816
tags question: http://stackoverflow.com/q/52235203
tags question: http://stackoverflow.com/q/52185422
tags question: http://stackoverflow.com/q/52190877
tags question: http://stackoverflow.com/q/52221144
tags question: http://stackoverflow.com/q/52241632
tags question: http://stackoverflow.com/q/52147236
tags question: http://stackoverflow.com/q/52205988
tags question: http://stackoverflow.com/q/52124792
tags question: http://stackoverflow.com/q/52199843
tags question: http://stackoverflow.com/q/52192148
tags question: http://stackoverflow.com/q/52166911
tags question: http://stackoverflow.com/q/52176353
tags question: http://stackoverflow.com/q/52136663
tags question: http://stackoverflow.com/q/52187453
tags question: http://stackoverflow.com/q/52182910
tags question: http://stackoverflow.com/q/52268879
tags question: http://stackoverflow.com/q/52220242
tags question: http://stackoverflow.com/q/52197351
tags question: http://stackoverflow.com/q/52197023
tags question: http://stackoverflow.com/q/52234780
tags question: http://stackoverflow.com/q/52115748
tags question: http://stackoverflow.com/q/52155331
tags question: http://stackoverflow.com/q/52141951
tags question: http://stackoverflow.com/q/52267673
tags question: http://stackoverflow.com/q/52177500
tags question: http://stackoverflow.com/q/52126895
tags question: http://stackoverflow.com/q/52150008
tags question: http://stackoverflow.com/q/52204265
tags question: http://stackoverflow.com/q/52202432
tags question: http://stackoverflow.com/q/52172956
tags question: http://stackoverflow.com/q/52119997
tags question: http://stackoverflow.com/q/52205351
tags question: http://stackoverflow.com/q/52171918
tags question: http://stackoverflow.com/q/52158448
tags question: http://stackoverflow.com/q/52257509
tags question: http://stackoverflow.com/q/52117648
tags question: http://stackoverflow.com/q/52196940
tags question: http://stackoverflow.com/q/52174530
tags question: http://stackoverflow.com/q/52213776
tags question: http://stackoverflow.com/q/52162402
tags question: http://stackoverflow.com/q/52248293
tags question: http://stackoverflow.com/q/52215711
tags question: http://stackoverflow.com/q/52170485
tags question: http://stackoverflow.com/q/52162522
tags question: http://stackoverflow.com/q/52189567
tags question: http://stackoverflow.com/q/52144159
tags question: http://stackoverflow.com/q/52144763
tags question: http://stackoverflow.com/q/52142035
tags question: http://stackoverflow.com/q/52144642
tags question: http://stackoverflow.com/q/52180502
tags question: http://stackoverflow.com/q/52263689
tags question: http://stackoverflow.com/q/52172171
tags question: http://stackoverflow.com/q/52158528
tags question: http://stackoverflow.com/q/52121536
tags question: http://stackoverflow.com/q/52121347
tags question: http://stackoverflow.com/q/52168051
tags question: http://stackoverflow.com/q/52180377
tags question: http://stackoverflow.com/q/52245721
tags question: http://stackoverflow.com/q/52200075
tags question: http://stackoverflow.com/q/52262226
tags question: http://stackoverflow.com/q/52227551
tags question: http://stackoverflow.com/q/52116245
tags question: http://stackoverflow.com/q/52126579
tags question: http://stackoverflow.com/q/52142671
tag name: tensorflow
tags question: http://stackoverflow.com/q/52201644
tags question: http://stackoverflow.com/q/52226691
tags question: http://stackoverflow.com/q/52199832

http://stackoverflow.com/a/52133694
downvote count: 0
answers question: http://stackoverflow.com/q/52133551
has body: If you need to use multiple versions of Python, or run different sets of packages in the Python environment, you should probably just use Anaconda to create them, for example: conda create -n py36 python=3.6 anaconda then you can just switch between them using activate &lt;your-environment-name&gt;
upvote count: 3
has comment: http://stackoverflow.com/comment/91218630
type: Answer
has comment: http://stackoverflow.com/comment/91229715
score: 3

http://stackoverflow.com/a/52219798
has body: It can be useful to you. Assign datetime index, apply groupby function over year and calculate mean :-) Groupby index Considered sample DataFrame TP MENU SLY CZA Time 2016-01-31 1.01 -0.33 -0.60 0.0 2016-01-30 0.32 0.06 0.16 0.0 2017-01-29 -1.19 -0.10 0.34 0.0 2017-01-28 -0.31 0.62 -0.20 0.0 2017-01-27 0.39 0.03 -0.43 0.0 2017-01-26 1.21 -0.54 -0.21 0.0 2018-07-25 -0.39 0.67 -0.11 0.0 2018-07-24 -0.27 0.00 0.11 0.0 Code snippet df.index = pd.to_datetime(df.index) df.groupby([df.index.year]).mean() Output Annualised mean TP MENU SLY CZA 2016 0.665 -0.1350 -0.220 0.0 2017 0.025 0.0025 -0.125 0.0 2018 -0.330 0.3350 0.000 0.0
has comment: http://stackoverflow.com/comment/91393964
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91394897
accepted answer of: http://stackoverflow.com/q/52219396
answers question: http://stackoverflow.com/q/52219396
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91393890

http://stackoverflow.com/comment/91463366
score: 0
comment on: http://stackoverflow.com/a/52258063
type: AnswerComment
has text: Sorry, but I do not need the full difference between the two datetime objects, but the number of hours between the two objects per day.
type: Comment

http://stackoverflow.com/comment/91408991
has text: Thank you roganjosh. I think this question showcases why self-answering is fine. I was facing a problem that I hadn't found an answer to, then I came up with an answer and I wanted to share it with others. And then I got 2 more answers that are 3x and 5x faster than my original solution. This is the power of StackOverflow :) @Yuca
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52226719
type: AnswerComment

http://stackoverflow.com/q/52119387
has comment: http://stackoverflow.com/comment/91189798
answer count: 1
has body: How to parse python json object? Currently i'm getting this value from another json file, it is a variable "Id6087b9b5b5" But what if i don't know the object string but i want to fetch "_number" in a loop? try.py for sub_dict in y[ChangeID]: #ChangeID is a variable print (ChangeID) MERGENUM = (entry['_number']) print (MERGENUM ) data.json { "Id6087b9b5b5": [ { "status": "NEW", "_number": 35328 } ], "Id6087b9b345": [ { "status": "NEW", "_number": 35348 } ], "Id6087b9b555": [ { "status": "NEW", "_number": 35310 } ], "Id6087b9b5b4": [ { "status": "NEW", "_number": 35308 } ] } output as a variable 35328 35348 35310 35308
has answer: http://stackoverflow.com/a/52119504
has comment: http://stackoverflow.com/comment/91189763
has comment: http://stackoverflow.com/comment/91189800
favorite count: 0
tagged with: python
has title: python json object parsing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91189891
accepted answer: http://stackoverflow.com/a/52119504
score: 0
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91189675
type: Question
tagged with: object

http://stackoverflow.com/comment/91230684
comment on: http://stackoverflow.com/q/52140023
has text: so there is a list of posts but at the very top of the list are just old posts everytime I submit a new post it's always at the bottom, I'm trying to make it where the new post goes on top instead of the bottom
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52120479
linked to: http://stackoverflow.com/q/3167494
tagged with: python
has comment: http://stackoverflow.com/comment/91192285
has comment: http://stackoverflow.com/comment/91192294
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91192184
has comment: http://stackoverflow.com/comment/91193289
has comment: http://stackoverflow.com/comment/91193727
has title: Python after sending a file to a remote client the file finishes writing a lot longer
has comment: http://stackoverflow.com/comment/91193763
has body: s is a standard tcp socket,this is the server: s = socket.socket() s.connect(("127.0.0.1", 5203)) with open("example.txt" "wb+") as f: exqwrt = f.read(1024) while (exqwrt): s.send(exqwrt) exqwrt = f.read(1024) code on client is, s is a standard tcp socket as well: s = socket.socket() s.bind(("127.0.0.1", 5203)) s.listen(5) conn, addr = s.accept() openedFile = open("examplet.txt", "wb+") while True: exwqrt = conn.recv(1024) openedFile.write(exqwrt) if not exqwrt: break The problem is that file gets sent pretty fast.But it is written on examplet.txt pretty slowly in like 5 minutes.
has comment: http://stackoverflow.com/comment/91192062
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91192418
has comment: http://stackoverflow.com/comment/91192364
answer count: 0
type: UnansweredQuestion
tagged with: sockets

http://stackoverflow.com/q/52124799
tagged with: scipy
tagged with: numpy
has title: Extended Raftery Markov Chain function minimization using python
has comment: http://stackoverflow.com/comment/91200628
type: UnansweredQuestion
tagged with: markov-chains
has comment: http://stackoverflow.com/comment/91200667
answer count: 1
downvote count: 0
has body: I am working on extended Raftery's model which is a more general higher-order Markov chain model, in that I need to solve the following Linear Programming model with certain constraints. Following is the (link) Linear Programming function that needs to be minimized: subject to : Where vectors "W" and "λ" are to be solved in the equation. Q and X are i-step transition probability matrix and steady-state probabilities respectively. Below is the sample I am working with: import numpy as np one_step_array = np.array([[0.12, 0.75, 0.12], [0.42, 0.14, 0.42], [0.75, 0.25, 0.0]]) two_step_array = np.array([[0.43, 0.23, 0.33], [0.43, 0.44, 0.11], [0.20, 0.59, 0.20]]) steady_state = np.array([0.38, 0.39, 0.21]) Q_Arr = np.vstack((np.matmul(one_step_array,steady_state),np.matmul(two_step_array,steady_state))).transpose() from pulp import * w1 = LpVariable("w1",0,None) w2 = LpVariable("w2",0,None) w3 = LpVariable("W3",0, None) L1 = LpVariable("L1",0,None) L2 = LpVariable("L2",0,None) prob = LpProblem("Problem",LpMinimize) prob += w1 &gt;= steady_state[0] - Q_Arr[0][0]*L1 - Q_Arr[0][1]*L2 prob += w1 &gt;= -steady_state[0] + Q_Arr[0][0]*L1 + Q_Arr[0][1]*L2 prob += w2 &gt;= steady_state[1] - Q_Arr[1][0]*L1 - Q_Arr[1][1]*L2 prob += w2 &gt;= -steady_state[1] + Q_Arr[1][0]*L1 + Q_Arr[1][1]*L2 prob += w3 &gt;= steady_state[2] - Q_Arr[2][0]*L1 - Q_Arr[2][1]*L2 prob += w3 &gt;= -steady_state[2] + Q_Arr[2][0]*L1 + Q_Arr[2][1]*L2 prob += w1 &gt;= 0 prob += w2 &gt;= 0 prob += w3 &gt;= 0 prob += L1 &gt;= 0 prob += L2 &gt;= 0 prob += L1 + L2 == 1 prob += w1+w2+w3 status = prob.solve(GLPK(msg=0)) LpStatus[status] print (value(w1)) print (value(w2)) print (value(w3)) print (value(L1)) print (value(L2)) Result is (λ1,λ2,w1,w2,w3) = (1,0,0.051,0.027,0.14) instead of (1,0,0.028,0.0071,0.0214) which is not correct. Could you please let me know where Am I going wrong?
has comment: http://stackoverflow.com/comment/91219012
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52137793
type: Question
upvote count: 1
tagged with: python
tagged with: markov-models

http://stackoverflow.com/a/52216282
has comment: http://stackoverflow.com/comment/91381627
has body: Updated # must under eagar mode def tensor_to_array(tensor1): return tensor1.numpy() example &gt;&gt;&gt; import tensorflow as tf &gt;&gt;&gt; tf.enable_eager_execution() &gt;&gt;&gt; def tensor_to_array(tensor1): ... return tensor1.numpy() ... &gt;&gt;&gt; x = tf.constant([1,2,3,4]) &gt;&gt;&gt; tensor_to_array(x) array([1, 2, 3, 4], dtype=int32) I believe you can do it without tf.eval() or sess.run by using tf.enable_eager_execution() example import tensorflow as tf import numpy as np tf.enable_eager_execution() x = np.array([1,2,3,4]) c = tf.constant([4,3,2,1]) c+x &lt;tf.Tensor: id=5, shape=(4,), dtype=int32, numpy=array([5, 5, 5, 5], dtype=int32)&gt; For more details about tensorflow eager mode, checkout here:Tensorflow eager If without tf.enable_eager_execution(): import tensorflow as tf import numpy as np c = tf.constant([4,3,2,1]) x = np.array([1,2,3,4]) c+x &lt;tf.Tensor 'add:0' shape=(4,) dtype=int32&gt;
has comment: http://stackoverflow.com/comment/91522353
accepted answer of: http://stackoverflow.com/q/52215711
has comment: http://stackoverflow.com/comment/91382159
has comment: http://stackoverflow.com/comment/91381924
upvote count: 8
has comment: http://stackoverflow.com/comment/91390863
answers question: http://stackoverflow.com/q/52215711
type: Answer
has comment: http://stackoverflow.com/comment/91383284
has comment: http://stackoverflow.com/comment/91381663
downvote count: 2
has comment: http://stackoverflow.com/comment/91454227
has comment: http://stackoverflow.com/comment/91391389
has comment: http://stackoverflow.com/comment/91455202
has comment: http://stackoverflow.com/comment/91484771
has comment: http://stackoverflow.com/comment/91388225
has comment: http://stackoverflow.com/comment/91383703
score: 6
has comment: http://stackoverflow.com/comment/91381683
has comment: http://stackoverflow.com/comment/91458529
type: AcceptedAnswer

http://stackoverflow.com/a/52142449
accepted answer of: http://stackoverflow.com/q/52141874
has comment: http://stackoverflow.com/comment/91235399
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52141874
score: 0
type: Answer
has body: Assuming your meeting times will not overlap each other because you cannot be in two places in the same time. Thus, (1,4) (3,5) cannot happen. One way to do this is to iterate with a variable that remembers the previous tuple, in this case I'll name it "previous", I'll keep your variable "m" as it is. Every time you go on the next tuple in your meeting times, you compare the ending meeting time from previous tuple with current starting meeting time. Then you remove the previous tuple because it will be a duplicate. If no condense operation, then you can just append to the list and then set "m" to "previous" for the next iteration. # Variable containing list of tuples meeting_times = [(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)] # Sort meetings by start time ordered_list = sorted(meeting_times) print('Given time tuple: ', ordered_list) def condensed_meeting_time(append_meeting_time, previous): # For each number in the variable for m in ordered_list: if previous: # This is to catch empty tuple that was initial if m[0] == previous[1]: # If current starting meeting time is equal to previous ending meeting time ... del append_meeting_time[-1] # Remove the previous element append_meeting_time.append( (previous[0], m[1]) ) # Create new tuple to merge previous start time to current ending time else: # If the time does not overlap, append normally and set current meeting time to 'previous' for next iteration append_meeting_time.append(m) previous = m else: # Base case to append the first element. append_meeting_time.append(m) previous = m return append_meeting_time print('After condensed range: ',condensed_meeting_time([], ())) This is the output I've got: Given time tuple: [(0, 1), (3, 5), (4, 8), (9, 10), (10, 12)] After condensed range: [(0, 1), (3, 5), (4, 8), (9, 12)] I hope this helps.

http://stackoverflow.com/q/52235715
has title: Merging Excel-Files without reprocessing the content
has comment: http://stackoverflow.com/comment/91446808
has comment: http://stackoverflow.com/comment/91419978
has body: I have a very complex Excel tool to analyze data. I want to enter raw-data into a separate sheet in this file using python. I tried this with openpyxl, but this was destroying my other sheets and diagrams because of unsupported functionalities of openpyxl. When saving, openpyxl is reprocessing all the datasheets. Is there a way to just combine two excel files without this reprocessing? Or another tool allowing for opening a sheet and writing into this without the above mentioned problems? So basically just blindly taking a datasheet and copy that to another file without any changes in other datasheets and compatibility problems.
tagged with: http://stackoverflow.com/tag/xlsx
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 0
tagged with: openpyxl
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/91458807
linked to: http://stackoverflow.com/q/44593705

http://stackoverflow.com/a/52148844
score: 3
type: Answer
answers question: http://stackoverflow.com/q/52124195
has comment: http://stackoverflow.com/comment/91293340
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: You have to enter the parameters for 2to3 to do that... I just saw that the dialog is currently horrible (it doesn't show the full text -- back then the text from 2to3 was probably small, but now that it's big it doesn't fit on the dialog space very well and the content is cropped to what's visible -- just fixed it: https://github.com/fabioz/Pydev/commit/fb0aa9d28c15e7deeb3aa229b0ad66146802d9e4). Now, to answer your question, at the dialog that opens you need to pass -w to write the files creating a backup file or -w -n if you want to write the files but don't want to keep backup files -- which I recommend if your source code is already under source control ;)
accepted answer of: http://stackoverflow.com/q/52124195

http://stackoverflow.com/a/52163260
has comment: http://stackoverflow.com/comment/91304918
has comment: http://stackoverflow.com/comment/91280441
score: 0
has comment: http://stackoverflow.com/comment/91495393
answers question: http://stackoverflow.com/q/52163199
has comment: http://stackoverflow.com/comment/91277025
type: Answer
has comment: http://stackoverflow.com/comment/91276450
has comment: http://stackoverflow.com/comment/91276780
has comment: http://stackoverflow.com/comment/91484706
has comment: http://stackoverflow.com/comment/91495092
has body: Unfortunately, what you're trying to do won't be possible. To run your Python script that is located on your file system, you would have to run it in your terminal and this is not possible to do via your navigator. I recommend you set up a quick server that does this for you. node.js server: const http = require('http'); const { exec } = require('child_process'); const fs = require('fs'); //create a server object: http.createServer(function (req, res) { //if the request url is: localhost:8080 if(req.url === "/"){ fs.readFile("index.html", function(err, data){ res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); res.end(); }); //if the request url is: localhost:8080/run }else if(req.url === "/run"){ exec('./ /home/techm/Documents/labelImg-master/run.sh', (error, stdout, stderr) =&gt; { if (error) { console.error(`exec error: ${error}`); res.write('Command has failed'); //write a response to the client res.end(); //end the response return; } console.log(`stdout: ${stdout}`); console.log(`stderr: ${stderr}`); res.write('Command has been run'); //write a response to the client res.end(); //end the response }); } }).listen(8080); //the server object listens on port 8080 Once you've put the above content in a file called (for example) server.js, run the server by typing node server.js in your terminal (in the same directory as that file) Then your ajax should be something like this. $.ajax({ url: "/run", context: document.body }).done(function(data) { //data should contain what the server responds, in this case "Command has been run" console.log(data); });
has comment: http://stackoverflow.com/comment/91304886
has comment: http://stackoverflow.com/comment/91304773
has comment: http://stackoverflow.com/comment/91277269
has comment: http://stackoverflow.com/comment/91280384

http://stackoverflow.com/comment/91235801
type: QuestionComment
comment on: http://stackoverflow.com/q/52142807
has text: Have you tried to rotate the labels? https://stackoverflow.com/q/10998621/8881141
score: 0
type: Comment

http://stackoverflow.com/q/52128586
tagged with: python
type: AnsweredQuestion
tagged with: list
tagged with: tkinter
has comment: http://stackoverflow.com/comment/91209516
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52128626
type: Question
has title: Create frames based on number of items in a list
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52128626
favorite count: 0
tagged with: python-3.x
has body: So I have a list: titles = ["Crazy", "Delusional", "Perfection", "IDK"] Using tkinter I want to create frames in different row and column based on number of items in a list titles, with the text in each frame (text will be from a list, each frame will get one text from elements in a list, so for example frame 1 will have text "Crazy" in it, frame 2 will have text "Delusional" in it...). In this example, there should be a total of four frames created, but if the number of elements changes, so titles becomes: titles = ["Crazy", "Delusional", "Perfection", "IDK", "Who Knows"] There should be five frames in total.

http://stackoverflow.com/q/52166475
tagged with: python
accepted answer: http://stackoverflow.com/a/52168528
type: AnsweredQuestion
upvote count: 1
type: Question
score: 1
answer count: 2
possible better answer: http://stackoverflow.com/a/52168848
downvote count: 0
tagged with: flask
has answer: http://stackoverflow.com/a/52168848
favorite count: 0
tagged with: ajax
has answer: http://stackoverflow.com/a/52168528
has body: I'm using DataTables to display data from MySQL. It worked fine, until I was forced to use server-side processing (100k rows). Now, when I load the table in the browser, it works fine until I use some feature of DataTables (search, column sorting..). When I click on e.g. column name, all I got is "Processing..." message. I noticed, that with every click on the table, the draw is raised by 1 in the XMLHttpRequest, but my 'draw' is still set to 1 in my code. My definition of draw, recordsTotal, recordsFiltered in python/flask code(shortened): tick = table.query.all() rowsCount = table1.query.count() x = {'draw':1,'recordsTotal':rowsCount,'recordsFiltered':10} y = dict(data=[i.serialize for i in tick]) z = y.copy() z.update(x) @app.route("/api/result") def result_json(): return jsonify(z) @app.route('/data') def get_data(): return render_template('data.html') My JSON: { "data": [ { "first": "Anton", "id": 1, "last": "Spelec" }, { "first": "Rosamunde", "id": 2, "last": "Pilcher" }, { "first": "Vlasta", "id": 3, "last": "Burian" }, { "first": "Anton", "id": 4, "last": "Bernolak" }, { "first": "Willy", "id": 5, "last": "Wonka" } ], "draw": 1, "recordsFiltered": 5, "recordsTotal": 5 } My html page with DataTables inicialisation: id first last The XHR is here: Request URL: <a href="http://10.10.10.12/api/result?draw=7&columns%5B0%5D%5Bdata%5D=id&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=first&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=last&columns%5B2%5D%5Bname%5D=&columns%5B2%5D%5Bsearchable%5D=true&columns%5B2%5D%5Borderable%5D=true&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D…
linked to: http://stackoverflow.com/q/36269684
has title: DataTables server-side processing - echoing back draw() parameter (Python/Flask)
tagged with: datatables

http://stackoverflow.com/a/52147795
accepted answer of: http://stackoverflow.com/q/52134574
has body: There's quite a lot of repetition in your program and the events shouldn't be handled in the while but in the event loop. I'd put all rects into a list and draw and update them in for loops. To select a rect, just loop over the rects and assign the colliding rect to a variable (selected in my example below). When pygame.MOUSEMOTION events occur, you can just add the event.rel (relative mouse movement) to the x and y attributes of the selected rect. We need to move along the x- and y-axis separately, so that we can handle the collisions with the other rects. If the selected rect moved along the x-axis and it collides with another rect, we can set its right or left coordinates to the left or right coords of the colliding rect. Afterwards we can do the same for the y-axis and set the top or bottom coords. For the boundary, I'd use a rect with the size of the screen and shrink it a little bit (with pygame.Rect.inflate) to get a smaller rect for the bounds checking. import pygame LINE_WIDTH = 10 WHITE = (255, 255, 255) RED = (255, 0, 0) BLACK = (0, 0, 0) LIGHT_BROWN = (153, 102, 51) FPS = 30 pygame.init() screen = pygame.display.set_mode((490+LINE_WIDTH, 600+LINE_WIDTH)) clock = pygame.time.Clock() screen_rect = screen.get_rect() boundary = screen_rect.inflate((-21, -21)) boundary.move_ip(1, 1) # Keep the square as a separate variable, so that we can # draw it with a different color. square = pygame.rect.Rect(150, 50, 200, 200) # Put all rects (the square as well) into a list. rects = [ pygame.rect.Rect(40, 50, 100, 200), pygame.rect.Rect(40, 260, 100, 200), pygame.rect.Rect(360, 50, 100, 200), pygame.rect.Rect(360, 260, 100, 200), pygame.rect.Rect(150, 260, 200, 100), pygame.rect.Rect(150, 370, 95, 95), pygame.rect.Rect(255, 370, 95, 95), pygame.rect.Rect(45, 470, 95, 95), pygame.rect.Rect(360, 470, 95, 95), square, ] selected = None # The currently selected rect. running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = Fals…
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52134574
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/91257776
has text: Interesting but elaborating more would be nice.
type: Comment
comment on: http://stackoverflow.com/a/52153801
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91425006
type: AnswerComment
score: 0
type: Comment
has text: It does overwrite the first row (`[1, 4]`) with column names.
comment on: http://stackoverflow.com/a/52238076

http://stackoverflow.com/q/52120776
has title: Avoiding for loop in multidimensional array
tagged with: numpy
has answer: http://stackoverflow.com/a/52123687
score: 0
answer count: 1
type: UnansweredQuestion
has body: So I have a 3D-array: &gt;&gt;&gt; img_data.shape (182, 218, 182) My idea is to replace every value equals to 0 with 255. I tried: new_img = np.zeros(img_range) print(new_img.shape) for i in range(img_range[0]): for j in range(img_range[1]): for k in range(img_range[2]): print "%s %s %s" % (i, j, k ) if img_data[i][j][k] == 0: new_img[i][j][k] = 2 else: new_img[i][j][k] = img_data[i][j][k] But this take forever, most likely because Python is dynamic and may be doing something in the backgrouns. Any ideas on how to improve this? Thanks, Rodrigo
tagged with: python
tagged with: indexing
type: Question

http://stackoverflow.com/a/52248634
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52248558
has body: Here's a dictionary comprehension with slicing that should do the trick: A = [['PokedexNumber', 'Name', 'Type', 'Total'], [1.0, 'Bulbasaur', 'GrassPoison', 318.0], [2.0, 'Ivysaur', 'GrassPoison', 405.0],[3.0, 'Venusaur', 'GrassPoison', 525.0]] B = {x[0]: dict(zip(A[0][1:], x[1:])) for x in A[1:]} print(B) Output: { 1.0: {'Name': 'Bulbasaur', 'Type': 'GrassPoison', 'Total': 318.0}, 2.0: {'Name': 'Ivysaur', 'Type': 'GrassPoison', 'Total': 405.0}, 3.0: {'Name': 'Venusaur', 'Type': 'GrassPoison', 'Total': 525.0} }
answers question: http://stackoverflow.com/q/52248558
downvote count: 1
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91264880
score: 0
type: Comment
has text: I don't know it's just me but it's taking a lot of time. I executed it but still no output.
comment on: http://stackoverflow.com/a/52157273
type: AnswerComment

http://stackoverflow.com/a/52275092
has comment: http://stackoverflow.com/comment/91513032
has comment: http://stackoverflow.com/comment/91511614
type: AcceptedAnswer
downvote count: 0
has body: I'm sure the problem is neither in --target nor in --no-cache-dir. I tried both command in transient empty virtual environments (recreating a venv after every command) and got the error with pip install fbprophet --target=/tmp/foo. I believe the problem is in fbprophet's setup.py: it imports pystan during build process without checking that it's available or installing it. I think it could be fixed by copying or moving pystan from requirements.txt to setup_requires. I suspect you didn't get the problem because after pip install fbprophet --no-cache-dir you have pystan installed globally. Remove everything installed with the 1st command and retry the second one. Or try them in new empty virtual environments. Send a pull request to fix the problem. I also think you can install in 2 steps: pip install --target=/tmp/foo --no-cache-dir pystan PYTHONPATH=/tmp/foo pip install --target=/tmp/foo --no-cache-dir fbprophet
type: Answer
accepted answer of: http://stackoverflow.com/q/52267470
answers question: http://stackoverflow.com/q/52267470
upvote count: 2
has comment: http://stackoverflow.com/comment/91511134
score: 2

web-scraping
tags question: http://stackoverflow.com/q/52171266
tags question: http://stackoverflow.com/q/52265577
tags question: http://stackoverflow.com/q/52129625
tags question: http://stackoverflow.com/q/52203593
tags question: http://stackoverflow.com/q/52228851
tags question: http://stackoverflow.com/q/52264028
tags question: http://stackoverflow.com/q/52114689
tags question: http://stackoverflow.com/q/52121094
tags question: http://stackoverflow.com/q/52134236
tags question: http://stackoverflow.com/q/52133734
tags question: http://stackoverflow.com/q/52137096
tags question: http://stackoverflow.com/q/52122834
tags question: http://stackoverflow.com/q/52170647
tags question: http://stackoverflow.com/q/52255112
tags question: http://stackoverflow.com/q/52125795
tags question: http://stackoverflow.com/q/52234500
tags question: http://stackoverflow.com/q/52237252
tags question: http://stackoverflow.com/q/52121730
tags question: http://stackoverflow.com/q/52156566
tags question: http://stackoverflow.com/q/52211523
tags question: http://stackoverflow.com/q/52261961
tags question: http://stackoverflow.com/q/52245035
tags question: http://stackoverflow.com/q/52119710
tags question: http://stackoverflow.com/q/52259882
tags question: http://stackoverflow.com/q/52141535
tags question: http://stackoverflow.com/q/52143512
tags question: http://stackoverflow.com/q/52120798
tags question: http://stackoverflow.com/q/52160845
tags question: http://stackoverflow.com/q/52205651
tags question: http://stackoverflow.com/q/52191528
tags question: http://stackoverflow.com/q/52187736
tags question: http://stackoverflow.com/q/52172376
tags question: http://stackoverflow.com/q/52266458
tags question: http://stackoverflow.com/q/52185815
tags question: http://stackoverflow.com/q/52150441
tags question: http://stackoverflow.com/q/52117628
tags question: http://stackoverflow.com/q/52227687
tags question: http://stackoverflow.com/q/52217866
tags question: http://stackoverflow.com/q/52160524
tags question: http://stackoverflow.com/q/52245908
tags question: http://stackoverflow.com/q/52129216
tags question: http://stackoverflow.com/q/52189783
tags question: http://stackoverflow.com/q/52246009
tags question: http://stackoverflow.com/q/52158893
tags question: http://stackoverflow.com/q/52267782
tags question: http://stackoverflow.com/q/52134210
tags question: http://stackoverflow.com/q/52114168
tags question: http://stackoverflow.com/q/52121009
tag name: web-scraping
tags question: http://stackoverflow.com/q/52232414
tags question: http://stackoverflow.com/q/52117674
tags question: http://stackoverflow.com/q/52225334
tags question: http://stackoverflow.com/q/52241118
tags question: http://stackoverflow.com/q/52179181
tags question: http://stackoverflow.com/q/52139568
tags question: http://stackoverflow.com/q/52263273
tags question: http://stackoverflow.com/q/52251228
tags question: http://stackoverflow.com/q/52155127
tags question: http://stackoverflow.com/q/52178474
tags question: http://stackoverflow.com/q/52260690
tags question: http://stackoverflow.com/q/52134302
tags question: http://stackoverflow.com/q/52202855
tags question: http://stackoverflow.com/q/52191137
type: Tag
tags question: http://stackoverflow.com/q/52165717
tags question: http://stackoverflow.com/q/52204743
tags question: http://stackoverflow.com/q/52237899
tags question: http://stackoverflow.com/q/52251377
tags question: http://stackoverflow.com/q/52240846
tags question: http://stackoverflow.com/q/52232476
tags question: http://stackoverflow.com/q/52121802
tags question: http://stackoverflow.com/q/52231714
tags question: http://stackoverflow.com/q/52137368
tags question: http://stackoverflow.com/q/52139594
tags question: http://stackoverflow.com/q/52140611
tags question: http://stackoverflow.com/q/52240455
tags question: http://stackoverflow.com/q/52260421

http://stackoverflow.com/comment/91528750
score: 0
has text: TimeGrouper has been depreciated and should not be used, you now need to use pb.Grouper() instead
comment on: http://stackoverflow.com/q/52270523
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91487407
type: QuestionComment
comment on: http://stackoverflow.com/q/52259900
has text: Before I write the code can you please expand a bit on your sub group conditions
score: 0
type: Comment

http://stackoverflow.com/comment/91369615
score: 0
type: QuestionComment
has text: You might be able to make `Node` an `int` subclass (with a `hello` method), then make `container.node` a `property` that stores a `Node` when given a `int`. That seems like a lot of work for no real benefit, plus I'm not sure how one would go about subclassing `int` sensibly.
comment on: http://stackoverflow.com/q/52209967
type: Comment

http://stackoverflow.com/comment/91292536
score: 1
comment on: http://stackoverflow.com/q/52170770
type: Comment
type: QuestionComment
has text: What are you trying to accomplish when you call `self.img.put(circle)`?

http://stackoverflow.com/q/52152162
has body: I'm making an analog clock program with pygame, datetime, and math, but the angles that the hands are at are all off, and the second hand goes way too quickly. Here's the code: import pygame from datetime import datetime from datetime import time from datetime import timedelta import math import time pygame.init() white = (255, 255, 255) black = (0, 0, 0) display_width = 400 display_height = 400 gameDisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('Clock') gameDisplay.fill(white) clock = pygame.time.Clock() clock_radius = 200 clock_center = int(display_width / 2), int(display_height / 2) def main(): for event in pygame.event.get(): if event.type == pygame.QUIT: quit() # Drawing the clock and its center. pygame.draw.circle(gameDisplay, black, clock_center, clock_radius, 5) pygame.draw.circle(gameDisplay, black, clock_center, 5, 0) pygame.display.update() # I move the hands by drawing a white line over the previous line # and then drawing the new line (which is a hand), so I need a # variable equal to the time one second ago (for the white line) as # well as the current time (for the current hand). now_hour = int(datetime.now().strftime('%I')) now_minute = int(datetime.now().strftime('%M')) now_second = int(datetime.now(). strftime('%S')) one_sec_ago_hour = int((datetime.now() - timedelta(seconds=1)).strftime('%I')) one_sec_ago_minute = int((datetime.now() - timedelta(seconds=1)).strftime('%M')) one_sec_ago_second = int((datetime.now() - timedelta(seconds=1)).strftime('%S')) # Drawing the lines/defining the endpoints with math. pygame.draw.line(gameDisplay, white, clock_center, ((clock_radius * (3 / 5)) * math.cos(90 - one_sec_ago_hour * 30) + 200, (clock_radius * (3 / 5)) * math.sin(90 - one_sec_ago_hour * 30) + 200), 10) pygame.draw.line(gameDisplay, white, clock_center, (clock_radius * (4 / 5) * math.cos(90 - one_sec_ago_minute * 6) + 200, clock_radius * (4 / 5) * math.sin(90 - one_sec_ago_minute * 6) + 200), 3) pygame.d…
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52153160
tagged with: datetime
tagged with: python
tagged with: pygame
type: AnsweredQuestion
has title: Why are the hands of my python analog clock showing the wrong time?
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/52153160
type: Question

http://stackoverflow.com/comment/93458874
type: QuestionComment
has text: I want to bring this thread back to life as I am having the same problems. Any input please??
comment on: http://stackoverflow.com/q/52218951
score: 0
type: Comment

http://stackoverflow.com/comment/129989324
score: 3
has text: Also `pathlib.Path().cwd()`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52119454

http://stackoverflow.com/a/52239472
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/91427801
answers question: http://stackoverflow.com/q/52239401
has comment: http://stackoverflow.com/comment/91427783
score: 1
has body: Assuming all your keys are positive integers. Then the complexity of this issue is twofold, first we need to find the maximum values, then we can pair it with a maximum key. I would do something like this: max_key = -1 max_val = -1 for key, val in my_dict.items(): if int(val) >= max_val: max_val = int(val) if int(key) > max_key: max_key = int(key) print("Max value: {}\nMax key: {}".format(max_val, max_key) That should do it. EDIT Using builtin function max probably works better, this code basically replicates what max is doing more or less.
has comment: http://stackoverflow.com/comment/91427796
has comment: http://stackoverflow.com/comment/91427743

http://stackoverflow.com/q/52216312
has title: Pandas Groupby: Is there normalization functionality? or best way to find ratio of total in group
has answer: http://stackoverflow.com/a/52216368
favorite count: 0
linked to: http://stackoverflow.com/q/47152691
upvote count: 1
possible better answer: http://stackoverflow.com/a/52216368
has body: Data: {"Survived":{"0":0,"1":1,"2":1,"3":1,"4":0,"5":0,"6":0,"7":0,"8":1,"9":1,"10":1,"11":1,"12":0,"13":0,"14":0,"15":1,"16":0,"17":1,"18":0,"19":1,"20":0,"21":1,"22":1,"23":1,"24":0,"25":1,"26":0,"27":0,"28":1,"29":0,"30":0,"31":1,"32":1,"33":0,"34":0,"35":0,"36":1,"37":0,"38":0,"39":1,"40":0,"41":0,"42":0,"43":1,"44":1,"45":0,"46":0,"47":1,"48":0,"49":0},"Pclass":{"0":3,"1":1,"2":3,"3":1,"4":3,"5":3,"6":1,"7":3,"8":3,"9":2,"10":3,"11":1,"12":3,"13":3,"14":3,"15":2,"16":3,"17":2,"18":3,"19":3,"20":2,"21":2,"22":3,"23":1,"24":3,"25":3,"26":3,"27":1,"28":3,"29":3,"30":1,"31":1,"32":3,"33":2,"34":1,"35":1,"36":3,"37":3,"38":3,"39":3,"40":3,"41":2,"42":3,"43":2,"44":3,"45":3,"46":3,"47":3,"48":3,"49":3},"Sex":{"0":"male","1":"female","2":"female","3":"female","4":"male","5":"male","6":"male","7":"male","8":"female","9":"female","10":"female","11":"female","12":"male","13":"male","14":"female","15":"female","16":"male","17":"male","18":"female","19":"female","20":"male","21":"male","22":"female","23":"male","24":"female","25":"female","26":"male","27":"male","28":"female","29":"male","30":"male","31":"female","32":"female","33":"male","34":"male","35":"male","36":"male","37":"male","38":"female","39":"female","40":"female","41":"female","42":"male","43":"female","44":"female","45":"male","46":"male","47":"female","48":"male","49":"female"},"Age":{"0":22.0,"1":38.0,"2":26.0,"3":35.0,"4":35.0,"5":28.0,"6":54.0,"7":2.0,"8":27.0,"9":14.0,"10":4.0,"11":58.0,"12":20.0,"13":39.0,"14":14.0,"15":55.0,"16":2.0,"17":28.0,"18":31.0,"19":28.0,"20":35.0,"21":34.0,"22":15.0,"23":28.0,"24":8.0,"25":38.0,"26":28.0,"27":19.0,"28":28.0,"29":28.0,"30":40.0,"31":28.0,"32":28.0,"33":66.0,"34":28.0,"35":42.0,"36":28.0,"37":21.0,"38":18.0,"39":14.0,"40":40.0,"41":27.0,"42":28.0,"43":3.0,"44":19.0,"45":28.0,"46":28.0,"47":28.0,"48":28.0,"49":18.0},"SibSp":{"0":1,"1":1,"2":0,"3":1,"4":0,"5":0,"6":0,"7":3,"8":0,"9":1,"10":1,"11":0,"12":0,"13":1,"14":0,"15":0,"16":4,"17":0,"18":1,"19":0,"20":0,"2…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52216376
score: 1
type: Question
duplicate of: http://stackoverflow.com/q/47152691
downvote count: 0
accepted answer: http://stackoverflow.com/a/52216376
answer count: 3
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/52216432

http://stackoverflow.com/comment/91305488
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52177086
has text: @user10163680 that is *string formatting*, that doesn't affect the `float` objects.

http://stackoverflow.com/comment/91221805
type: AnswerComment
score: 0
type: Comment
has text: Thanks! Using the 1 in `all(1)` for column axis was what I was missing
comment on: http://stackoverflow.com/a/52135563

http://stackoverflow.com/q/52135625
has title: Solving functional equations with tensorflow
answer count: 1
favorite count: 0
has body: Let us consider the functional equation Mathematically, we know how to solve that equation in closed form, but what if we look for an approximate solution f in the form of a fully-connected 1 or 2-layer neural network with relu activation function? What is the best way in Tensorflow to do a gradient descent on for mini-batches of x's drawn randomly in [-10,10] ? My question arises from the fact that there is both f(x) and f(x+1) in the equation, and that differs from classical supervised learning.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91225627
tagged with: python
has comment: http://stackoverflow.com/comment/91227218
score: 1
upvote count: 3
downvote count: 2
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/52139079

http://stackoverflow.com/comment/91470489
score: 1
type: Comment
type: QuestionComment
has text: Possible duplicate of [Call Python function from Javascript code](https://stackoverflow.com/questions/13175510/call-python-function-from-javascript-code)
comment on: http://stackoverflow.com/q/52261414

http://stackoverflow.com/comment/91316624
has text: i edit the post with detail
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52180216
type: Comment

http://stackoverflow.com/comment/91209581
comment on: http://stackoverflow.com/a/52123275
score: 0
type: AnswerComment
type: Comment
has text: Okay, I will. But one thing, I was referring to the change made in the comment above. Passing in threadsperblock = 64 and blockspergrid = 16 would make it parallelized, right?

http://stackoverflow.com/q/52167754
type: Question
upvote count: 1
tagged with: python
answer count: 1
tagged with: python-import
has title: In Jupyter Notebook NameError when I try to import a module
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91285990
has comment: http://stackoverflow.com/comment/105140660
tagged with: nameerror
score: 1
has body: I have 2 modules written in Jupyter Notebook (windows OS). I try to import module_1.py into module_2.py like that: import module_2 ... I have error: NameError Traceback (most recent call last) in () 1 from tkinter import * 2 ----> 3 import Backend 4 5 def view_command(): C:\python\GUI\Backend.py in &lt;module&gt;() 72 { 73 "cell_type": "code", ---&gt; 74 "execution_count": null, 75 "metadata": {}, 76 "outputs": [], NameError: name 'null' is not defined Maybe it is because of in IPython importing is not as simple as in Python. Thanks for help
has comment: http://stackoverflow.com/comment/91285507
favorite count: 0
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/52172436

http://stackoverflow.com/a/52270199
has comment: http://stackoverflow.com/comment/91488950
has comment: http://stackoverflow.com/comment/91488834
has comment: http://stackoverflow.com/comment/91489798
has comment: http://stackoverflow.com/comment/91492420
has comment: http://stackoverflow.com/comment/91489735
has comment: http://stackoverflow.com/comment/91489644
has comment: http://stackoverflow.com/comment/91489745
score: 6
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/91489769
has comment: http://stackoverflow.com/comment/91489646
accepted answer of: http://stackoverflow.com/q/52269950
has comment: http://stackoverflow.com/comment/91489208
answers question: http://stackoverflow.com/q/52269950
has comment: http://stackoverflow.com/comment/91489609
has body: short answer: Qt5 does not provide the use of the terminal, so you will have to use QProcess. TL;DR The EmbTerminal class that is proposed as a solution is a widget so you must add it with addTab(), keep in mind that you must have installed the urxvt terminal (if you want to check your installation run urxvt in the terminal) import sys from PyQt5 import QtCore, QtWidgets class EmbTerminal(QtWidgets.QWidget): def __init__(self, parent=None): super(EmbTerminal, self).__init__(parent) self.process = QtCore.QProcess(self) self.terminal = QtWidgets.QWidget(self) layout = QtWidgets.QVBoxLayout(self) layout.addWidget(self.terminal) # Works also with urxvt: self.process.start('urxvt',['-embed', str(int(self.winId()))]) self.setFixedSize(640, 480) class mainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super(mainWindow, self).__init__(parent) central_widget = QtWidgets.QWidget() lay = QtWidgets.QVBoxLayout(central_widget) self.setCentralWidget(central_widget) tab_widget = QtWidgets.QTabWidget() lay.addWidget(tab_widget) tab_widget.addTab(EmbTerminal(), "EmbTerminal") tab_widget.addTab(QtWidgets.QTextEdit(), "QTextEdit") tab_widget.addTab(QtWidgets.QMdiArea(), "QMdiArea") if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) main = mainWindow() main.show() sys.exit(app.exec_())
has comment: http://stackoverflow.com/comment/91489692
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91356833
score: 0
type: Comment
has text: Thanks for the good practice advice. I just realized there was an extra `/python/` in the pyinstaller path so I removed it. Now it finds pyinstaller just fine but I get the famous `Fatal error in launcher: Unable to create process using ""`
type: AnswerComment
comment on: http://stackoverflow.com/a/52203449

http://stackoverflow.com/comment/91281606
score: 0
type: Comment
has text: @matias-valdenegre Alright! Now I tried updating virtualenv following Tensorflow instructions and I get `Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow`
comment on: http://stackoverflow.com/a/52165475
type: AnswerComment

http://stackoverflow.com/comment/91321102
has text: So I just replace with what you wrote? if __name__ == '__main__': parser = OptionParser(usage="Usage: python %prog [FILE]...") # No options added yet. Add them here if you ever need them. options, args = parser.parse_args() if not args: parser.print_usage() exit(1) for arg in args: if os.path.isfile(arg): for email in get_emails(file_to_str(arg)): print email else: print '"{}" is not a file.'.format(arg) parser.print_usage()
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52185637
type: AnswerComment

http://stackoverflow.com/a/73278154
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52214171
has body: You can with discohook.org, add an embed then click image and add the image url, to get the url post the image you want to discord then click it and then copy the url and paste it into discohook image embed

http://stackoverflow.com/q/52197927
favorite count: 0
tagged with: python
tagged with: qtwebchannel
type: AnsweredQuestion
tagged with: qwebenginepage
tagged with: pyside2
has comment: http://stackoverflow.com/comment/91348806
type: Question
score: 5
has answer: http://stackoverflow.com/a/52510913
upvote count: 5
tagged with: qwebengineview
has body: I wrote an app in pyside2, which opening a webpage in QWebEngine. That web page has 2 buttons, I am not understanding how can I detect a button click in pyside2 app module, I need to perform other operation on that button click. Example below is my code from PySide2.QtWidgets import QApplication from PySide2.QtWebEngineWidgets import QWebEngineView, QWebEnginePage from PySide2.QtCore import QUrl class WebEnginePage(QWebEnginePage): def __init__(self, *args, **kwargs): QWebEnginePage.__init__(self, *args, **kwargs) self.featurePermissionRequested.connect(self.onFeaturePermissionRequested) def onFeaturePermissionRequested(self, url, feature): if feature in (QWebEnginePage.MediaAudioCapture, QWebEnginePage.MediaVideoCapture, QWebEnginePage.MediaAudioVideoCapture): self.setFeaturePermission(url, feature, QWebEnginePage.PermissionGrantedByUser) else: self.setFeaturePermission(url, feature, QWebEnginePage.PermissionDeniedByUser) app = QApplication([]) view = QWebEngineView() page = WebEnginePage() page.profile().clearHttpCache() view.setPage(page) view.load(QUrl("https://test.webrtc.org/")) view.show() app.exec_() below is the output: Now I just want to close my application when a user clicks "start" button.
accepted answer: http://stackoverflow.com/a/52510913
has comment: http://stackoverflow.com/comment/91347913
has comment: http://stackoverflow.com/comment/91347894
downvote count: 0
answer count: 1
has title: How to detect button click inside Qwebengine in pyside2

http://stackoverflow.com/comment/91238607
type: Comment
has text: You can also log _inside_ operators using the log method from BaseOperator like so `self.log.info("This was %s", "fun")`. Are all the print-statements done inside the dag or is your for-loop inside a custom Operator?
comment on: http://stackoverflow.com/q/52144108
score: 0
type: QuestionComment

http://stackoverflow.com/a/52223316
type: Answer
score: 1
upvote count: 1
has body: from the docs: Externally Visible Server If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer. If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding --host=0.0.0.0 to the command line: flask run --host=0.0.0.0 This tells your operating system to listen on all public IPs.
answers question: http://stackoverflow.com/q/52223096
downvote count: 0

http://stackoverflow.com/q/52181628
linked to: http://stackoverflow.com/q/51949189
has comment: http://stackoverflow.com/comment/91313628
linked to: http://stackoverflow.com/q/2719038
tagged with: django
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/52177182
has answer: http://stackoverflow.com/a/52181755
has title: django - While using get_user_model for user creation
type: Question
has comment: http://stackoverflow.com/comment/91313331
has body: How do I override the .save() method for the model which uses get_user_model? forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django import forms class UserCreateForm(UserCreationForm): class Meta: fields = ("first_name", "last_name", "username", "email", "password1", "password2") model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["username"].label = "Username" self.fields["email"].label = "Email address" On creation of user I want to send user data into another model. As it has no written model (rather I'm importing it as from django.contrib.auth import get_user_model), how do I override the save method like- def save(self, *args, **kwargs): super(Model, self).save() Record.objects.create( employee_ID = self.employee_ID, first_name = self.first_name, last_name = self.last_name) where my Record model is - class Record(models.Model): first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) employee_ID = models.CharField(max_length = 20)
has comment: http://stackoverflow.com/comment/91314161
possible better answer: http://stackoverflow.com/a/52182190
score: 0
accepted answer: http://stackoverflow.com/a/52181755
answer count: 2
has answer: http://stackoverflow.com/a/52182190

http://stackoverflow.com/comment/91441284
has text: It depends upon what you want to compile and what is missing. There is no simple answer. You need to refer to individual package's installation instructions.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52246329

http://stackoverflow.com/comment/91338715
comment on: http://stackoverflow.com/a/52194229
type: AnswerComment
type: Comment
score: 0
has text: You're assuming that the `Device` constructor is called with `unicode` rather than `str` here? That's certainly possible, but it seems just as possible that they're, say, UTF-8 strings (which in 3.x automatically got decoded to `str` using the default UTF-8 encoding, but in 2.7 they get left as `str`, which you then try to `%s` into a unicode format string, which implicitly decodes them as ASCII).

http://stackoverflow.com/q/52118322
answer count: 0
has comment: http://stackoverflow.com/comment/91187566
type: Question
tagged with: mongodb
tagged with: flask
has body: I have a Project model with the following fields: class Project(db.Document): project_name = db.StringField(max_length=80, required=True) description = db.StringField(max_length=160, required=True) start_date = db.DateTimeField(required=True) end_date = db.DateTimeField(required=True) created = db.DateTimeField() status = db.BooleanField(default=False) releases = db.ListField(db.ReferenceField(Release)) and I am trying to create a route that shows all the active projects only whose status are set to true, and their end date has not being passed. UPDATED @app.route('/search/projects', methods=['GET']) def search_projects_get(): try: proj = Project.objects if proj.status is True and proj.end_date &lt; datetime.now(): return jsonify(proj) except Exception as e: errors.bad_request(repr(e)) Can someone please help me complete the logic in my route?
score: 0
has comment: http://stackoverflow.com/comment/91187878
has comment: http://stackoverflow.com/comment/91187971
type: UnansweredQuestion
has title: In python, how to set condition to check which projects are currently active and their end date has not passed?
tagged with: python
has comment: http://stackoverflow.com/comment/91187814

http://stackoverflow.com/a/52139782
score: 0
answers question: http://stackoverflow.com/q/52139610
type: Answer
has body: You were comparing strings not variables, you need to remove quotes, and you not saved random number into a variable. The for loop is making one repetition only, you can remove it. Update your cod like this: import random def loto(): _number = int(input("Enter any number between 1-10: ")) rand_number = random.randint(1,11) # can't had the same name as random if (_number == rand_number): print ("You Won! :)") elif (_number &lt; rand_number): print ("Your number is less") elif (_number &gt; rand_number): print ("Your number is more") else: print ("You Lost :(") loto()

http://stackoverflow.com/comment/91377253
type: QuestionComment
comment on: http://stackoverflow.com/q/52213776
has text: I've found that adding dropout layers can significantly improve accuracy. I'd also experiment with batch sizes. With image classification, I've had good results with small batch sizes.
score: 0
type: Comment

http://stackoverflow.com/a/52205225
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52205160
score: 3
type: Answer
answers question: http://stackoverflow.com/q/52205160
has body: You can do with two steps df['bonus_value']=df.id.map(df[df.bonus].groupby('id').value.sum())# map the sum value for each group df.loc[df.bonus,'bonus_value']=0 #then assign 0 to bonus is True df Out[205]: bonus id value bonus_value 0 True 1 10 0 1 True 1 15 0 2 False 1 5 25 3 False 2 20 10 4 True 2 10 0
upvote count: 3
type: AcceptedAnswer

dns
tags question: http://stackoverflow.com/q/52259116
tag name: dns
tags question: http://stackoverflow.com/q/52224310
type: Tag
tags question: http://stackoverflow.com/q/52126729
tags question: http://stackoverflow.com/q/52146491

http://stackoverflow.com/comment/91378331
has text: That `extend` call is a silly way to add multiple values to the list. You have to *build* a tuple with the values in order to pass them all to the `extend` method. If you're doing that, you should just switch the parentheses for square brackets and make the list directly with a literal `[video_ad_1, ...]`. There's the same issue with your suggested loop (you can't loop over the variables without putting them in something iterable, but the most appropriate iterable to use is the list you're expecting as output). I suspect the questioner's teacher just expects a bunch of `append` calls in a row.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52214510

http://stackoverflow.com/comment/91327329
type: Comment
type: QuestionComment
has text: @Bazingaa Okay. So passing 3 values in the `guess` array and 3 in the `bounds` array would make sense in a 3-d function?
score: 0
comment on: http://stackoverflow.com/q/52188012

http://stackoverflow.com/q/52119128
score: 4
has answer: http://stackoverflow.com/a/52351939
has comment: http://stackoverflow.com/comment/91189291
tagged with: string
favorite count: 0
tagged with: python
upvote count: 4
tagged with: dictionary
has title: Best way to match whether a sub-string is present in the keys of a python dictionary
answer count: 4
tagged with: lookup
downvote count: 0
has answer: http://stackoverflow.com/a/52119690
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91189362
has answer: http://stackoverflow.com/a/52119323
type: Question
has body: I have a Python dictionary, a sample structure of which is as below (excerpt): items = { "Google": "Mountain View", "Johnson &amp; Johnson": "New Brunswick", "Apple": "Cupertino", } Now what I have is a string, namely str1. What I want to do is look if any of the keys from dictionary items is present in string str1, for example if I have a string like Where is Google based out of?. Initially I wrote this pseudo code: for str_word in str1.split(): if str_word in items: print("Key found. Value is = ".format(items[str_word])) Now this is good as dictionary keys are indexed/hashed. So the in operator runtime is constant but as you can notice this works fine for words like Google or Apple but this will not work for Johnson &amp; Johnson (if my string is Where is Jonhnson &amp; Johnson based out of?). The other way I can think of is to first extract all the keys from the dictionary and then iterate one-by-one over each key and see if it is present in the str1 (reverse of first approach). This will increase the runtime as my dictionary is huge with hundreds or thousands of keys. I want to know if there is a way I can modify my first approach to count for being able to match a sub-string with keys of a dictionary that could contain multiple words like Johnson &amp; Johnson?
has comment: http://stackoverflow.com/comment/91189403
has answer: http://stackoverflow.com/a/52119295

http://stackoverflow.com/comment/91184282
type: Comment
type: QuestionComment
has text: @Wen I made an edit, is the example I provided what you are looking for?
score: 0
comment on: http://stackoverflow.com/q/52116171

http://stackoverflow.com/q/52225956
has title: How to make scrapy follow invalid links?
has answer: http://stackoverflow.com/a/52233023
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/91402008
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91405216
tagged with: python-3.x
tagged with: python
has body: I use scrapy very often to check long lists of links whether they're available or dead. My problem is when the link is incorrectly formatted for example doesn't start with http:// or https:// the crawler crashes. ValueError: Missing scheme in request url: http.www.gobiernoenlinea.gob.ve/noticias/viewNewsUser01.jsp?applet=1&amp;id_noticia=41492 I read the list of links from pandas Series and check each of them. When the response is reachable I log it as "ok" otherwise as "dead". import scrapy import pandas as pd from link_checker.items import LinkCheckerItem class Checker(scrapy.Spider): name = "link_checker" def get_links(self): df = pd.read_csv(r"final_07Sep2018.csv") return df["Value"] def start_requests(self): urls = self.get_links() for url in urls.iteritems(): index = {"index" : url[0]} yield scrapy.Request(url=url[1], callback=self.get_response, errback=self.errback_httpbin, meta=index, dont_filter=True) def get_response(self, response): url = response.url yield LinkCheckerItem(index=response.meta["index"], url=url, code="ok") def errback_httpbin(self, failure): yield LinkCheckerItem(index=failure.request.meta["index"], url=failure.request.url, code="dead") I am still interested in spotting those incorrectly formatted urls. How can I validate them and yield "dead" for those as well?
has comment: http://stackoverflow.com/comment/91401887
type: UnansweredQuestion

http://stackoverflow.com/a/52276382
type: AcceptedAnswer
downvote count: 0
has body: To use either initializable or reinitializable iterators, you must create a class that inherits from tf.train.SessionRunHook, which has access to the session at multiple times during training and evaluation steps. You can then use this new class to initialize the iterator has you would normally do in a classic setting. You simply need to pass this newly created hook to the training/evaluation functions or to the correct train spec. Here is quick example that you can adapt to your needs : class IteratorInitializerHook(tf.train.SessionRunHook): def __init__(self): super(IteratorInitializerHook, self).__init__() self.iterator_initializer_func = None # Will be set in the input_fn def after_create_session(self, session, coord): # Initialize the iterator with the data feed_dict self.iterator_initializer_func(session) def get_inputs(X, y): iterator_initializer_hook = IteratorInitializerHook() def input_fn(): X_pl = tf.placeholder(X.dtype, X.shape) y_pl = tf.placeholder(y.dtype, y.shape) dataset = tf.data.Dataset.from_tensor_slices((X_pl, y_pl)) dataset = ... ... iterator = dataset.make_initializable_iterator() next_example, next_label = iterator.get_next() iterator_initializer_hook.iterator_initializer_func = lambda sess: sess.run(iterator.initializer, feed_dict={X_pl: X, y_pl: y}) return next_example, next_label return input_fn, iterator_initializer_hook ... train_input_fn, train_iterator_initializer_hook = get_inputs(X_train, y_train) test_input_fn, test_iterator_initializer_hook = get_inputs(X_test, y_test) ... estimator.train(input_fn=train_input_fn, hooks=[train_iterator_initializer_hook]) # Don't forget to pass the hook ! estimator.evaluate(input_fn=test_input_fn, hooks=[test_iterator_initializer_hook])
type: Answer
accepted answer of: http://stackoverflow.com/q/52266000
score: 4
answers question: http://stackoverflow.com/q/52266000
upvote count: 4

http://stackoverflow.com/comment/91274321
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52162064
has text: I don't understand what you're asking here. You do have a model class: Mytable. But if you want a dropdown, why don't you create a form?

http://stackoverflow.com/a/52173622
type: Answer
has body: The problem is if the function does not return anything then it will throw an error as the variable is never defined because initialization of variable depends on the return value of the function. Just initialize the variable with None ticket_reservation_expired_var = None ticket_reservation_expired_var = ticket_reservation_expired( self.timestamp_of_reservation ) if ticket_reservation_expired_var: return redirect( 'events:detail', organizer=self.organizer, event=self.event, )
downvote count: 1
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/91298303
has comment: http://stackoverflow.com/comment/91305507
answers question: http://stackoverflow.com/q/52173321

http://stackoverflow.com/comment/91249419
comment on: http://stackoverflow.com/a/52149388
has text: @pyd - `pop` extract column from `df` and drop delete it. Extracting means after `a = df.pop('col')` in `a` is Series `col` and in `df` is no column `col`.
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/91414641
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52232068
score: 0
has text: I don't know matplotlib, but it would be easy to use PIL to load & convert the image to greyscale or B & W. And Numpy can easily load PIL images.

http://stackoverflow.com/comment/91341349
type: QuestionComment
has text: You are adding two 'dataframes', but what you want to do is to add two 'columns' from separate dataframes. Just Google 'pandas sum two columns from different dataframes'. And you will find it.
comment on: http://stackoverflow.com/q/52195927
score: 0
type: Comment

http://stackoverflow.com/comment/91477148
type: Comment
type: QuestionComment
score: 0
has text: There must be a reason why you do it this way, but why use globals altogether? Also try/except with pass? You can use some data structure with defaults (dataclass, proper constructor with defaults, or a class).
comment on: http://stackoverflow.com/q/52262659

http://stackoverflow.com/comment/91449901
type: QuestionComment
has text: @ashgetstazered: I know. The point I am moving towards is: tail recursive algorithms are the *easiest* ones to make iterative. That's what the tail recursion optimization is!
comment on: http://stackoverflow.com/q/52250960
score: 0
type: Comment

http://stackoverflow.com/a/52179265
type: Answer
has body: I'm not sure what the issue but try input with quotation marks It's work for me Check the input function if you use it right
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52176457
score: 1
answers question: http://stackoverflow.com/q/52176457
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91561240

http://stackoverflow.com/comment/91451215
type: QuestionComment
comment on: http://stackoverflow.com/q/52250821
has text: Also can show the shape of logits and labels
score: 0
type: Comment

http://stackoverflow.com/comment/91187892
type: Comment
comment on: http://stackoverflow.com/a/52117368
type: AnswerComment
has text: @ezeekiel: sorry, I meant the `certs_list` variable obviously
score: 0

http://stackoverflow.com/comment/91230587
score: 1
comment on: http://stackoverflow.com/q/52140428
type: Comment
type: QuestionComment
has text: The add method should only take two arguments; self, and the thing you're adding to it.

http://stackoverflow.com/a/52269291
has comment: http://stackoverflow.com/comment/91524587
answers question: http://stackoverflow.com/q/52244707
score: 0
has body: For official website, you should install it with conda. anaconda fast.ai To install # Prerequisites Anaconda, manages Python environment and dependencies # Normal installation Download project: git clone https://github.com/fastai/fastai.git Move into root folder: cd fastai Set up Python environment: conda env update Activate Python environment: conda activate fastai If this fails, use instead: source activate fastai # Install as pip package (not recommend) You can also install this library in the local environment using pip pip install fastai However this is not currently the recommended approach, since the library is being updated much more frequently than the pip release, fewer people are using and testing the pip version, and pip needs to compile many libraries from scratch (which can be slow). An alternative is to use the latest Github version with pip pip install git+https://github.com/fastai/fastai.git
type: Answer

http://stackoverflow.com/a/52169666
type: Answer
answers question: http://stackoverflow.com/q/52169506
has comment: http://stackoverflow.com/comment/91289883
downvote count: 1
has comment: http://stackoverflow.com/comment/91289787
has comment: http://stackoverflow.com/comment/91289851
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/91290014
has comment: http://stackoverflow.com/comment/91289924
has body: Add to a string during the loop, return the result: def paper_doll(text): s = '' for i in range(0,len(text)): s += ''.join(text[i]*3) return s print(paper_doll('Hello')) Output: HHHeeellllllooo (I also removed the -1 in range so you get three "o"s)
has comment: http://stackoverflow.com/comment/91290033

http://stackoverflow.com/q/52201744
has comment: http://stackoverflow.com/comment/91375811
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91373808
tagged with: keras
has comment: http://stackoverflow.com/comment/91373265
score: 0
has comment: http://stackoverflow.com/comment/91373847
tagged with: array-broadcasting
answer count: 1
has answer: http://stackoverflow.com/a/52213160
has comment: http://stackoverflow.com/comment/91354505
has comment: http://stackoverflow.com/comment/91373786
has comment: http://stackoverflow.com/comment/91375788
type: UnansweredQuestion
has body: I am trying to convert some categorical features into one hot encodings for use in Keras. However, when I try to map these features, I end up receiving an error indicating the shapes are incompatible. Here is my code: import numpy import pandas from keras.models import Sequential from keras.layers import Dense from sklearn.preprocessing import LabelEncoder from keras.utils import np_utils # load dataset dataframe = pandas.read_csv("data/development.csv") dataset = dataframe.values X = dataset[:,0:7].astype(int) encoder = LabelEncoder() for i in [3,4,5,6]: col = X[i] encoder.fit(col) encoded_col = encoder.transform(col) X[i] = np_utils.to_categorical(encoded_col) # Error is here Y = dataset[:,7].astype(int) And here is the error I'm receiving: ValueError: could not broadcast input array from shape (7,5) into shape (7) Is there anything that I should be doing differently here? I am using Python 3.6, with Keras 2.2.2.
tagged with: python
has title: Numpy/Keras: ValueError: could not broadcast input array from shape (7,5) into shape (7)
has comment: http://stackoverflow.com/comment/91353259

http://stackoverflow.com/q/52136663
tagged with: python
score: 2
type: UnansweredQuestion
has title: How to resume properly the training of a network from a tensorflow checkpoint file?
tagged with: tensorflow
type: Question
has body: I am struggling to restore a model for one day without any success. My code consists of a class TF_MLPRegressor(), where I define the network architecture within the constructor. Then I invoke the fit() function to do the training. So this is how I save a simple Perceptron model with 1 hidden layer within the fit() function: starting_epoch = 0 # Launch the graph tf.set_random_seed(self.random_state) # fix the random seed before creating the Session in order to take effect! if hasattr(self, 'sess'): self.sess.close() del self.sess # delete Session to release memory gc.collect() self.sess = tf.Session(config=self.config) # save the session to predict from new data # Create a saver object which will save all the variables saver = tf.train.Saver(max_to_keep=2) # max_to_keep=2 means to not keep more than 2 checkpoint files self.sess.run(tf.global_variables_initializer()) # ... (each 100 epochs) saver.save(self.sess, self.checkpoint_dir+"/resume", global_step=epoch) Then I create a new TF_MLPRegressor() instance with exactly the same input parameter values and invoke the fit() function to restore the model like this: self.sess = tf.Session(config=self.config) # create a new session to load saved variables ckpt = tf.train.latest_checkpoint(self.checkpoint_dir) starting_epoch = int(ckpt.split('-')[-1]) metagraph = ".".join([ckpt, 'meta']) saver = tf.train.import_meta_graph(metagraph) self.sess.run(tf.global_variables_initializer()) # Initialize variables lhl = tf.trainable_variables()[2] lhlA = lhl.eval(session=self.sess) saver.restore(sess=self.sess, save_path=ckpt) # Restore model weights from previously saved model lhlB = lhl.eval(session=self.sess) print lhlA == lhlB lhlA and lhlB are the last hidden layer weights before and after restoring and according to my code they match completely, namely the saved model is not loaded to the session. What am I doing wrong?
tagged with: deep-learning
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52150215
tagged with: restore
favorite count: 0
upvote count: 3
tagged with: checkpoint

http://stackoverflow.com/comment/102633616
type: Comment
comment on: http://stackoverflow.com/a/52257573
score: 0
type: AnswerComment
has text: @SultanMorbiwala Glad to be able to help you. Upvote the answer if this/any answer is/was helpful to you for the benefit of the future readers.

http://stackoverflow.com/q/52193937
has comment: http://stackoverflow.com/comment/91339512
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91338415
tagged with: docker
linked to: http://stackoverflow.com/q/33315210
has body: When I ran the docker file code below RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends \ ca-certificates \ vim \ git \ python \ python-pip \ curl \ wget \ lsof \ libmysqlclient-dev \ python-dev \ &amp;&amp; \ apt-get clean &amp;&amp; \ rm -rf /var/lib/apt/lists/* #PYTHON requirements ENV HTTPS_PROXY "https://gec-proxy-svr.homeoffice.wal-mart.com:8080/" RUN python --version RUN pip install pip --upgrade RUN pip install setuptools RUN pip install setuptools --upgrade RUN pip install git+https://github.com/PyMySQL/mysqlclient-python.git RUN pip install -r requirements.txt I got this error Running setup.py install for mysqlclient: finished with status 'error' Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-req-build-LIEfN7/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-OFwDUp/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying _mysql_exceptions.py -&gt; build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/__init__.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/compat.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -&gt…
has title: pip install mysqlclient fails on Ubuntu with python 2.7 on docker
tagged with: python
has answer: http://stackoverflow.com/a/52194021
favorite count: 0
has comment: http://stackoverflow.com/comment/91337716
upvote count: 1
tagged with: pip
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52194021
has comment: http://stackoverflow.com/comment/91337711
type: Question

http://stackoverflow.com/q/52234474
answer count: 0
has comment: http://stackoverflow.com/comment/91475796
has comment: http://stackoverflow.com/comment/91541845
has comment: http://stackoverflow.com/comment/91543703
type: Question
has body: Hi I get a string response from an api in the form of shortcode. I want to parse it to html to be pushed to a website that only accepts html or markup I am using python 2.7 I was thinking of writing a description = re.sub('\[vc_sub_header\]','&lt;h1&gt;'description) description = re.sub('\[\\vc_sub_header\]','&lt;h1&gt;'description) but some of the shortcode elements contain a css class which i need to ignore. Here is a snippet of the response I am having to parse: [vc_column_text css=\".vc_custom_1536261801005{margin-bottom: 0px !important;border-bottom-width: 0px !important;padding-bottom: 0px !important;}\"]On 5 September 2018 [/vc_column_text] I want to parse elements ignoring the css text : [vc_column_text css=\".vc_custom_1536261801005{margin-bottom: 0px !important;border-bottom-width: 0px !important;padding-bottom: 0px !important;}\"] to &lt;p&gt; I was thinking of using regex but it is difficult becasue I don't know how to ignore the css part.
has comment: http://stackoverflow.com/comment/91456995
has comment: http://stackoverflow.com/comment/91468508
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/91462119
tagged with: shortcode
has comment: http://stackoverflow.com/comment/91460160
has comment: http://stackoverflow.com/comment/91475940
type: UnansweredQuestion
has title: Python shortcode to html
tagged with: python
tagged with: regex

http://stackoverflow.com/comment/91195229
has text: @Offofue Changjng a large library from synchronous or threaded or whatever to asyncio-based without radically changing the API seems like it would be a huge task, so I wouldn’t be surprised if some of the docs are lagging. If the function returns an awaitable that when awaited gives you a `TotalList`, but the docs say it directly returns a `TotalList`, that might be a docs bug that you could file and they could fix. But again, this is just a wild guess about a library I don’t know, so… hopefully someone else knows more. (But: does the code _work_, if you don’t try to type check it?)
type: QuestionComment
comment on: http://stackoverflow.com/q/52121291
score: 0
type: Comment

http://stackoverflow.com/comment/91465635
type: Comment
has text: (*Spyder maintainer here*) Please post a simple example of a Qt app that doesn't enter into breakpoints.
type: QuestionComment
comment on: http://stackoverflow.com/q/52258924
score: 2

http://stackoverflow.com/comment/91336885
has text: Actually, when I tested out the program, it seems that I only need to put in the folder's-folder's name and then the filename to load my image from the folder's folder; trying to put my folder's name and my folder's-folder's name would just give an error.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52181069

http://stackoverflow.com/a/52134593
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52134576
upvote count: 3
score: 3
has body: You can make use of the sum along the first axis: res = df.groupby('id').agg('sum') res.div(res.sum(1), 0) A B id 1 0.666667 0.333333 2 0.625000 0.375000 3 0.526316 0.473684

python-2.7
tags question: http://stackoverflow.com/q/52234474
tags question: http://stackoverflow.com/q/52119879
tags question: http://stackoverflow.com/q/52149331
tags question: http://stackoverflow.com/q/52255550
tags question: http://stackoverflow.com/q/52254186
tags question: http://stackoverflow.com/q/52210577
tags question: http://stackoverflow.com/q/52196721
tags question: http://stackoverflow.com/q/52264242
tags question: http://stackoverflow.com/q/52253543
tags question: http://stackoverflow.com/q/52184211
tags question: http://stackoverflow.com/q/52222205
tags question: http://stackoverflow.com/q/52264886
tags question: http://stackoverflow.com/q/52250375
tags question: http://stackoverflow.com/q/52165285
tags question: http://stackoverflow.com/q/52194205
tags question: http://stackoverflow.com/q/52179520
tags question: http://stackoverflow.com/q/52157214
tags question: http://stackoverflow.com/q/52239956
tags question: http://stackoverflow.com/q/52135497
tags question: http://stackoverflow.com/q/52251292
tags question: http://stackoverflow.com/q/52167220
tags question: http://stackoverflow.com/q/52195269
tags question: http://stackoverflow.com/q/52233215
tags question: http://stackoverflow.com/q/52182951
tags question: http://stackoverflow.com/q/52236933
tags question: http://stackoverflow.com/q/52175987
tags question: http://stackoverflow.com/q/52240668
tags question: http://stackoverflow.com/q/52115748
tags question: http://stackoverflow.com/q/52133732
tags question: http://stackoverflow.com/q/52155425
tags question: http://stackoverflow.com/q/52173005
tags question: http://stackoverflow.com/q/52146184
tags question: http://stackoverflow.com/q/52197465
tags question: http://stackoverflow.com/q/52157372
tags question: http://stackoverflow.com/q/52140641
tags question: http://stackoverflow.com/q/52203828
tags question: http://stackoverflow.com/q/52135993
tags question: http://stackoverflow.com/q/52157505
tags question: http://stackoverflow.com/q/52178332
tags question: http://stackoverflow.com/q/52173523
tags question: http://stackoverflow.com/q/52227838
tags question: http://stackoverflow.com/q/52237810
tags question: http://stackoverflow.com/q/52166976
tags question: http://stackoverflow.com/q/52174027
tags question: http://stackoverflow.com/q/52210222
tags question: http://stackoverflow.com/q/52189260
tags question: http://stackoverflow.com/q/52209035
tags question: http://stackoverflow.com/q/52125707
tags question: http://stackoverflow.com/q/52174019
tags question: http://stackoverflow.com/q/52164640
tags question: http://stackoverflow.com/q/52166051
tags question: http://stackoverflow.com/q/52169501
tags question: http://stackoverflow.com/q/52242506
tags question: http://stackoverflow.com/q/52149113
tags question: http://stackoverflow.com/q/52147373
tags question: http://stackoverflow.com/q/52215642
tags question: http://stackoverflow.com/q/52218031
tags question: http://stackoverflow.com/q/52183451
tags question: http://stackoverflow.com/q/52242966
tags question: http://stackoverflow.com/q/52262147
tags question: http://stackoverflow.com/q/52113696
tags question: http://stackoverflow.com/q/52194235
tags question: http://stackoverflow.com/q/52132514
tags question: http://stackoverflow.com/q/52243734
tags question: http://stackoverflow.com/q/52219956
tags question: http://stackoverflow.com/q/52270179
tags question: http://stackoverflow.com/q/52180315
tags question: http://stackoverflow.com/q/52220794
tags question: http://stackoverflow.com/q/52234171
tags question: http://stackoverflow.com/q/52221874
tags question: http://stackoverflow.com/q/52178129
tags question: http://stackoverflow.com/q/52151906
tags question: http://stackoverflow.com/q/52244164
tags question: http://stackoverflow.com/q/52133523
tags question: http://stackoverflow.com/q/52177830
tags question: http://stackoverflow.com/q/52160225
tags question: http://stackoverflow.com/q/52180216
tags question: http://stackoverflow.com/q/52180117
tags question: http://stackoverflow.com/q/52246833
tags question: http://stackoverflow.com/q/52137230

http://stackoverflow.com/q/52250100
tagged with: python
tagged with: generative-adversarial-network
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52251261
has title: Selectively Optimizing a Keras Model with Tensorflow
tagged with: tensorflow
type: Question
tagged with: keras
has body: I'm creating a GAN (generative adversariel network) using both Tensorflow and Keras. The issue that occurs is when I attempt to pass my list of generator training parameters into the vars_list for the training step. My generator looks like def create_generator(z_noise): #build layer one l1 = Dense(h1_size)(z_noise) L1 = LeakyReLU(0.1)(l1) #layer 2 l2 = Dense(h2_size)(L1) L2 = LeakyReLU(0.1)(l2) #layer 3 l3 = Dense(h3_size)(l2) #generated data x_generate = sigmoid(l3) #params g_params = [l1, L1, l2, L2, l3] return x_generate, g_params The x_generate is then passed into the discriminator which is still written in Tensorflow and yet to be converted to keras. That portion works correctly up until I pass in the optimization parameters. #generate the nets x_generated, g_params = create_generator(z_prior) y_data, y_generated, d_params = create_discriminator(x_data, x_generated, keep_prob) #declare loss functions d_loss = - (tf.log(y_data) + tf.log(1 - y_generated)) # inverted due to inability to do normal maximization g_loss = - tf.log(y_generated) #optimizer optimizer = tf.train.AdamOptimizer(learning_rate=0.0001) d_trainer = optimizer.minimize(d_loss, var_list=d_params) g_trainer = optimizer.minimize(g_loss, var_list=g_params) The outcome is an error stating NotImplementedError: ('Trying to update a Tensor ', &lt;tf.Tensor 'dense_4/BiasAdd:0' shape=(256, 20) dtype=float32&gt;) on the line g_trainer = optimizer.minimize(loss, var_list=g_params)
score: 0
accepted answer: http://stackoverflow.com/a/52251261
answer count: 1

http://stackoverflow.com/a/52262370
score: 4
answers question: http://stackoverflow.com/q/52261904
type: AcceptedAnswer
type: Answer
upvote count: 4
has body: The issue is that calling .format on the string is causing one set of the double braces to be removed: &gt;&gt;&gt; 'entity/{{ ds_nodash }}.0.{}.json'.format(filename) 'entity/{ ds_nodash }.0.foobar.json' You need to escape the braces that you want to be in the string by doubling them: &gt;&gt;&gt; 'entity/{{{{ ds_nodash }}}}.0.{}.json'.format(filename) 'entity/{{ ds_nodash }}.0.foobar.json'
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52261904

http://stackoverflow.com/q/52124584
has comment: http://stackoverflow.com/comment/91200970
has answer: http://stackoverflow.com/a/52124612
accepted answer: http://stackoverflow.com/a/52124612
tagged with: python
has comment: http://stackoverflow.com/comment/91201648
has comment: http://stackoverflow.com/comment/91201651
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91201630
has answer: http://stackoverflow.com/a/52125910
has title: How to transform a list of 1-D ndarray to 2-D ndarray (mxnet ndarray)
type: Question
tagged with: numpy
tagged with: mxnet
has comment: http://stackoverflow.com/comment/91201534
has comment: http://stackoverflow.com/comment/91201633
has comment: http://stackoverflow.com/comment/91201682
upvote count: 2
tagged with: numpy-ndarray
answer count: 2
has comment: http://stackoverflow.com/comment/91200493
possible better answer: http://stackoverflow.com/a/52125910
favorite count: 0
has body: In this example, I have a list of 1-d ndarray, with length 9, the list has 9 elements, and each one has shape=(2048,), so totally 9 * (2048,), I get these ndarray from mxnet so that each of the ndarray is &lt;NDArray 2048 @cpu(0)&gt; the array dtype=numpy.float32 If I use np.asarray to transform this list, it becomes the following result shape=&lt;class 'tuple'&gt;: (9, 2048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) Obviously, I want a 2-D array, with shape=(9, 2048), how to solve this problem? ps: I discover this problem by saving a npy file and load it. I directly saved the list before converting it to a ndarray (so the np.save would transform the list to the ndarrary automatically) and after I loaded it, I found the shape has become something above, which is really abnormal The answer below, np.vstack and np.array both works for the common list to ndarray problem but could not solve mine, so I doubt it is some special case of mxnet

http://stackoverflow.com/comment/91308347
has text: @Ev.Kounis You could build a suffix-tree from the keys (takes O(n) time), after that checking if a key appears in the tree takes O(m) time where `m` is the number of characters in the key,. Also: it is possible to obtain all keys that contain that given key in this way. So the algorithm would take O(n) + O(n*m) and m is probably some constant.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52178792

http://stackoverflow.com/comment/91360133
comment on: http://stackoverflow.com/a/52203447
has text: Split the quads? ;)
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/q/52169356
tagged with: pybind11
has comment: http://stackoverflow.com/comment/91308869
has comment: http://stackoverflow.com/comment/91296187
upvote count: 1
has comment: http://stackoverflow.com/comment/91290657
has comment: http://stackoverflow.com/comment/91296321
has comment: http://stackoverflow.com/comment/91293089
favorite count: 0
tagged with: python
has title: pybind11 how to add C++ dependencies using setup.py
tagged with: c++
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/91291414
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91293209
has body: (I am new to Python and Python binding) I have a C++ package which uses FCL library, and its data types. The code is working in C++, but when I try to use Pybind11 to access it in Python, it compiles without error, but when I import it in Python I get the error: undefined symbol: _ZTVN3fcl3BoxE Heres my setup.py from distutils.core import setup, Extension def get_pybind_include(): import pybind11 return pybind11.get_include() import sys extra_compile_args = ['--std=c++11','-lfcl','-libccd'] ext_modules = [Extension('Coll', ['src/Coll.cpp'], library_dirs=['lib'], include_dirs=['include', get_pybind_include()], language='c++', extra_compile_args=extra_compile_args), ] setup(name='Coll', version='0.1', description='Python bindings for the Coll v1', setup_requires=['fcl'], ext_modules=ext_modules, ) Seems to be problem with linking FCL library, how can I make sure its linked? EDIT: I am on virtual environment, not sure if this has effect.
tagged with: c++11
has comment: http://stackoverflow.com/comment/91291739
type: Question
has comment: http://stackoverflow.com/comment/91294366

http://stackoverflow.com/a/52134887
downvote count: 0
type: AcceptedAnswer
score: 4
accepted answer of: http://stackoverflow.com/q/52132506
answers question: http://stackoverflow.com/q/52132506
has body: The SSL error was because Python 3.7 does not rely on MacOS' openSSL anymore. It comes with its own openSSL bundled and doesn't have access on MacOS' root certificates. So all I needed to do was run the following command- /Applications/Python\ 3.7/Install\ Certificates.command
type: Answer
upvote count: 4

http://stackoverflow.com/comment/91355568
has text: You may also wish to verify that [`os.path.isdir(pathtodir)`](https://docs.python.org/3/library/os.path.html#os.path.isdir) is true, to make sure it's a directory and not a regular file.
type: AnswerComment
type: Comment
score: 2
comment on: http://stackoverflow.com/a/52203277

http://stackoverflow.com/a/52203018
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52202607
answers question: http://stackoverflow.com/q/52202607
score: 1
upvote count: 1
has body: You almost never need eval() — it can be evil. In this case just use functools.reduce() on your list of columns / expressions: sa.select([reduce(operator.add, [table.c.col1, table.c.col2, 'done'])])
type: AcceptedAnswer

http://stackoverflow.com/a/52283649
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52203953
has body: result of kb 0:000&gt; kb # ChildEBP RetAddr Args to Child 00 000bf618 76fa0e00 7ffdf000 7ffda000 76ff714c ntdll!LdrpDoDebuggerBreak+0x2c 01 000bf778 76f860a7 000bf7ec 76f20000 76c245cb ntdll!LdrpInitializeProcess+0x11a9 02 000bf7c8 76f83659 000bf7ec 76f20000 00000000 ntdll!_LdrpInitialize+0x78 03 000bf7d8 00000000 000bf7ec 76f20000 00000000 ntdll!LdrInitializeThunk+0x10 when i click on the dml link 02 i get 0:000&gt; dx Debugger.Sessions[0].Processes[2684].Threads[3736].Stack.Frames[2].SwitchTo();dv /t /v Debugger.Sessions[0].Processes[2684].Threads[3736].Stack.Frames[2].SwitchTo() Unable to enumerate locals, Win32 error 0n87 Private symbols (symbols.pri) are required for locals. Type ".hh dbgerr005" for details. as i emphasized in my earlier answers the same can be achieved by dx @$curstack.Frames[2].SwitchTo();dv /v /t typing this is exactly equivalent to clicking the 02 link 0:000&gt; dx @$curstack.Frames[2].SwitchTo();dv /v /t @$curstack.Frames[2].SwitchTo() Unable to enumerate locals, Win32 error 0n87 Private symbols (symbols.pri) are required for locals. Type ".hh dbgerr005" for details. this will be meaningful only if you are debugging with source available here is an example of stack and frame 2 with source i am using kbL to hide my src line info on the stacktrace and then clicked frame no 2 DML link and then type the command as you can see it print the same info like you click now if you say i need to see the "RUN" string not use the number 2 you should write a script to text parse each line as i showed you in my earlier answer to the thread you linked 0:000&gt; kbL # ChildEBP RetAddr Args to Child 00 (Inline) -------- -------- -------- -------- mfctest!CThreadLocal&lt;_AFX_THREAD_STATE&gt;::GetData 01 0025fe48 012fbc2f 015bf7a8 012fd4bd ffffffff mfctest!AfxGetThreadState 02 0025fe64 0151979e 00000000 015c6360 7ffdb000 mfctest!CWinThread::Run+0xf 03 0025fe7c 014c17d5 012e0000 00000000 00322d3e mfctest!AfxWinMain+0x93 04 (Inline) -------- -------- -------- …

http://stackoverflow.com/comment/104710679
has text: Did you find the work around for your problem? Would be great if you could share any insights
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52143172
score: 0

http://stackoverflow.com/a/52118586
has body: not sure why you used main text = ... INSTEAD of just text = ... or main_text = ... and also looks like you have an extra parenthesis at the end.... so, if you want to get a string from the user and store it in a variable text you should rewrite your statement like this: IF you are using Python3: text = input("Type a message: ") IF you are using Python2: text = raw_input("Type a message: ") Please specify what version of python you are using next time you ask so it's easier for us to answer :) (You can check the version you are running with import sys; print(sys.version))
score: 0
answers question: http://stackoverflow.com/q/52118075
type: Answer

http://stackoverflow.com/comment/91422549
type: Comment
comment on: http://stackoverflow.com/a/52236993
score: 0
type: AnswerComment
has text: Thanks now it works, please could you give me a more detailed answer what, theoretically, you were doing with the Imputer() function? I was wondering why in Panda that replace with 9999 worked well.

http://stackoverflow.com/comment/91423233
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52231442
has text: one method I was thinking of doing was generating all possible permutations of points and finding the permutation or permutations with the maximum amount of elements represented, which is in a way a kind of graph traversal.
score: 0

http://stackoverflow.com/q/52240338
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/91429885
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91429906
has body: Read one character at a time from the file, ignoring everything to get "<"(ignore "<" as well). Read one character at a time, appending them to a string until ">" or white space(ignore ">" as well) the expected output should be : [....html,body,h1,/h1,/h2,/body,.....] pretty much get all the tags from the document Title Q2. HTML TAG CHECKER A markup language is a language that annotates text so that the computer can manipulate the text. Most markup languages are human readable because the annotations are written in a way to distinguish them from the text. The most important feature of a markup language is that the tags it uses to indicate annotations should be easy to distinguish from the document content. One of the most well-known markup languages is the one commonly used to create web pages, called HTML, or "Hypertext Markup Language". In HTML, tags appear in "angle brackets" such as in " ". When you load a Web page in your browser, you do not see the tags themselves: the browser interprets the tags as instructions on how to format the text for display. Most tags in HTML are used in pairs to indicate where an effect starts and ends. For example: this is a paragraph of text written in HTML Here represents the start of a paragraph, and indicates where that paragraph ends. Other tags include and that are used to place the enclosed text in bold font, and and indicate that the enclosed text is italic. Note that "end" tags look just like the "start" tags, except for the addition of a backslash ‘/’after the < symbol. Sets of tags are often nested inside other sets of tags. For example, an ordered list is a list of numbered bullets. You specify the start of an ordered list with the tag , and the end with . Within the ordered list, you identify items to be numbered with the tags (for "list item") and . For example, the following specification: First item Second item Third item would result in the following: First item Second item Third item Stack.py: class Stack: def __in…
tagged with: html-parsing
has title: extract html tags using Stack implementation using python
type: Question
has comment: http://stackoverflow.com/comment/91429653
has comment: http://stackoverflow.com/comment/91429853
score: 0

http://stackoverflow.com/q/52238164
has body: Here is my basic program I am running with a local jupyter notebook on my computer. I am not sure how to resolve this dll error: import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt %matplotlib inline Here is the error message accompanying my code: ImportError Traceback (most recent call last) &lt;ipython-input-1-c1680853bc3a&gt; in &lt;module&gt;() 1 import numpy as np 2 import matplotlib as mpl ----&gt; 3 import matplotlib.pyplot as plt 4 #%matplotlib inline c:\python27\lib\site-packages\matplotlib\pyplot.py in &lt;module&gt;() 29 from cycler import cycler 30 import matplotlib ---&gt; 31 import matplotlib.colorbar 32 from matplotlib import style 33 from matplotlib import _pylab_helpers, interactive c:\python27\lib\site-packages\matplotlib\colorbar.py in &lt;module&gt;() 30 31 import matplotlib as mpl ---&gt; 32 import matplotlib.artist as martist 33 import matplotlib.cbook as cbook 34 import matplotlib.collections as collections c:\python27\lib\site-packages\matplotlib\artist.py in &lt;module&gt;() 14 import matplotlib 15 from . import cbook, docstring, rcParams ---&gt; 16 from .path import Path 17 from .transforms import (Bbox, IdentityTransform, Transform, TransformedBbox, 18 TransformedPatchPath, TransformedPath) c:\python27\lib\site-packages\matplotlib\path.py in &lt;module&gt;() 19 import numpy as np 20 ---&gt; 21 from . import _path, rcParams 22 from .cbook import (_to_unmasked_float_array, simple_linear_interpolation, 23 maxdict) ImportError: DLL load failed: %1 is not a valid Win32 application.
tagged with: dllimport
answer count: 0
has comment: http://stackoverflow.com/comment/91425187
tagged with: matplotlib
type: Question
has comment: http://stackoverflow.com/comment/91425136
tagged with: dll
has comment: http://stackoverflow.com/comment/91424976
score: 0
has title: Need help dealing with a DLL error based on matplotlib.pyplot
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/64240549
type: Answer
has body: The solution is the ErrorMessage that you got which says ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting) django.core.exceptions.ImproperlyConfigured: The INSTALLED_APPS setting must be a list or a tuple. Change your installed apps datatype to a list by changing your {} to [].
answers question: http://stackoverflow.com/q/52251907
score: 0

http://stackoverflow.com/comment/99494820
score: 0
comment on: http://stackoverflow.com/a/53413172
type: AnswerComment
has text: Based on my experience, do not do it in Windows. Do it in Linux. Don't get the zip files but rather use the RPMs to install. Get the basiclite version. The basic one will exceed 50MB lambda limit when zipped up. You'll have to add /lib64/libaio* files o /usr/lib/oracle/.../lib. Relax permissions on the files in the lib folder, and then zip them up - zip --symlinks -r9 ~/lamda.zip *
type: Comment

http://stackoverflow.com/a/52269227
downvote count: 0
answers question: http://stackoverflow.com/q/52268817
score: 1
has body: you can convert the timestamp column value to time only. using below example: df['date_time'].dt.time Then add the two columns having same type i.e timedelta. df['new_time'] = df['first_time'] + df['date_time']
type: Answer
upvote count: 1

http://stackoverflow.com/q/52135392
has comment: http://stackoverflow.com/comment/91220716
has title: Reshape dictionary values from 1D to 2D array
tagged with: python
has comment: http://stackoverflow.com/comment/91220742
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52135480
accepted answer: http://stackoverflow.com/a/52135480
type: Question
has answer: http://stackoverflow.com/a/52135484
possible better answer: http://stackoverflow.com/a/52135484
answer count: 2
upvote count: 1
tagged with: arrays
has body: I want to calculate cosine similarity for words in two dictionaries. The words are keys, arrays are values. In order to do this, I need to convert them to 2D array first, I did some research and found x = x.reshape(1,-1) I successfully converted it with a single value in dictionary, however, I don't know how to convert the whole dictionary's values by using for loops. The data D {'A': array([ 4.80625004e-01, -1.40245005e-01, -9.99999046e-03]), 'B': array([-0.46553 , -0.1519755 , 0.41836]), 'C': array([0.0090175 , 0.05817001, -0.09712502])} D2 (same format as D) {'D': ([8.11059952e-01, 6.84859991e-01, 1.01619996e-01]), 'E':([-0.82868 , 0.49513 , 0.67581]), 'F':([-0.17093 , 0.88746 , 0.0931135])} I tried for i in D2.items(): D2[i] = D2[i].reshape(1, -1) #Error on this line but received error: TypeError: unhashable type: 'numpy.ndarray' Some advice please? thank you in advanced!
favorite count: 0

http://stackoverflow.com/q/52167284
answer count: 2
has comment: http://stackoverflow.com/comment/91284979
upvote count: 0
has body: i have a lot of csv files with date, row[0] = is date in format: year-month-date, and i have output from this files. for row in reader: out = row[0], row[2] + "/" + row[3], row[5] print(out) out example: ('2018-07-21', 'info1', 'info2') ('2018-03-19', 'info1', 'info2') ('2018-07-14', 'info1', 'info2') ('2018-05-16', 'info1', 'info2') ('2018-01-27', 'info1', 'info2') how i can sort this output by date, or add this rows to list and sort in list, but i have output from files in tuple. thank you for help
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/52167569
tagged with: python
has comment: http://stackoverflow.com/comment/91284819
possible better answer: http://stackoverflow.com/a/52167544
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91284945
has answer: http://stackoverflow.com/a/52167544
has title: Sort output from csv files by date python
accepted answer: http://stackoverflow.com/a/52167569
downvote count: 3
score: -3
type: Question
has comment: http://stackoverflow.com/comment/91285059
has comment: http://stackoverflow.com/comment/91285112
has comment: http://stackoverflow.com/comment/91284452

http://stackoverflow.com/q/52175803
has answer: http://stackoverflow.com/a/52175835
has comment: http://stackoverflow.com/comment/91302347
type: Question
score: -2
has body: How print(n) will be executed? def rec(n): if n&gt;0: rec(n-1) #here it is used to call rec(9) again how 'print(n)'will execute print(n) rec(10)
possible better answer: http://stackoverflow.com/a/52175901
has title: recursion for printing numbers
has answer: http://stackoverflow.com/a/52175901
answer count: 2
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/91302272
has comment: http://stackoverflow.com/comment/91302290
favorite count: 0
has comment: http://stackoverflow.com/comment/91302301
has comment: http://stackoverflow.com/comment/91302286
accepted answer: http://stackoverflow.com/a/52175835
tagged with: python
type: AnsweredQuestion
tagged with: recursion

http://stackoverflow.com/comment/91333908
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52191948
has text: "I'd like to expose some of the private members of Scenario to Python scripts -- without using the explicit getter/setter functions:" - *Why*? Why wouldn't you want to use the getter functions to get data from the object? That makes no sense to me.
type: Comment

http://stackoverflow.com/a/52208894
answers question: http://stackoverflow.com/q/52208802
has body: There's no need to iterate your dictionary. Just access the appropriate dictionary item directly. If you need to deal with KeyError, you can use a try / except clause: def year_info(year, yearly_weather): try: k = year v = yearly_weather[k] return "{:&lt;8.0f}| {:&lt;18.2f}| {:&gt;12.2f} | {:&gt;10.2f} | {:&gt;10.0f}| {:&gt;10.0f}" .format(k, *v) except KeyError: return "{:^8s}| {:^18s}| {:^12s} | {:^10s} | {:^10s} | {:^10s}".format(*['N/A']*6) Result res = year_info(1965, yearly_weather) '1965 | 43.00 | 33.00 | 0.27 | 1| 1'
has comment: http://stackoverflow.com/comment/91367320
accepted answer of: http://stackoverflow.com/q/52208802
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91367344
score: 3
upvote count: 3

http://stackoverflow.com/comment/91414343
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52232548
has text: Use `if not any([not phone, not password, not age, not name]):`

http://stackoverflow.com/comment/91315016
has text: Also, I tentatively retract my statement about the RBM implementation being bugged. After having read [this paper](http://www.jmlr.org/papers/v11/erhan10a.html), I think that a) the layer sizes are too small, and b) the number of training samples is way, way too low. Have a look at Fig. 9 and 11.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52166308
score: 1

http://stackoverflow.com/comment/91380914
score: 0
type: QuestionComment
has text: using raw you need to generate procedure args by format string, but when you callproc you send the args by second parameter.
type: Comment
comment on: http://stackoverflow.com/q/52215941

http://stackoverflow.com/q/52207582
accepted answer: http://stackoverflow.com/a/52207921
has body: I have a pandas data frame 'train' as Name Comb Sales Joy A123 102 John A134 112 Aby A123 140 Amit A123 190 Andrew A134 210 Pren A123 109 Abry A134 230 Hulk A134 188 ... For each unique Comb I want to find the 25% quantiles of the corresponding sales and create respective bins. For example if you create 25% quantile bins for the sales of Comb='A123' you will get (102.00 107.25 124.50 152.50 190.00). Now I want to bin my sales for all Comb='A123' using these quantiles. My resulting data would be Name Comb Sales Bin Bin_Low Bin_High Joy A123 102 1 102 107.25 John A134 112 1 112 169 Aby A123 140 3 124.50 152.50 Amit A123 190 4 152.90 190 Andrew A134 210 3 199 215 Pren A123 109 2 107.25 124.50 Abry A134 230 4 215 230 Hulk A134 188 2 169 199 I created the below code but my final data frame does not come out in the right format. quant = pd.DataFrame() i = '' for i in train.comb.unique(): a=pd.qcut(train[train.comb == i ]['Sales'], 4,duplicates='drop') df = pd.DataFrame(np.array(a)) comp=pd.concat([train[train.combo == i ],df], axis=1) quant=quant.append(comp) Any help would be appreciated.
tagged with: quantile
tagged with: pandas
answer count: 1
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52207921
tagged with: python
type: AnsweredQuestion
upvote count: 1
type: Question
has title: Binning a pandas column based on quantiles
has comment: http://stackoverflow.com/comment/91365017

http://stackoverflow.com/comment/91338681
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52194291
has text: What is `it`? Do you mean `id`?

http://stackoverflow.com/q/52261694
has comment: http://stackoverflow.com/comment/91471487
type: UnansweredQuestion
has body: I'm looking for a way to update lots of rows in a DB(100K+). I'm connecting to the db remotely and updating the rows but it takes way to much time. If i download the db to my local machine and update them rows there its fast. I'm looking for a way to process the db on my computer then send only the changed part like all together. For example I can write a script which would download the db and edit it on my local machine then send it back and that takes way less time than doing the update. What I'm looking for is sending back only the column where the edit takes place and insert it into the server machine. Update: Looks like its not the update script which is causing the bottlenect. Still need to find a way to figure it out whats causing the bottleneck
has comment: http://stackoverflow.com/comment/91471034
has comment: http://stackoverflow.com/comment/91471230
has comment: http://stackoverflow.com/comment/91472437
tagged with: database
tagged with: mysql
type: Question
score: 0
tagged with: python
has title: MYSQL remote update is slow
answer count: 0

http://stackoverflow.com/comment/93176924
comment on: http://stackoverflow.com/a/53141558
score: 0
type: AnswerComment
type: Comment
has text: Thanks for the information you shared. I can't use classification for my problem as I need the exact value as forecast not the direction of it.

http://stackoverflow.com/a/52253221
score: 1
answers question: http://stackoverflow.com/q/52166911
has body: Assignment operation returns a tensor and you need to use it, otherwise you are not interested in the assignment itself (from the TF's point of view). Changing your mandelbrot_ code this way: # part of the code in the end of mandelbrot_ function with tf.control_dependencies(l): n__ = n_.assign(l[0]) x__ = x_.assign(l[1]) y__ = y_.assign(l[2]) return ( graph, # graph (x, y), # inputs (n__, x__, y__), # outputs (n_, x_, y_) # variables ) It now returns outputs (results of assignment) and variables. Also changed mandelbrot function to initialize variables returned in additional tuple: def mandelbrot(x, y): """ Compute number of iterations of the Mandelbrot function at (x,y). """ g, in_, out_, vars_ = mandelbrot_() x_in, y_in = in_ n_out, x_out, y_out = out_ n_var, x_var, y_var = vars_ with tf.Session(graph=g).as_default() as session: # initialize vars with null values feed0 = { x_in:0.0, y_in:0.0 } session.run(n_var.initializer, feed0) session.run(x_var.initializer, feed0) session.run(y_var.initializer, feed0) # run the graph at the chosen point feed = { x_in:x, y_in:y } n_out, x_out, y_out = session.run(out_, feed) print("({0},{1}): {2}".format(x, y, [n_out, x_out, y_out])) And now running mandelbrot(0.25, -0.15) produces (0.25,-0.15): [255, 0.22613873, -0.2738613] output.
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91477945
type: Answer
accepted answer of: http://stackoverflow.com/q/52166911

http://stackoverflow.com/a/52149161
upvote count: 3
has body: You have CSV data, you can use the csv module: import csv with open('your file', 'r', newline='', encoding='utf8') as fp: rows = csv.reader(fp, delimiter=' ') # generator comprehension errors = (row for row in rows if row[4] == '1') for error in errors: print(error)
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52148942
score: 3

http://stackoverflow.com/comment/91345930
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52196843
has text: Hi, you should try to create the minimal example when asking a question. See [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). Your question here is about `"There is an upcoming task in %d days at %d cluster!" %a %cluster`, so that is actually the only part of your code which is relevant. You should not include various `tkinter`, `random` etc. in the question just because you have them in the file.
score: 0

http://stackoverflow.com/comment/91360317
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52205005
has text: You're welcome. Another thing to review would be `All values on the Y axis sum to 1` requirement. It doesn't make much sense. Usually normalization requirement is integral of the function from 0 to max value is equal to 1
type: Comment

http://stackoverflow.com/q/52245499
has comment: http://stackoverflow.com/comment/91439237
has comment: http://stackoverflow.com/comment/91439198
has comment: http://stackoverflow.com/comment/91439214
has comment: http://stackoverflow.com/comment/91439179
type: Question
has answer: http://stackoverflow.com/a/52245628
answer count: 1
has title: Choosing data structure in Python
tagged with: data-structures
favorite count: 0
has comment: http://stackoverflow.com/comment/91439368
score: 1
accepted answer: http://stackoverflow.com/a/52245628
has comment: http://stackoverflow.com/comment/91439321
upvote count: 2
has comment: http://stackoverflow.com/comment/91439442
tagged with: python
has comment: http://stackoverflow.com/comment/91439397
has body: I want to manipulate data of this form: {red -&gt; 1,5,6,7,5,11,...} {green -&gt; 2,3,4,10,11,12,...} {blue -&gt; 2,3,5,6,7,8,9,10,...} where colors are keys, and numbers are, let's say, some locations (non-key integer values). I'll have a lot of colors, and a lot of associated numbers. I want to perform operations like total number of colors, top 5 colors with most numbers in it, etc. What data structures in Python can you suggest to use (which stores key value and associated non key entries)? I know this is a broad question. I'm trying to solve this problem, if that helps. PS. I'm trying to follow online course. And that is not a hw. Even if that was a hw, my question is not asking for a solution, i guess. EDIT that data collection contains a lot of small txt files with some text in it. In data structure, eventually I want to save unique words from all that txt files along with pointers to documentid's where those words appear. Ex: 1.txt "The weather today is good" 2.txt "It is going to rain today" data structure should be (numbers are docid's) { The-&gt;1 weather-&gt;1 today-&gt;1,2 is-&gt;1,2 good-&gt;1 it-&gt;2 going-&gt;2 to-&gt;2 rain-&gt;2
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91439348

http://stackoverflow.com/a/52170781
type: AcceptedAnswer
downvote count: 0
has body: Using join df.array=df.array.apply(' '.join) df Out[211]: id array 0 1 2 3 4 1 2 5 2 3 6 7 8 Update pd.concat([df,pd.DataFrame(df.array.tolist())],1) Out[249]: id array 0 1 2 0 1 [2, 3, 4] 2 3 4 1 2 [5] 5 None None 2 3 [6, 7, 8] 6 7 8
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/52170723
answers question: http://stackoverflow.com/q/52170723
has comment: http://stackoverflow.com/comment/91311732
upvote count: 3

http://stackoverflow.com/q/52243451
favorite count: 0
score: -1
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52247172
tagged with: matplotlib
type: Question
tagged with: numpy
upvote count: 0
answer count: 1
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/52247172
has body: For example, i have the following data frame in pandas cleaned and ready for merging. DataFrame1 for average Income per year Country | Year 1 | Year 2 | Year 3 A | 50 | 30 | 20 B | 70 | 20 | 90 C | 10 | 20 | 30 Dataframe2 for Fertility rate Country | Year 1 | Year 2 | Year 3 A | 1.5 | 2 | 2.5 B | 2 | 2 | 3 C | 1 | 1 | 4 Basically im trying to show the relationship between DataFrame1 and DataFrame2 over the years on matplotlib. But i cant seem to merge them as they have the same headings as Years? In addition, i just cant seem to find a graph for me to compare these data on matplotlib when trying to use the X axis as the years.Any advice wold be great as im using the values above as the datasets are huge. Could it be that the data is too much?
has title: merging and visualization of datasets using pandas

http://stackoverflow.com/comment/91230716
score: 0
type: AnswerComment
type: Comment
has text: @ToobaAftab: It doesn't matter how many things you're adding together; each `+` in `a+b+c` only has two arguments.
comment on: http://stackoverflow.com/a/52140482

http://stackoverflow.com/comment/91330326
score: 0
type: Comment
type: QuestionComment
has text: I want the output of each timestep from LSTM for debugging. Hence using return_sequences.
comment on: http://stackoverflow.com/q/52189093

http://stackoverflow.com/q/52265558
upvote count: 1
tagged with: python
has body: I am implementing a Deep Q network (with fixed Q target), which requires to assign the parameters from a network to another (prediction network and target network, have the same parameter). I am using a convolutional network, so I use some API like: tf.layers.conv2d tf.layers.dense and so on. Is there a good way to do this? Thank you!
score: 1
tagged with: tensorflow
type: Question
tagged with: neural-network
downvote count: 0
has comment: http://stackoverflow.com/comment/91794260
tagged with: reinforcement-learning
favorite count: 0
answer count: 0
has title: tensorflow copy parameters to another network(same architecture), like DQN
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91552215

http://stackoverflow.com/q/52238877
accepted answer: http://stackoverflow.com/a/52238927
tagged with: python
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91430776
upvote count: 3
tagged with: dataframe
tagged with: numpy
has comment: http://stackoverflow.com/comment/91442143
score: 2
has answer: http://stackoverflow.com/a/52238927
has comment: http://stackoverflow.com/comment/91426444
has title: How to add a nested column to a 3D Pandas DataFrame?
tagged with: pandas
type: AnsweredQuestion
has body: New to Pandas, not very sure how the 3D DataFrame works. My dataframe, called 'new' looks like this: unique cat numerical a b c d e f 0 0 1 2 3 4 5 1 0 1 2 3 4 5 I want to insert column 'z' so that it ends up like this: unique cat numerical a b z c d e f 0 0 1 9 2 3 4 5 1 0 1 9 2 3 4 5 I successfully made a new column after slicing out 'unique' from my dataframe: Doing this: new_column = new.loc[:,'unique'].assign(z=pd.Series([9,9]).values) Gets me this: a b z 0 0 1 9 1 0 1 9 However I have no idea how to put it back into the dataframe. I tried: new['unique'] = new_column But I've since found out that it just tries to replace all the values in all the rows and columns found under 'unique', like this: new['unique'] = 'a' Gets: unique cat numerical a b c d e f 0 a a 2 3 4 5 1 a a 2 3 4 5 And using .loc gets this instead: unique cat numerical a b c d e f 0 NaN NaN 2 3 4 5 1 NaN NaN 2 3 4 5 Here's my full code: import pandas as pd import numpy as np data=[[0,1,2,3,4,5],[0,1,2,3,4,5]] datatypes=np.array(['unique','unique','cat','cat','numerical','numerical']) columnnames=np.array(['a','b','c','d','e','f']) new = pd.DataFrame(data=data, columns=pd.MultiIndex.from_tuples(zip(datatypes,columnnames))) print('new: ') print(new) new_column = new.loc[:,'unique'].assign(z=pd.Series([9,9]).values) print('\nnew column:') print(new_column) new.loc[:,'unique'] = new_column print('\nattempt 1:') print(new) new['unique'] = new_column print('\nattempt 2:') print(new)
favorite count: 0
tagged with: python-3.x
type: Question

http://stackoverflow.com/comment/91469518
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52260091
has text: how do you expect to have a list that has keys and values? Python does not support such a list

http://stackoverflow.com/comment/91306960
has text: can you please explain this, I'm new to python and I didn't get it how it is working correctly.. and thanks for the answer. @ThatBird
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52178325
type: AnswerComment

http://stackoverflow.com/comment/91280550
type: Comment
has text: It will match also `"baseAsin": "B01GL56060",`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52165505

http://stackoverflow.com/q/52149434
tagged with: dictionary
has body: I wrote simple python which gives idea how the system performs but the total is not calculated. Now what I want is get the corresponding value (i.e. cone type, Scoop flavor for each scoop, and Topping flavor for each topping) and calculate total cost and finally displaying the items chosen in details (item-->price and quantity) and the total sum. customername = input("Enter the customer's name....") ic_no = int(input("Enter the number of ice-creams you want to buy")) total = {} for i in range(1, ic_no + 1): print("For item ", i) cone = int(input("Enter the cone type: ")) scoop = int(input("Enter the scoop amount: ")) for j in range(1, scoop+1): #select flavor type for each scoop flavor = int(input("Entr No."+ str(j) +" flavor")) topping = int(input("Entr the toppings amount: ")) for k in range(1, topping+1): #select flavor type for each topping top_flavor = int(input("Entr No." + str(k) +" topping flavor")) print("Total price is ", total) I want to get the selected items simply by passing number. For eg: 1 for 'plain' cone type. cone_type = ( {"name": "Plain", "price": 2}, {"name": "Wafle", "price": 3}, ) scoop_flavor = ( {"name": "Mint", "price": 1}, {"name": "Caramel", "price": 1}, {"name": "Chocolate", "price": 1}, {"name": "Apple", "price": 1}, ) topping_flavor = ( {"name": "Chocolate", "price": 1}, {"name": "Caramel", "price": 0.5}, {"name": "Peanut", "price": 0.5}, {"name": "Coconut Sprinkle", "price": 0.25}, )
has answer: http://stackoverflow.com/a/52149626
has answer: http://stackoverflow.com/a/52149673
has title: How to extract corresponding value from python dictionary?
type: Question
has answer: http://stackoverflow.com/a/52151035
tagged with: sharp
score: 0
answer count: 3
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52261508
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91470912
has body: am hitting a block here. I have to translate this excel formula IF(COUNTIFS(advisor!$C:$C,$A2)=0,"0 disclosed", "Independent") if df.groupby('id').apply(lambda x: x['id'] == df_advisor['company_id']).count() == 0: df['auditor_compensation'] = '0 disclosed' else: df['auditor_compensation'] = 'Independent' so far this is my python-pandas solution which i keep getting KeyError: ('company_id', 'occurred at index 1') Any help will be very much appreciated. Edit df sample data: company data id ticker iq_id company auditor_compensation 48299 ENXTAM:AALB IQ881736 Aalberts Industries ? 48752 ENXTAM:ABN IQ1090191 ABN AMRO Group ? 48865 ENXTAM:ACCEL IQ4492981 Accell Group ? 49226 ENXTAM:AGN IQ247906 AEGON ? 49503 ENXTAM:AD IQ373545 Koninklijke ? below is df_advisor sample data id type company_id advisor_company_id 1 auditor 48299 60911 17 auditor 48752 165120 6359 auditor 48865 73607 37 auditor 49226 81877 4415 compensation 49226 90258 53 auditor 49503 81877 So the goal is to check the whole column company_id in df_advisor, and count the occurance df['id'] in order to populate the auditor_compensation column.
downvote count: 0
has comment: http://stackoverflow.com/comment/91471195
has answer: http://stackoverflow.com/a/52272207
tagged with: pandas
has answer: http://stackoverflow.com/a/52262812
tagged with: python
has title: Pandas excel like countifs of two dataframes with condition
favorite count: 0
accepted answer: http://stackoverflow.com/a/52272207
score: 2
possible better answer: http://stackoverflow.com/a/52262812
upvote count: 2
has comment: http://stackoverflow.com/comment/91491356
tagged with: excel
type: AnsweredQuestion

http://stackoverflow.com/a/52154778
has comment: http://stackoverflow.com/comment/91259737
downvote count: 0
answers question: http://stackoverflow.com/q/52154712
type: Answer
score: 1
has body: You can use a conditional expression to only add the 's' to 'point' if the number is greater than 1. Also note that using range() is neater than manually typing the scores and .format better than a % (especially when doing multiple formats). for num in range(1, 11): print('A judge can give a gymnast {} point{}.'.format(num, 's' if num &gt; 1 else '')) which gives: A judge can give a gymnast 1 point. A judge can give a gymnast 2 points. A judge can give a gymnast 3 points. A judge can give a gymnast 4 points. A judge can give a gymnast 5 points. A judge can give a gymnast 6 points. A judge can give a gymnast 7 points. A judge can give a gymnast 8 points. A judge can give a gymnast 9 points. A judge can give a gymnast 10 points.
upvote count: 1

http://stackoverflow.com/comment/91349771
comment on: http://stackoverflow.com/a/52196927
type: AnswerComment
score: 0
type: Comment
has text: Thank you for the answer, third solution worked only If is_deconv=False, how to make it work with True parameter

http://stackoverflow.com/comment/91453952
type: QuestionComment
score: 1
has text: Thanks for catching this! Issue raised on https://github.com/nltk/nltk/issues/2112
comment on: http://stackoverflow.com/q/52250268
type: Comment

serverless-framework
tag name: serverless-framework
tags question: http://stackoverflow.com/q/52169226
type: Tag

http://stackoverflow.com/a/52183421
has comment: http://stackoverflow.com/comment/91317689
has comment: http://stackoverflow.com/comment/91318504
has body: MultiRNNCell is indeed not iterable. For your case, first, the RNN variables will not be created until you call tf.nn.dynamic_rnn, so you should try to retrieve them after that. Second, with use_peephole you have more than kernel and bias variables. To retrieve them, you can access all the RNN variables together from multi_layer_cell.variables or each layer's own set through the cell objects stored in layers: multi_layer_cell = tf.contrib.rnn.MultiRNNCell(layers) rnn_outputs, states = tf.nn.dynamic_rnn(multi_layer_cell, X, dtype=tf.float32) for index, one_lstm_cell in enumerate(layers): one_kernel, one_bias, *one_peepholes = one_lstm_cell.variables tf.summary.histogram("Kernel", one_kernel) tf.summary.histogram("Bias", one_bias)
answers question: http://stackoverflow.com/q/52182255
has comment: http://stackoverflow.com/comment/91319579
type: Answer
has comment: http://stackoverflow.com/comment/91317389
has comment: http://stackoverflow.com/comment/91317931
has comment: http://stackoverflow.com/comment/91316669
has comment: http://stackoverflow.com/comment/91318075
score: 2
has comment: http://stackoverflow.com/comment/91318166
downvote count: 0
has comment: http://stackoverflow.com/comment/91317625
has comment: http://stackoverflow.com/comment/91318779
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91320507
has comment: http://stackoverflow.com/comment/91320064
accepted answer of: http://stackoverflow.com/q/52182255

http://stackoverflow.com/q/52246451
linked to: http://stackoverflow.com/q/3136059
possible better answer: http://stackoverflow.com/a/52246510
downvote count: 0
tagged with: pyspark
has title: How to save the returned values of UDF function into two columns?
has answer: http://stackoverflow.com/a/52246510
tagged with: apache-spark
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52247645
accepted answer: http://stackoverflow.com/a/52252430
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
has body: My function get_data returns a tuple: two integer values. get_data_udf = udf(lambda id: get_data(spark, id), (IntegerType(), IntegerType())) I need to split them into two columns val1 and val2. How can I do it? dfnew = df \ .withColumn("val", get_data_udf(col("id"))) Should I save the tuple in a column, e.g. val, and then split it somehow into two columns. Or is there any shorter way?
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91444038
answer count: 3
linked to: http://stackoverflow.com/q/40959655
has answer: http://stackoverflow.com/a/52252430
has comment: http://stackoverflow.com/comment/91444333
tagged with: apache-spark-sql

http://stackoverflow.com/a/52166805
has body: when you delete the 9th element in the list, the 11th element shifts to 10th. This will be more complex when you have more empty elements. I recommend to delete it by checking for empty element using function = [x for x in function if x] The code above check for non-empty element and gives back the list you want. If you are concerned to remove via index, I would recommend to remove from decreasing order of the position. i.e., as you knew [9, 11] elements are to be removed, remove the element with highest index first. function.pop(11) then function.pop(9)
type: Answer
answers question: http://stackoverflow.com/q/52166565
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/52157974
tagged with: nexus
has body: pip: 18.0 python: 3.6 Nexus: 3.13 We have a corporate Nexus installed for hosting internal libraries, and a hosted pypi repository has been created. I was able to deploy a wheel file following this instruction, but failed to install it locally. Command to install: python -m pip install --index-url https://xxxx/xxx-pypi/ 'customlib==0.0.1' -v Error received: Could not find a version that satisfies the requirement customlib==0.0.1 (from versions: ) No matching distribution found for customlib==0.0.1 Please advise on this issue. Thanks in advance!
tagged with: pip
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52174693
has title: Failed to install custom lib deployed on Sonatype Nexus Pypi repository
tagged with: pypi
type: Question
has answer: http://stackoverflow.com/a/52174693
score: 0
answer count: 1
tagged with: python-3.x

http://stackoverflow.com/q/52196010
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/91366575
tagged with: process
tagged with: concurrency
upvote count: 1
has title: Should I use wait for popen
type: Question
tagged with: signals
has comment: http://stackoverflow.com/comment/91353250
downvote count: 0
has body: I'm using subprocess.Popen in playStation function to run another process which is media player to play radio station. However, when I kill the parent process, it doesn't stop, not killed. Just stuck after pressing CTRL-C, CTRL-Z or sending SIGKILL. Normally, It should be killed immediately. But not. I feel I exactly do a or some mistake(s). One of them maybe I don't think to wait the media player which is run by subprocess.Popen since it plays the radio station until I kill the child. Should I wait? If so, how, where? If I wait before return p, it is stuck. I try to simplify my code, def playStation(stationAddress): # if there is a media player being run, kill it for new one killMPlayer = "killall mplayer" os.system(killMPlayer) radioName = 'mplayer ' + '-playlist ' + stationAddress p = subprocess.Popen(radioName.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) ## the return value is not used I have added it ,maybe necessary return p arr = [ 'radio ip address:port 1', 'radio ip address:port 2', 'radio ip address:port 3', 'radio ip address:port 4', . . . . . there are more but just simplicity 4 is enough ] counter = 0 try: while True: signal.signal(signal.SIGCHLD, signal.SIG_IGN) pid = os.fork() if pid == 0: playStation(arr[counter]) ### normally playStation does work, control is takeovered by '''mplayer''' !!!! exit(0) else: ### wait until rotary encoder(switcher) is turned GPIO.wait_for_edge(CLOCKPIN, GPIO.FALLING) sleep(0.5) ### stop current child to create new child ### stop currently playing radio station to change to new station os.kill(pid, signal.SIGTERM) #os.waitpid(pid, 0) # prevent index out of bound if rotary_encoder_turned_left: counter = counter - 1 if counter &lt; 0: counter = 4 elif rotary_encoder_turned_right: counter = counter + 1 if counter &gt; 4: counter = 0
favorite count: 0
tagged with: fork

http://stackoverflow.com/q/52146051
has body: I used exec with selenium to run as below, from selenium import webdriver search_method = 'find_element_by_class_name' search_word = 'keyword' exec("elem_search_word = driver." + search_method + "('" + search_word + "')") elem_search_word.send_keys('python')) but I got error, what can I do? elem_search_word.send_keys(str(args.search)) NameError: name 'elem_search_word' is not defined
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52146423
score: 1
tagged with: selenium
type: Question
has comment: http://stackoverflow.com/comment/91242304
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91242348
has title: Python EXEC show error: name is not defined
has answer: http://stackoverflow.com/a/52146423
has comment: http://stackoverflow.com/comment/91242187
tagged with: exec
favorite count: 0

http://stackoverflow.com/q/52230227
has title: Buildozer not building for android
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52244096
has comment: http://stackoverflow.com/comment/91435582
type: Question
has body: I have buildozer master on ubuntu 18.04 trying to build a simple app: from kivy.app import App from kivy.uix.scatter import Scatter from kivy.uix.label import Label from kivy.uix.floatlayout import FloatLayout class TutorialApp(App): def build(self): f = FloatLayout() s = Scatter() l = Label(text='Hello!', font_size=150) f.add_widget(s) s.add_widget(l) return f if __name__ == "__main__": TutorialApp().run() Here is the output from buildozer: # Check configuration tokens # Ensure build layout # Check configuration tokens # Preparing build # Check requirements for android # Run 'dpkg --version' # Cwd None b"Debian 'dpkg' package management program version 1.19.0.5 (amd64).\nThis is free software; see the GNU General Public License version 2 or\nlater for copying conditions. There is NO warranty.\n"# Search for Git (git) # -&gt; found at /usr/bin/git # Search for Cython (cython) # -&gt; found at /usr/local/bin/cython # Search for Java compiler (javac) # -&gt; found at /usr/lib/jvm/java-11-openjdk-amd64/bin/javac # Search for Java keytool (keytool) # -&gt; found at /usr/lib/jvm/java-11-openjdk-amd64/bin/keytool # Install platform # Run 'pip install -q --user "appdirs" "colorama&gt;=0.3.3" "sh&gt;=1.10" "jinja2" "six"' # Cwd None # Apache ANT found at /home/andrew/.buildozer/android/platform/apache-ant-1.9.4 # Android SDK found at /home/andrew/.buildozer/android/platform/android-sdk-24 # Android NDK found at /home/andrew/Downloads/androidNDK/crystax-ndk-10.3.2 # Check application requirements # Check garden requirements # Compile platform # Run '/usr/bin/python3 -m pythonforandroid.toolchain create --dist_name=tryingPython --bootstrap=sdl2 --requirements=python3crystax,kivy --arch armeabi-v7a --copy-libs --color=always --storage-dir="/home/andrew/Documents/myPython/androidApps/.buildozer/android/platform/build"' # Cwd /home/andrew/Documents/myPython/androidApps/.buildozer/android/platform/python-for-android-new-toolchain [INFO]: Will compile for the following archs: arme…
score: 0
tagged with: android
answer count: 1
has comment: http://stackoverflow.com/comment/91428539
tagged with: python
tagged with: kivy

http://stackoverflow.com/comment/91221836
score: 0
type: Comment
has text: OK, now what can I do for this like output `$ python3 -c 'print(1, 2, 3)' 1 2 3`
comment on: http://stackoverflow.com/a/52136033
type: AnswerComment

http://stackoverflow.com/comment/91353678
has text: Thanks for the suggestion. I will look into the `ttk.Separator`, but what I'm really interested to see is why the code I posted is not working, not how to draw the vertical line, which can be probably done in many ways.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52201723

http://stackoverflow.com/comment/91223046
type: Comment
type: AnswerComment
has text: I don't think you even have to save it. You can just take frame and work on it, as described in [this tutorial](https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html).
comment on: http://stackoverflow.com/a/52136519
score: 0

http://stackoverflow.com/comment/91322873
has text: What are you passing as `sf`? The result of `pickle.dumps`? A reproducible data flow will be helpful.
comment on: http://stackoverflow.com/a/52180535
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52178427
has body: When having issues with a query you can use the psycopg2 mogrify function to see if there is an issue with your string. It will attempt to interpolate any parameters as well so can be a good check. Since I didn't have a cursor object to call it on I did this instead: print psycopg2.extensions.adapt(YOUR_QUERY).getquoted() In your case this gives: &gt;&gt;&gt; import psycopg2 &gt;&gt;&gt; print psycopg2.extensions.adapt(YOUR_QUERY).getquoted() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: A string literal cannot contain NUL (0x00) characters. &gt;&gt;&gt; print psycopg2.extensions.adapt('\\0').getquoted() '\\0' &gt;&gt;&gt; So you can see it doesn't like the '\0'. If you escape the backslash as John Rotenstein suggests psycopg2 will accept the query but it may not give you what you want for your null value. The documentation suggests it should work if you can get the interpolation sorted out.
answers question: http://stackoverflow.com/q/52173763
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/52201870
has answer: http://stackoverflow.com/a/69610730
tagged with: python
has comment: http://stackoverflow.com/comment/91403913
score: 3
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/91403592
has comment: http://stackoverflow.com/comment/91408168
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/91353062
has comment: http://stackoverflow.com/comment/91356169
downvote count: 0
has title: Why does Pandas read_excel function return an error in Pyinstaller .exe but not under Python interpreter?
has body: I'm using the Pandas read_excel function to import data from a spreadsheet. This works fine when run under the Python interpreter, but when I build an exe with PyInstaller it returns an IndexError. Here's a simplified code pandas_test.py that demonstrates the problem: import pandas as pd filepath = 'C:/Users/User/Documents/Development/Python/PHL/Test Data/Study template mock-up.xlsx' df = pd.read_excel(filepath, sheet_name='Data Entry', index_col=9) print(df.head()) This runs just fine under Python 3.6 with pandas 0.23.4 and xlrd 1.1.0. When I build pandas_test.py with PyInstaller it successfully produces an pandas_test.exe, but I get this error: Traceback (most recent call last): File "pandas_test.py", line 4, in &lt;module&gt; File "site-packages\pandas\io\excel.py", line 212, in read_excel File "site-packages\pandas\io\excel.py", line 513, in _parse_excel File "site-packages\pandas\io\parsers.py", line 1912, in TextParser File "site-packages\pandas\io\parsers.py", line 764, in __init__ File "site-packages\pandas\io\parsers.py", line 995, in _make_engine File "site-packages\pandas\io\parsers.py", line 2021, in __init__ File "site-packages\pandas\io\parsers.py", line 2772, in _get_index_name File "site-packages\pandas\io\parsers.py", line 3084, in _clean_index_names IndexError: list index out of range [17264] Failed to execute script pandas_test I've read through the PyInstaller output, but there's nothing obviously related: 887 INFO: PyInstaller: 3.3.1 887 INFO: Python: 3.6.2 889 INFO: Platform: Windows-10-10.0.17134-SP0 892 INFO: wrote C:\Users\User\Documents\Development\Python\PandaTest\pandas_test.spec I could understand if some module was not found, but why an IndexError only in the deployed code?
favorite count: 0
has answer: http://stackoverflow.com/a/54679314
tagged with: pyinstaller
type: UnansweredQuestion

http://stackoverflow.com/comment/91277670
type: Comment
type: QuestionComment
has text: No, it can come on the different lines. I just need when the are more then one one, it does not matter if they are consecutive or not. Thanks Martijn
comment on: http://stackoverflow.com/q/52163823
score: 0

http://stackoverflow.com/comment/91402090
type: QuestionComment
has text: If both options are working, and you just need to determine which is better, then maybe codereview.stackexchange.com might be an option?
score: 0
comment on: http://stackoverflow.com/q/52226293
type: Comment

http://stackoverflow.com/comment/91442878
type: Comment
type: QuestionComment
has text: If you properly follow the [reference](https://en.cppreference.com/w/cpp/container/unordered_set/insert), the complexity section lists O(n) time for insertion. In the worst case, hashing fails to provide O(1) if same bucket gets filled continuously. I competitive programming, I have got TLE several times due to this. Trie guarantees O(bit-depth) ~ O(1) insertion. Thus overall O(n)
score: 0
comment on: http://stackoverflow.com/q/52246669

http://stackoverflow.com/comment/91361667
comment on: http://stackoverflow.com/q/52206196
type: Comment
type: QuestionComment
has text: You might get sth like: `{2:{3: 2, 4: 1}, 3:{2: 2, 4: 1}, 4:{3: 1, 2: 1}}` which would make more sense.
score: 1

http://stackoverflow.com/comment/91364647
type: Comment
comment on: http://stackoverflow.com/q/52207645
score: 1
has text: Your posted code puts a single number in the list and returns that one-element list. Please post the code that actually produces your problem.
type: QuestionComment

http://stackoverflow.com/comment/91391893
type: Comment
comment on: http://stackoverflow.com/a/52220950
score: 0
type: AnswerComment
has text: @KoYan I can't really reproduce it with the data you have given above. On your example, everything works as you can see. Must be a problem that is not covered by your example

http://stackoverflow.com/q/52167343
upvote count: 1
tagged with: python
answer count: 0
linked to: http://stackoverflow.com/q/464040
score: 1
tagged with: cgi
has title: Take value in web browser and show result from DB using Python CGI script
type: Question
downvote count: 0
has body: I have created a CGI script using python 3.6 wherein it will take user input from a HTML form and then search the database based on the value. How should I take the input and filter data based on the value? My current script is showing the entire table instead of filtering. Basically output needs to be based on "Where" condition. HTML Script : Sender ID Blacklist Please enter Sender id below Senderid: Below is the CGI script (test3.cgi) : import mysql.connector as mx import sys import cgi import cgitb def htmltop(): print("""Content-type: text/html\r\n\r\n Output:""") def htmltail(): print(""" """) def connectdb(): mydb=mx.connect(host='127.0.0.1', user='root', passwd='', port='3306', database='arghad') cur=mydb.cursor() return mydb,cur def Blacklist(mydb,cur): query="select * from arghad.test" cur.execute(query) result=cur.fetchall() return result def displaytest(result): print(" ") print(" ") print(" senderid ") print(" route ") print(" time ") print(" ") for x in result: print(" ") print(" {0} ".format(x[0])) print(" {0} ".format(x[1])) print(" {0} ".format(x[2])) print(" ") print(" ") if __name__ == '__main__': try: htmltop() form = cgi.FieldStorage() mydb,cur=connectdb() result=Blacklist(mydb,cur) displaytest(result) cur.close() htmltail() except: cgi.print_exception() Output : I have given only one value by the way.
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/52268718
type: Answer
upvote count: 2
has body: You would be reading new input in every elif evaluation. Store the input once, so you can repeatedly compare it: i = input() if i == "hello": print("Hello, " + username + "!") elif i == "cat": # ... elif i == ...: # ...
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52268646

http://stackoverflow.com/comment/91388980
type: Comment
comment on: http://stackoverflow.com/a/52154455
score: 0
has text: You are asking for something to have 2 values at the same time which is not possible. A couple of solutions: One way is to add additional `assign` ops (and maybe a `placeholder` as well if you want for easily feeding it) to your graph. You can dynamically find all the places in `g` where `y` is used and add some `assign` ops to assign `z` to all variables that took the value from placeholder `y`. Another way would be to create two copies of your graph and feed `x, y` to `f` and `x,y=z` to `g`, calculate a combined loss and apply the gradients yourself to the respective sub-graphs
type: AnswerComment

http://stackoverflow.com/a/52180314
accepted answer of: http://stackoverflow.com/q/52168083
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: This issue resolved by downloading the wheel file of django-pyodbc-azure 2.1.0.0 from https://pypi.org/project/django-pyodbc-azure/#files and installing using the command pip install django_pyodbc_azure-2.1.0.0-py3-none-any.whl.
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91314112
answers question: http://stackoverflow.com/q/52168083

http://stackoverflow.com/q/52155056
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/17256602
has answer: http://stackoverflow.com/a/52157203
type: UnansweredQuestion
tagged with: unit-testing
score: 1
type: Question
upvote count: 2
tagged with: python-import
answer count: 1
linked to: http://stackoverflow.com/q/34865873
tagged with: flask
has title: How to handle importing when testing Flask apps: AssertionError: View function mapping is overwriting an existing endpoint function
has body: I am struggling trying to understand how to write tests in Flask. I've inherited an app that already has a bunch of tests that hit routes like /login and test that the response is what's expected. I have a substantially more complicated situation. I need to test a route/method that depending on the circumstances, hits an external api, figures out whether a path exists in the container the app itself is running in, starts a process that takes 10+ minutes to run on a different machine -- all manner of things. So I can't just hit the route and see if I got what I wanted; I need mocking and patching to mimic the effects of various external world states. Right now I have a route defined like so in brain_db/views.py: @app.route('/label_view/&lt;int:scan_number&gt;') @login_required def label_view(scan_number): &lt;so much complicated logic&gt; The first route defined in that same file, brain_db/views.py, is @app.route('/surface_test') def surface_test(): &lt;some code&gt; Here is a simplified version of the file that's throwing the error: import unittest from mock import MagicMock, patch from flask_brain_db.test_helpers import set_up, tear_down from flask_brain_db.brain_db.models import Scan from brain_db.views import label_view class BrainDBTest(unittest.TestCase): def setUp(self): app, db = set_up() scan = Scan(1, '000001', '000001_MR1', 'scan.nii.gz', scan_number=1) db.session.add(scan) scan = Scan.query.filter(Scan.scan_number == 1).first() db.session.commit() def tearDown(self): tear_down() def mock_volume_views_setup(self) scan = Scan.query.filter(Scan.scan_number == 1).first() container_file_path = '/path/to/file/in/container' return scan, container_file_path def mock_os_path_exists(self, arg): return True @patch('brain_db_helpers.volume_views_setup', mock_volume_views_setup) @patch('os.path.exists', mock_os_path_exists) def test_label_view(self): rv = label_view(1) assert(True) # I'll actually write tests when I figure out that I can! print rv Here is the error: =…
downvote count: 1

http://stackoverflow.com/comment/91422627
score: 1
comment on: http://stackoverflow.com/q/52236941
has text: To my knowledge you cannot hide the console log of chromedriver, in latest versions....
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91323305
score: 0
has text: @jdehesa Out of curiosity, do people ever use a filename queue or something similar to read data into a tf.data.Dataset?
type: Comment
comment on: http://stackoverflow.com/q/52182910
type: QuestionComment

http://stackoverflow.com/q/52208153
has comment: http://stackoverflow.com/comment/91365865
has title: Pythonic / Panda Way to Create Function to Groupby
possible better answer: http://stackoverflow.com/a/52209189
tagged with: pandas
has answer: http://stackoverflow.com/a/52209189
accepted answer: http://stackoverflow.com/a/52209070
downvote count: 0
has comment: http://stackoverflow.com/comment/91365763
favorite count: 0
tagged with: python-3.x
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: I am fairly new to programming &amp; am looking for a more pythonic way to implement some code. Here is dummy data: df = pd.DataFrame({ 'Category':np.random.choice( ['Group A','Group B'], 10000), 'Sub-Category':np.random.choice( ['X','Y','Z'], 10000), 'Sub-Category-2':np.random.choice( ['G','F','I'], 10000), 'Product':np.random.choice( ['Product 1','Product 2','Product 3'], 10000), 'Units_Sold':np.random.randint(1,100, size=(10000)), 'Dollars_Sold':np.random.randint(100,1000, size=10000), 'Customer':np.random.choice(pd.util.testing.rands_array(10,25,dtype='str'),10000), 'Date':np.random.choice( pd.date_range('1/1/2016','12/31/2018', freq='D'), 10000)}) I have lots of transactional data like that that I perform various Groupby's on. My current solution is to make a master groupby like this: master = df.groupby(['Customer','Category','Sub-Category','Product',pd.Grouper(key='Date',freq='A')])['Units_Sold'].sum()\ .unstack() From there, I perform various groupbys using .groupby(level=) function to aggregate the information in the way I'm looking for. I usually make a summary at each level. In addition, I create sub-totals at each level using some variation of the below code. y = master.groupby(level=[0,1,2]).sum() y.index = pd.MultiIndex.from_arrays([ y.index.get_level_values(0), y.index.get_level_values(1), y.index.get_level_values(2) + ' Total', len(y.index)*[''] ]) y1 = master.groupby(level=[0,1]).sum() y1.index = pd.MultiIndex.from_arrays([ y1.index.get_level_values(0), y1.index.get_level_values(1)+ ' Total', len(y1.index)*[''], len(y1.index)*[''] ]) y2 = master.groupby(level=[0]).sum() y2.index = pd.MultiIndex.from_arrays([ y2.index.get_level_values(0)+ ' Total', len(y2.index)*[''], len(y2.index)*[''], len(y2.index)*[''] ]) pd.concat([master,y,y1,y2]).sort_index()\ .assign(Diff = lambda x: x.iloc[:,-1] - x.iloc[:,-2])\ .assign(Diff_Perc = lambda x: (x.iloc[:,-2] / x.iloc[:,-3])- 1)\ .dropna(how='all')\ This is just an example - I may perform the same exercise, but …
score: 1
has answer: http://stackoverflow.com/a/52209070
type: Question
answer count: 2

http://stackoverflow.com/q/52172760
tagged with: header
favorite count: 0
has title: moving files to folders after they got read and separated by a variable
tagged with: python
type: AnsweredQuestion
tagged with: fits
tagged with: loops
type: Question
has answer: http://stackoverflow.com/a/52172931
accepted answer: http://stackoverflow.com/a/52172931
tagged with: if-statement
has body: I have created a python script that reads a variable FILTER from files in a folder and puts the result on screen. However, there are 4 types of variables and I would like this script to separate them all to the corresponding folders. Like move all of the files to a folder named "V" if they have variable FILTER = V, if they have FILTER = B, then move all of the B ones to folder named "B" The script below works to see which files have which filter on screen. import glob import pyfits import shutil myList = [] for fitsName in glob.glob('*.fits'): hdulist = pyfits.open(fitsName) b = hdulist[0].header['FILTER'] c = b myList.append(c) hdulist.close() for item in sorted(myList): print item Result on screen: B B B V V V R R R I I I now with shutil the code i run; import os import glob import pyfits import shutil myList = [] for fitsName in glob.glob('*.fits'): hdulist = pyfits.open(fitsName) hdu = hdulist[0] prihdr = hdulist[0].header a = hdulist[0].header['FILTER'] b = a if b == "B": shutil.move('/home/usr/Desktop/old/', '/home/usr/Desktop/new/B/') myList.append(b) hdulist.close() Now this code works without problem but it moves all the files in Desktop/old/ to Desktop/new/B/ however, some files have b = V and other variables so what is the problem here? How can I specify the names of which files have the filters I desired so that it can automatically move? so it is like from the code above, if c= FILTERNAME1 move to SOMEFOLDER1 if c = FILTERNAME2 move to SOMEFOLDER2 and so on.. I could not write a working code line for this so any help would be appreciated a lot. Solution; import os import glob import pyfits import shutil for fitsName in glob.glob('*.fits'): hdulist = pyfits.open(fitsName) hdu = hdulist[0] a = hdulist[0].header['FILTER'] if a == "B": shutil.move(fitsName, '/home/usr/Desktop/new/B/') if a == "V": shutil.move(fitsName, '/home/usr/Desktop/new/V/') if a == "R": shutil.move(fitsName, '/home/usr/Desktop/new/R/') if a == "I": shutil.move(fitsName, '/home/usr/Des…
score: 0
upvote count: 1
answer count: 1
downvote count: 1

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/52217866
tags question: http://stackoverflow.com/q/52171778
tags question: http://stackoverflow.com/q/52247813
tags question: http://stackoverflow.com/q/52242773
tags question: http://stackoverflow.com/q/52142768
tags question: http://stackoverflow.com/q/52237519
tags question: http://stackoverflow.com/q/52270868
tags question: http://stackoverflow.com/q/52143512
tags question: http://stackoverflow.com/q/52158048
tags question: http://stackoverflow.com/q/52163199
type: Tag
tags question: http://stackoverflow.com/q/52165717
tags question: http://stackoverflow.com/q/52239590
tags question: http://stackoverflow.com/q/52140317
tags question: http://stackoverflow.com/q/52121073
tags question: http://stackoverflow.com/q/52209888
tags question: http://stackoverflow.com/q/52261567
tags question: http://stackoverflow.com/q/52236057
tags question: http://stackoverflow.com/q/52188570
tags question: http://stackoverflow.com/q/52268433
tags question: http://stackoverflow.com/q/52155127
tags question: http://stackoverflow.com/q/52117156
tags question: http://stackoverflow.com/q/52128922
tags question: http://stackoverflow.com/q/52250516
tags question: http://stackoverflow.com/q/52247052
tags question: http://stackoverflow.com/q/52261414
tags question: http://stackoverflow.com/q/52205558
tags question: http://stackoverflow.com/q/52191015
tags question: http://stackoverflow.com/q/52269635
tags question: http://stackoverflow.com/q/52224595
tags question: http://stackoverflow.com/q/52137238
tags question: http://stackoverflow.com/q/52240846
tags question: http://stackoverflow.com/q/52193143
tags question: http://stackoverflow.com/q/52117533
tags question: http://stackoverflow.com/q/52129856
tags question: http://stackoverflow.com/q/52135929
tags question: http://stackoverflow.com/q/52240338
tags question: http://stackoverflow.com/q/52170877
tags question: http://stackoverflow.com/q/52125795
tags question: http://stackoverflow.com/q/52235577
tags question: http://stackoverflow.com/q/52125153
tags question: http://stackoverflow.com/q/52150648
tag name: html
tags question: http://stackoverflow.com/q/52242843
tags question: http://stackoverflow.com/q/52189218
tags question: http://stackoverflow.com/q/52161656
tags question: http://stackoverflow.com/q/52214339
tags question: http://stackoverflow.com/q/52225930
tags question: http://stackoverflow.com/q/52265280
tags question: http://stackoverflow.com/q/52211968
tags question: http://stackoverflow.com/q/52257172
tags question: http://stackoverflow.com/q/52218461
tags question: http://stackoverflow.com/q/52138510
tags question: http://stackoverflow.com/q/52122949
tags question: http://stackoverflow.com/q/52216318
tags question: http://stackoverflow.com/q/52223138
tags question: http://stackoverflow.com/q/52214395

http://stackoverflow.com/q/52201136
tagged with: django-rest-framework
favorite count: 0
has comment: http://stackoverflow.com/comment/91351244
tagged with: python
has comment: http://stackoverflow.com/comment/91351261
type: UnansweredQuestion
upvote count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/91351440
score: 1
has body: I have searched for a solution but I have not found any, I have a dictionary like This tmp ={ 'admission_date':adm.admission_date, 'course':adm.course.name } In models.py i have admission_date to DatetimeField. In the Get Function I want to format this date like this 2018-09-05 By removing all part How can i do This.
has answer: http://stackoverflow.com/a/52201241
type: Question
has title: How To Convert (2018-09-05T09:00:06.540486Z) Into (2018-09-05) In python?
answer count: 1
downvote count: 0

http://stackoverflow.com/q/52260737
has answer: http://stackoverflow.com/a/52269238
has comment: http://stackoverflow.com/comment/91485923
has body: I got error cannot import name main when i tried to running pip. I had tried modify file /usr/bin/pip to from pip import __main__ if __name__ == '__main__': sys.exit(__main__._main()) according to this and i got another error module object has no attribute _main. Thanks in advance.
has title: ImportError: cannot import name main when running pip with pip version 18.0, ubuntu 18.04
tagged with: ubuntu
accepted answer: http://stackoverflow.com/a/52269238
score: 0
answer count: 1
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/91539300
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/28210269
type: Question

http://stackoverflow.com/comment/91367623
type: Comment
type: QuestionComment
has text: Python 2.6 is still supported?
comment on: http://stackoverflow.com/q/52209093
score: 0

http://stackoverflow.com/comment/91198526
score: 1
has text: You want to match on the string values that those variable resolve to though right? It would be `'imgType_c'` rather than the variable name `imgType_c`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52123629

http://stackoverflow.com/comment/91216148
type: Comment
has text: No problem. If the answer helped you, you can upvote it and/or mark it as "accepted" with the checkmark. Welcome to StackOverflow, and good luck moving forward with learning Python!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52124511

flask-socketio
tags question: http://stackoverflow.com/q/52194063
tags question: http://stackoverflow.com/q/52154728
type: Tag
tags question: http://stackoverflow.com/q/52267135
tags question: http://stackoverflow.com/q/52207273
tag name: flask-socketio
tags question: http://stackoverflow.com/q/52153296

http://stackoverflow.com/a/52171766
upvote count: 3
has body: Since your euclidian distances are on scalars, it's equivalent to the absolute value between each point. So you can repeat your arrays in the appropriate order using np.repeat and np.tile, and just subtract your arrays from one another: import numpy as np a = [[1, 2, 3], [4, 5, 6]] b = [[10, 20]] a1 = np.array(a).flatten() b1 = np.array(b).flatten() Final_distance = np.abs(np.subtract(np.repeat(a1, len(b1)), np.tile(b1, len(a1)))) Which returns: array([ 9, 19, 8, 18, 7, 17, 6, 16, 5, 15, 4, 14])
has comment: http://stackoverflow.com/comment/91295608
answers question: http://stackoverflow.com/q/52171623
downvote count: 0
score: 3
type: Answer

http://stackoverflow.com/comment/91477960
has text: Thank you all of you for your response. @Onyambu, on using hstack, I get a completely flattened array (1,16) but instead I want to get (1,9) keeping the inner arrays intact minus the dtype='<U9'. Is it possible ?.
comment on: http://stackoverflow.com/q/52247579
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91429544
score: 1
comment on: http://stackoverflow.com/q/52240343
type: Comment
has text: Could you show us what the input looks like? Seems like the formatting got messed up.
type: QuestionComment

http://stackoverflow.com/comment/101921994
comment on: http://stackoverflow.com/a/55991598
type: AnswerComment
has text: I tried so many different solutions but that 'shuffle=False' tip is exactly what I was missing.
type: Comment
score: 1

http://stackoverflow.com/comment/91337676
has text: I have figured out how to scale the data with `ax.relim()` and `ax.autoscale_view()`, but the ticks do not change.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52193852

http://stackoverflow.com/q/52210274
tagged with: python-multithreading
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
has title: Nonblocking queue of threads
has body: I want to create simple queue of threads. THREADS WILL START WITH POST REQUEST I created simple example without requests. I tried to join threads, but it doesn't work as i want. def a(): print('start a') sleep(5) print('end a') def b(): print('start b') sleep(5) print('end b') t = Thread(target=a) t.start() t.join() print('test1') t = Thread(target=b) t.start() t.join() print('test2') Result of code: start a end a test1 start b end b test2 Expectation: start a test1 end a start b test2 end b I know i can print('test1') before join, but when i use post request thread can start in time of printing ('test1') t.start() print('test1') &lt;- here comes post request t1.start() print('test2') t1.join() t.join() In this case threads will run parallel
has comment: http://stackoverflow.com/comment/91370085
tagged with: concurrency
tagged with: queue
type: Question
has answer: http://stackoverflow.com/a/52214704
has comment: http://stackoverflow.com/comment/91377413
has comment: http://stackoverflow.com/comment/91370492
score: 0
answer count: 1

http://stackoverflow.com/q/52187046
tagged with: django-views
type: Question
has title: Django Rest Framework: How to implement a nested logic?
has answer: http://stackoverflow.com/a/52218427
tagged with: django-models
score: 0
answer count: 1
tagged with: django-rest-framework
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: Let's say I have three models as: class User(AppModel): name = models.CharField(max_length=255) class Business(AppModel): owner = models.ForeignKey("User", related_name="businesses", on_delete=models.CASCADE) legal_name = models.CharField(max_length=255) class Invoice(AppModel): business = models.ForeignKey("Business", related_name="invoices", on_delete=models.CASCADE) amount = models.integerField() As you can see, a user can have multiple businesses and a business can have multiple invoices. My serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields= ('name') class BusinessSerializer(serializers.ModelSerializer): owner = UserSerializer(many=False) class Meta: model = Business fields= ('owner','legal_name') class InvoiceSerializer(serializers.ModelSerializer): business= BusinessSerializer(many=False) class Meta: model = Invoice fields= ('business','amount') views.py: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class BusinessViewSet(viewsets.ModelViewSet): queryset = Business.objects.all() serializer_class = BusinessSerializer class InvoiceViewSet(viewsets.ModelViewSet): queryset = Invoice.objects.all() serializer_class = InvoiceSerializer urls.py: router = DefaultRouter() router.register('user', UserViewSet, base_name='users') router.register('business', BusinessViewSet, base_name='businesses') router.register('invoice', InvoiceViewSet, base_name='invoices') urlpatterns = router.urls http://example.com/api/user returns all users. Not a problem. But the functionality I'm looking for is: http://example.com/api/business/ returns [ { "legal_name": "1business", "owner": 1, }, { "legal_name": "2business", "owner": 1, },] http://example.com/api/business/1/ returns { "legal_name": "1business", "owner": 1, } The above is ok. But I also need: http://example.com/api/business/1/invoices/ should return [ { "business": 1, "amount": 100, }, { "business": 1, "amount": 999, },] A…

http://stackoverflow.com/comment/91217840
type: QuestionComment
comment on: http://stackoverflow.com/q/52133630
score: 0
type: Comment
has text: `sentence = sentence.replace(brand, BRANDS[brand])` ... replace returns a new string

http://stackoverflow.com/comment/91264833
score: 0
comment on: http://stackoverflow.com/q/52157261
type: QuestionComment
type: Comment
has text: [mcve] please. You don't even mention what part of your code dump is relevant...

http://stackoverflow.com/comment/91304906
has text: Please [edit] your question to document *all* your requirements, like the ones you added in a comment to the now-deleted answer (which seems to solve precisely the question as it is currently articulated).
score: 0
comment on: http://stackoverflow.com/q/52171576
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52269103
score: 1
answers question: http://stackoverflow.com/q/52268817
upvote count: 1
downvote count: 0
type: Answer
has body: I don't have panda installed, but according to documentation, panda timestamps and timedeltas can be added. So something like this might work: result = [t + d for t, d in zip(timestamps, deltas)]

http://stackoverflow.com/a/52248980
has comment: http://stackoverflow.com/comment/91446452
type: Answer
has comment: http://stackoverflow.com/comment/91446402
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52248937
score: 1
answers question: http://stackoverflow.com/q/52248937
has body: transform isn't enough. You will need to mask everything but the last index. You can perform index aligned assignment to do so. g = df.groupby('name')['star'] df['minstar'] = pd.Series(g.min(), index=g.apply(pd.Series.last_valid_index)) df.fillna('') name CEMS star minstar 0 ACC CEMS-1 3 1 ACC CEMS-2 4 2 ACC CEMS-3 5 3 ACC CEMS-4 5 3 4 ARTi CEMS-1 4 5 ARTi CEMS-2 5 6 ARTi CEMS-3 4 7 ARTi CEMS-4 5 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/127942970
type: Comment
comment on: http://stackoverflow.com/a/52243379
type: AnswerComment
score: 0
has text: unfortunately, it fails with "_corrupt_record" for some records

http://stackoverflow.com/a/52165001
has body: Looking at your responses to other people, it appears that you don't want the alt-text of all the images, but only specified ones. The common denominator from the (admittedly small) example you gave is that they share a class. Might this be what you're looking for? lines=soup.find_all('img', class_='cfJLC') for line in lines: print(line['alt']) Output: Japanese League Cup Japanese League Cup
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91279479
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52164163
accepted answer of: http://stackoverflow.com/q/52164163
upvote count: 2

http://stackoverflow.com/comment/103504059
comment on: http://stackoverflow.com/a/52175154
score: 0
type: AnswerComment
has text: That more looks like an error with the filename (probably, named "Tabula")
type: Comment

http://stackoverflow.com/q/52265879
tagged with: http://stackoverflow.com/tag/svg
downvote count: 0
has comment: http://stackoverflow.com/comment/91479868
has answer: http://stackoverflow.com/a/52266513
type: AnsweredQuestion
has body: I'm using the cairosvg library in order to convert some svg files into png using google cloud functions, however I got the error CAIRO_STATUS_WRITE_ERROR when I run inside a google cloud function. svg_string = """ &lt;svg baseProfile="full" height="100%" version="1.1" width="100%" xmlns="http://www.w3.org/2000/svg"&gt; &lt;circle cx="50" cy="50" r="40" /&gt; &lt;/svg&gt; """ cairosvg.svg2png( bytestring=svg_string, write_to='/tmp/output.png') Stacktrace: Traceback (most recent call last): File "/env/local/lib/python3.7/site-packages/google/cloud/functions_v1beta2/worker.py", line 281, in run_background_function _function_handler.invoke_user_function(event_object) File "/env/local/lib/python3.7/site-packages/google/cloud/functions_v1beta2/worker.py", line 171, in invoke_user_function return call_user_function(request_or_event) File "/env/local/lib/python3.7/site-packages/google/cloud/functions_v1beta2/worker.py", line 168, in call_user_function event_context.Context(**request_or_event.context)) File "/user_code/main.py", line 54, in handle_upload bytestring=svg_string, write_to='/tmp/output.png') File "/env/local/lib/python3.7/site-packages/cairosvg/__init__.py", line 45, in &lt;lambda&gt; surface_type.convert(*args, **kwargs))(_surface_type) File "/env/local/lib/python3.7/site-packages/cairosvg/surface.py", line 139, in convert instance.finish() File "/env/local/lib/python3.7/site-packages/cairosvg/surface.py", line 463, in finish self.cairo.write_to_png(self.output) File "/env/local/lib/python3.7/site-packages/cairocffi/surfaces.py", line 653, in write_to_png self._pointer, _encode_filename(target))) File "/env/local/lib/python3.7/site-packages/cairocffi/__init__.py", line 79, in _check_status raise exception(message, status) OSError: [Errno cairo returned CAIRO_STATUS_WRITE_ERROR: b'error while writing to output stream'] 11
score: 1
has comment: http://stackoverflow.com/comment/91479999
type: Question
tagged with: google-cloud-platform
answer count: 1
has title: CAIRO_STATUS_WRITE_ERROR: b'error while writing to output stream' on Google Cloud Functions
upvote count: 1
tagged with: google-cloud-functions
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/52266513

http://stackoverflow.com/comment/91257445
type: Comment
comment on: http://stackoverflow.com/a/52152222
has text: Also, you pass `months` (your list), not `month` (which is empty)
score: 0
type: AnswerComment

http://stackoverflow.com/q/52188563
has comment: http://stackoverflow.com/comment/91338698
has body: I just made a space-invadish game, where things fall to the ground and you have to avoid crashing, etc. I succeeded in creating 2 objects falling down simultaneously but I cannot make them doing this with different speed. This the first object's attributes. thing_startx = random.randrange(0, display_width-100) thing_starty = -700 thing_speed = 4 Now it falls by thing_starty += thing_speed in each while loop iteration. For the next object I just added random numbers to the original X and Y coordinates so it gets it different position. (cf function below to create two rect objects if mult == True) def things_mult(thingx, thingy, thingw, thingh, color, mult, xopt, yopt, wopt, col2): if mult == False: pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh]) else: pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw , thingh]) pygame.draw.rect(gameDisplay, col2, [thingx + xopt, thingy + yopt, thingw + wopt, thingh]) Now, I assume I just need to define thingy_new = thing_starty + thing_yopt thingy_new = thingy_new + thing_speed* someconstant #(to make it faster or slower) Unfortunately, it does not work out like that. Can someone please explain to me why I am somehow shortcoming that simple logic?
tagged with: python
tagged with: pygame
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91343719
score: 2
has answer: http://stackoverflow.com/a/52235124
type: Question
has title: pygame elements with different "speed"
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91343676
favorite count: 0

http://stackoverflow.com/comment/91208660
has text: How can compute the coin every time i insert coin? And when i press the button it gives me the computed result.
type: AnswerComment
comment on: http://stackoverflow.com/a/52126777
type: Comment
score: 0

http://stackoverflow.com/comment/91463436
type: Comment
type: QuestionComment
has text: Is there any language where this is even possible?
comment on: http://stackoverflow.com/q/52258055
score: 0

http://stackoverflow.com/a/52256493
has comment: http://stackoverflow.com/comment/91460278
has comment: http://stackoverflow.com/comment/91460320
has comment: http://stackoverflow.com/comment/91460173
type: Answer
answers question: http://stackoverflow.com/q/52256445
upvote count: 10
has body: (list_one, list_two) is a tuple of exactly two elements, containing list_one and list_two. Since a day is never equal to a list, day not in (list_one, list_two) turns out to be True. You could either merge the lists and write lists = list_one + list_two if day not in lists: ... or use if day not in list_one and day not in list_two: ... or alternatively, applying De Morgan's laws: if not (day in list_one or day in list_two): ... to express that day is in neither of those lists.
downvote count: 0
score: 10

http://stackoverflow.com/comment/91403475
score: 0
has text: @Sinjin Are you talking about the code block containing the for loop? That was an example of what to not do. But if you want to test it out, make a new project and choose a test variable for `income`.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52214791

http://stackoverflow.com/comment/91417344
has text: How many rows? Number of colums? Datatypes used?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52220794
type: QuestionComment

http://stackoverflow.com/comment/91309335
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52150848
type: Comment
has text: What you are proposing is to do it manually and that is not what I need

http://stackoverflow.com/comment/91248763
score: 0
type: Comment
type: QuestionComment
has text: @Zero: In my case the number of features is not equal in the original X and X_new. I saw this solution, but I do not understand what is "feature_selector.get_support": `X_selected_df = pd.DataFrame(X_new, columns=[X.columns[i] for i in range(len(X.columns)) if feature_selector.get_support()[i]])`
comment on: http://stackoverflow.com/q/52149376

http://stackoverflow.com/q/52145803
tagged with: minimum
has answer: http://stackoverflow.com/a/52145849
possible better answer: http://stackoverflow.com/a/52145881
has answer: http://stackoverflow.com/a/52145881
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52145899
has body: I have two arrays a=([2,3,5]) and b=([-2,3.2,10]) How can I get minimum value from these two arrays? Expected answer is -2
duplicate of: http://stackoverflow.com/q/10012788
has title: Minimum value from two arrays
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/10012788
upvote count: 3
score: 0
downvote count: 3
has answer: http://stackoverflow.com/a/52145908
tagged with: python
answer count: 4
favorite count: 0
accepted answer: http://stackoverflow.com/a/52145899

http://stackoverflow.com/q/52250218
linked to: http://stackoverflow.com/q/27652543
has comment: http://stackoverflow.com/comment/91451052
has comment: http://stackoverflow.com/comment/91449709
has comment: http://stackoverflow.com/comment/91471828
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91473104
has comment: http://stackoverflow.com/comment/91448641
tagged with: python
tagged with: python-requests
score: 2
type: AnsweredQuestion
has body: I am using the Python Requests module (v. 2.19.1) with Python 3.4.3, calling a function on a remote server that generates a .csv file for download. In general, it works perfectly. There is one particular file that takes >6 minutes to complete, and no matter what I set the timeout parameter to, I get an error after exactly 5 minutes trying to generate that file. import requests s = requests.Session() authPayload = {'UserName': 'myloginname','Password': 'password'} loginURL = 'https://myremoteserver.com/login/authenticate' login = s.post(loginURL, data=authPayload) backupURL = 'https://myremoteserver.com/directory/jsp/Backup.jsp' payload = {'command': fileCommand} headers = {'Connection': 'keep-alive'} post = s.post(backupURL, data=payload, headers=headers, timeout=None) This times out after exactly 5 minutes with the error: File "/usr/lib/python3/dist-packages/requests/adapters.py", line 330, in send timeout=timeout File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 612, in urlopen raise MaxRetryError(self, url, e) urllib3.exceptions.MaxRetryError: > HTTPSConnectionPool(host='myremoteserver.com', port=443): Max retries exceeded with url: /directory/jsp/Backup.jsp (Caused by &lt; class 'http.client.BadStatusLine'>: '') If I set timeout to something much smaller, say, 5 seconds, I get a error that makes perfect sense: urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='myremoteserver.com', port=443): Read timed out. (read timeout=5) If I run the process from a browser, it works fine, so it doesn't seem like it's the remote server closing the connection, or a firewall or something in-between closing the connection.
accepted answer: http://stackoverflow.com/a/52264975
downvote count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/52264975
linked to: http://stackoverflow.com/q/18478013
answer count: 1
has comment: http://stackoverflow.com/comment/91472544
has comment: http://stackoverflow.com/comment/91451561
has title: Python Requests post times out despite timeout setting

http://stackoverflow.com/comment/91310591
type: Comment
comment on: http://stackoverflow.com/a/52180189
type: AnswerComment
has text: I tried this: and still get the error...
score: 0

http://stackoverflow.com/a/53730663
accepted answer of: http://stackoverflow.com/q/52267964
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52267964
type: Answer
has body: Here's what I did. In case somebody needs a problem like this solved. This code can be optimized but I just didn't have the time atm. Assumes: date is in format [anything] DD [anything] month (written) [anything] YYYY Assumes: If the day is not specified, number 1 is preferred. Same for months. import re def validate_date(d,m,y): leap = False valid = False y = int(y) d = int(d) m = int(m) if(y % 400 == 0): leap=True if(y % 100 == 0): leap = False if(y % 4 == 0): leap = True if (m&lt;13): if (m == 1 | m==3 | m== 5 | m==7 | m==8 | m==10 | m==12 ): if (d &lt;=31): valid=True if (m == 4 | m==6 | m==9 | m==11 ): if (d &lt;= 30): valid = True if (m==2): if (leap == True): if (d &lt;= 29): valid = True if (leap == False): if (d &lt;= 28): valid = True return valid months = { 1: "januari", 2: "februari", 3: "mars", 4: "april", 5: "maj", 6: "juni", 7: "juli", 8: "augusti", 9: "september", 10: "oktober", 11: "november", 12: "december" } def validate(date): month=0 day=0 year=0 raw_date = str(date) #get the integers in the text raw_date = raw_date.lower() if (not ("q1" in raw_date or "q2" in raw_date or "q3" in raw_date or "q4" in raw_date)): if (len(re.findall('\d+', raw_date))==2): day, year = map(int, re.findall('\d+', raw_date)) elif (len(re.findall('\d+', raw_date))==3): day, month, year = re.findall('\d+', raw_date) else: if (len(re.findall('\d+', raw_date))==2): quarter, year = map(int, re.findall('\d+', raw_date)) day = 1 #Set month to the string found, if any. if (month==0): if (months.get(1) in raw_date or ("q1" in raw_date)): month = 1 elif(months.get(2) in raw_date): month = 2 elif(months.get(3) in raw_date): month = 3 elif(months.get(4) in raw_date or ("q2" in raw_date)): month = 4 elif(months.get(5) in raw_date): month = 5 elif(months.get(6) in raw_date): month = 6 elif(months.get(7) in raw_date or ("q3" in raw_date)): month = 7 elif(months.get(8) in raw_date): month = 8 elif(months.get(9) in raw_date): month = 9 elif(months.get(10) in raw_date or ("q4" in raw_da…
score: 0

http://stackoverflow.com/a/52133736
score: -1
answers question: http://stackoverflow.com/q/52133437
upvote count: 0
type: Answer
downvote count: 1
has body: The first code version always checks all the digits, even if it knows the number can't be a palindrome. The second code version doesn't do that.

http://stackoverflow.com/comment/91261188
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52134482
score: 0
has text: Hi Hitobat, I tried using `static` array as you mentioned but the core dumped issue still persists. I even tried allocating memory with `malloc` but still got the same error. Although data array getting out of scope as the function finishes is logical to think, I suspect that there is some problem in writing data in `pyArr`. I have updated the code with `malloc` implementation to hold memory for data array which also produces `core dumped` problem. Any help is appreciated.

http://stackoverflow.com/q/52269522
answer count: 1
tagged with: python
tagged with: ckan
type: AnsweredQuestion
has body: How does CKAN fetch data from a database? How does it retrieve data from a Link while viewing it (when we are not using Datastore)? I am using CKAN 2.7.2.
type: Question
tagged with: fiware
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/52276902
has title: Fetching/Retrieval of Data from CKAN?
accepted answer: http://stackoverflow.com/a/52276902

http://stackoverflow.com/comment/91343323
has text: @Jay. Then select the answer by clicking on the check mark next to it.
score: 0
comment on: http://stackoverflow.com/a/52196959
type: Comment
type: AnswerComment

http://stackoverflow.com/a/52165280
answers question: http://stackoverflow.com/q/52165037
type: Answer
score: 3
upvote count: 3
downvote count: 0
has body: The property cycler can comprise of different properties, such as color, maker, linestyle etc. When setting the property cycler via ax1.set_prop_cycle(marker=[...]) you create a new property cycler which only contains a marker property, but no color. In order to have a marker and color property you either need to set both, or extent the current property cycler by the property you want to change. The latter would be shown in the following. from matplotlib import pyplot as plt import numpy as np fig, (ax1,ax2) = plt.subplots(nrows=2) cycler = plt.rcParams["axes.prop_cycle"] cycler += plt.cycler(marker=['o','s','x','+','*']) ax1.set_prop_cycle(cycler) colors = plt.rcParams["axes.prop_cycle"].by_key()["color"] cycler2 = plt.cycler(color=colors) cycler2 *= plt.cycler(marker=['o','s','x','+','*']) ax2.set_prop_cycle(cycler2) xx = np.arange(10) for n in xx: ax1.plot(xx, n*xx) ax2.plot(xx, n*xx) plt.show() Note the difference between addition and multiplication here.

http://stackoverflow.com/comment/91196313
type: Comment
has text: Also, you're missing the key from the first test example
comment on: http://stackoverflow.com/q/52121773
score: 0
type: QuestionComment

http://stackoverflow.com/q/52231908
has answer: http://stackoverflow.com/a/52231979
score: 0
tagged with: pandas
has body: I want to convert the id's of an dataframe into an alphabetical list based on the index value. Then I need to apply that "alpha" value to another dataframe with the data that will be listed. so instead of this data showing the client id number: 2011-05-13 #483 .... 2011-05-13 #483 .... 2011-05-13 #553 .... 2011-05-13 #555 .... with this index of the list: #483 - Client 1 #551 - Client 2 #553 - Client 3 #554 - Client 4 #555 - Client 5 So I want the data output to be something like this: 2011-05-13 #A .... 2011-05-13 #A .... 2011-05-13 #C .... 2011-05-13 #D .... Index becomes: #A - Client 1 #B - Client 2 #C - Client 3 #D - Client 4 #F - Client 5 I am using Pandas and this is the client dataframe. Can I create the alpha list based on the index? df_accts id client 0 483 Client 1 1 551 Client 2 2 553 Client 3 3 554 Client 4 4 555 Client 5 There will be between 1 ad 15 clients per report so no need to worry about things like AA or BB. thank so much.
accepted answer: http://stackoverflow.com/a/52231979
tagged with: python
has comment: http://stackoverflow.com/comment/91413220
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91413189
has comment: http://stackoverflow.com/comment/91413171
type: Question
has title: Convert numbers (index values) to Alphabet values with Pandas
answer count: 1

http://stackoverflow.com/comment/91281021
score: 0
has text: thanks for reply can you give an example
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52165430

http://stackoverflow.com/comment/91339606
comment on: http://stackoverflow.com/q/52194981
score: 0
type: Comment
type: QuestionComment
has text: @WelcometoStackOverflow Thanks for this. Yes, I understand, I will try to edit this. Unfortunately, the actual code is very long. I try to do a code to mimic my problem.

http://stackoverflow.com/comment/91274648
type: AnswerComment
has text: @Alollz I'm getting an error with your first solution 'type' object is not iterable?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52155279

http://stackoverflow.com/q/52254931
type: UnansweredQuestion
tagged with: curve-fitting
tagged with: python
linked to: http://stackoverflow.com/q/41600370
has comment: http://stackoverflow.com/comment/91458862
downvote count: 0
score: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/91460581
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/21566379
has comment: http://stackoverflow.com/comment/91460943
linked to: http://stackoverflow.com/q/40829791
has title: Result from function not a proper array of floats using optimize.curve_fit
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91459279
favorite count: 0
has answer: http://stackoverflow.com/a/52261592
has body: I have recorded experimental temperatures at five locations from the surface of a solid. At every time step, I want to fit these readings to a theoretical curve defined by my function: Temp_Function_JLT(X,h). X is a multi-dimensional array that includes the x_coordinates as well as time, initial temperature and material properties (all independent variables). "h" is the heat transfer coefficient, which for the purpose of this exercise I'm trying to optimize (leaving the physics aside for a moment.) This is the definition of my temperature function: import pandas as pd import numpy as np import matplotlib.pyplot as plt import pickle import scipy.optimize as opt from scipy.special import erfc def Temp_Function_JLT(X,ht): # Work around the fact that only one independent variable can be passed to optimize.curve_fit x,t,T0,q,alpha,rho,c,k = X term_a = q/ht term_b = erfc(x/np.sqrt(4*alpha*t)) term_c = np.exp(((ht*x)/(np.sqrt(alpha)*np.sqrt(k*rho*c)))+((ht**2)/(k*rho*c))) term_d = erfc((ht*np.sqrt(t))/(np.sqrt(k*rho*c)) + (x/np.sqrt(4*alpha*t))) Temperature = (term_a * (term_b - term_c * term_d)) + T0 - 273 return Temperature The function works. I can run it with some initial parameters and obtain sensible values. More importantly for this question, if I call it with the following data: t = 1 x_test = np.linspace(0.004,0.02,5) # TC locations time_test = range(1,180,30) T0_test = 25 + 273 q_test = 20000 h_test = 10 I will obtain a numpy array as a solution of shape (1,) which gives an answer to np.ndim of 1 (This has been mentioned in the following previous questions: Least Linear Squares: scipy.optimize.curve_fit() throws "Result from function call is not a proper array of floats." Fitting a vector function with curve_fit in Scipy Fitting a 2D Gaussian function using scipy.optimize.curve_fit - ValueError and minpack.error The problem arises when I call opt.curve_fit(). indepth_temperatures is a list that contains each test as an array. I iterate over it (to iterate over ea…

http://stackoverflow.com/q/52247443
has body: I am trying to fit data taken from xlsx file with decision tree classifier but i am getting error "ValueError: could not convert string to float: 'E-50'". Following is my code from my Jupyter Notebook: import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn import tree from sklearn.tree import DecisionTreeClassifier results = pd.read_excel("new3.xlsx") Y = np.array(results.values[:, 1:9]) X= np.array(results.values[:,0]) X_Train,X_Test,Y_Train,Y_Test= train_test_split(X,Y, test_size = 0.3, random_state = 176) model = DecisionTreeClassifier() model.fit(X_Train,Y_Train)
favorite count: 0
has title: Decision tree classifier fit function throwing error "ValueError: could not convert string to float: 'E-50'"
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91442913
type: Question
has comment: http://stackoverflow.com/comment/92006760
has comment: http://stackoverflow.com/comment/91443326
has comment: http://stackoverflow.com/comment/91442986
downvote count: 0
tagged with: jupyter
tagged with: decision-tree

http://stackoverflow.com/q/52129445
score: -2
downvote count: 5
accepted answer: http://stackoverflow.com/a/52129847
tagged with: http://stackoverflow.com/tag/r
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/5963269
has body: I've written the following function in Python. For any date it works out the correct Week Ending or Commencing date. I can't figure out how to write this in R. Anyone have any ideas? def Week_dates(dt, day, we=False): """ dt is a date day is string like 'sat' or 'mon' """ day = day.lower() days = ['mon','tue','wed','thu','fri','sat','sun'] if we: day_num = (days.index(day) + 1) % 7 else: day_num = days.index(day) day_offset = (dt.weekday() + 7-day_num) % 7 return dt - timedelta(days=day_offset) + timedelta(days=(6 * we))
tagged with: python
tagged with: code-translation
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52129847
upvote count: 3
has title: Weekday alogorithm conversion from Python into R?
type: Question
has comment: http://stackoverflow.com/comment/91209230

http://stackoverflow.com/comment/91440539
type: Comment
has text: Running this now, will let you know if we hit ~950 recursions. If we this works, I believe the problem can be atrributed to the amount of threads at one time or something like that. Will let you know and accept if this fixes the problem :) Thanks for the suggestion. So far so good.
type: AnswerComment
comment on: http://stackoverflow.com/a/52246132
score: 0

http://stackoverflow.com/q/52225108
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/52225329
has answer: http://stackoverflow.com/a/52225329
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52225235
accepted answer: http://stackoverflow.com/a/52225235
tagged with: letters-and-numbers
has answer: http://stackoverflow.com/a/52225479
has title: How can I get letters in an expression on Python
type: Question
has body: I have this expression: And I need to get the 10 letters next to "/dp/" (B01J5FGW66) How can I make a function that do this?
tagged with: expression

http://stackoverflow.com/q/52261567
score: 0
possible better answer: http://stackoverflow.com/a/52262014
has comment: http://stackoverflow.com/comment/91471581
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: python
has body: I have a user model in Django in which the usertype field is "administrator" for teachers and "student" otherwise. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=False) username = models.CharField(max_length=25, unique=True) password = models.CharField(max_length=50) usertype = models.CharField(max_length=140, null=True) teacher = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null = True ) objects = UserManager() I also have a Django model for student data: class Row(models.Model): user = models.TextField(max_length=500, blank=True) question = models.TextField(max_length=500, blank=True) answer = models.TextField(max_length=500, blank=True) When a teacher is logged in, I display their list of students and want them to be able to view a copy of the student's data (a modal should pop up). Students Directory: Name Email Download Data {% for student in usertable %} {{ student.first_name }} {{ student.last_name}} {{ student.email }} Download Link {% endfor %} So, I pass the student's username into viewData() and that should pop up the modal. However, the function is written in javascript and I can't do something like - "Row.objects.all.filter(username=username)". However, I can't pass the already filtered object into the profile.html because I don't know which student's username I will need. There's probably an easy solution to this that I'm missing somewhere. TLDR - in my profile.html project I want to click a button and pop up a modal with my Django model filtered by a certain username (which can vary)
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52262014
has comment: http://stackoverflow.com/comment/91471269
has answer: http://stackoverflow.com/a/52262076
accepted answer: http://stackoverflow.com/a/52262076
type: Question
answer count: 2
has title: Django teacher-student model filtering data

http://stackoverflow.com/q/52210707
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52210732
has comment: http://stackoverflow.com/comment/91371068
has answer: http://stackoverflow.com/a/52210959
score: 0
has answer: http://stackoverflow.com/a/52210817
answer count: 3
has body: I want to find the 5 upstream words of the found match word in a string. Example. I hav string This is the most Absurd rat ever in the history I want to search for "rat" and then get the 4 words of upstream of found "rat word I tried using re.search(r'\brat\b', " This is the most Absurd rat in the history") But it gives me the space position like span(25,28), but how would i use it to get the words. If i would know the position in terms of the word, then I can simply get the 4 index up/down words.
possible better answer: http://stackoverflow.com/a/52210959
favorite count: 0
has answer: http://stackoverflow.com/a/52210732
tagged with: python
tagged with: regex
type: AnsweredQuestion
has title: find the upstream 5 words of matched word in python
has comment: http://stackoverflow.com/comment/91371055
upvote count: 1

http://stackoverflow.com/q/52268287
has answer: http://stackoverflow.com/a/68264056
favorite count: 0
has body: I'm attempting to do lesson 2 of my python coding class and I'm running into a misunderstanding. The book asks me to "Extend to also output in reverse." The code should output like this (assuming input 99, 3.77, z, Howdy) Enter integer (0 - 155): 99 Enter float: 3.77 Enter character: z Enter string: Howdy 99 3.77 z Howdy Howdy z 3.77 99 However when I run the code I am getting this error: Enter integer (0 - 155): Enter float: Enter character: Enter string: 99 3.77 z Howdy Enter integer (0 - 155): Traceback (most recent call last): File "main.py", This is what my code actually looks like: # FIXME (1): Finish reading other items into variables, then output the four values on a single line separated by a space userInt = int(input('Enter integer (0 - 155):\n')) userFloat = float(input('Enter float:\n')) userCharacter = str(input('Enter character:\n')) userString = str(input('Enter string:\n')) print(userInt, userFloat, userCharacter, userString, '\n') # FIXME (2): Output the four values in reverse userInt = int(input('Enter integer (0 - 155):\n')) userFloat = float(input('Enter float:\n')) userCharacter = str(input('Enter character:\n')) userString = str(input('Enter string:\n')) print(userInt, userFloat, userCharacter, userString, userString, userCharacter, userFloat, userInt) I've tried a few different things but no matter what I do it keeps highlighting a space after the 'Howdy' and then highlighting a return then printing out that traceback error message. I dont know what it means and I'm not sure how to fix it. Thanks so much for any input!
has answer: http://stackoverflow.com/a/70706824
has answer: http://stackoverflow.com/a/66485448
has answer: http://stackoverflow.com/a/52268346
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52268341
accepted answer: http://stackoverflow.com/a/52268341
possible better answer: http://stackoverflow.com/a/70706824
score: 1
has title: Problems reversing output in Python - Student question
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/67426920
answer count: 6
tagged with: reverse
downvote count: 1
tagged with: python

http://stackoverflow.com/comment/91451861
type: Comment
has text: @AdrianW I made these change and it has shortened my code and I learn something new, but still didn't make my code give the desired output
score: 0
comment on: http://stackoverflow.com/q/52252031
type: QuestionComment

http://stackoverflow.com/comment/91319817
type: AnswerComment
comment on: http://stackoverflow.com/a/52176484
type: Comment
has text: @MadPhysicist: you needn't tell me. But it is not necessary to recompute the number of bits every time, which is what this test amounts to. (Though the overhead is tiny.)
score: 0

http://stackoverflow.com/a/52252702
has body: Default parameters are a language agnostic feature designed to help programmers. Let us consider your example def calc_tax(sales_total,tax_rate=0.04): print(sales_total * tax_rate) We can call the function as calc_tax(100) (Notice how I dont even have to mention 0.04 as the function will automatically take the default value) and calc_tax(100,0.09) Where in the first case , the default value of tax_rate i.e. 0.04 is used and you get a same answer as what print(sales_total*0.04) Now, if at any point you want to change this value , say to 0.09 then by your method we would have to go to the source code and modify the function. Sometimes this isn't entirely possible or may not be as simple as the example you provided , as in the case where this tax_rate is used multiple times in the function. If you are 100% sure that a value will never change , for like constants like pi then in that case they are not passed into the function parameters but for other cases it is both simpler and more efficient to use default parameters.
answers question: http://stackoverflow.com/q/52252354
score: 0
type: Answer

http://stackoverflow.com/q/52183096
downvote count: 0
tagged with: file
type: Question
tagged with: temporary-files
upvote count: 6
has title: How to use io to generate in memory data streams as file like objects?
has answer: http://stackoverflow.com/a/52184671
has answer: http://stackoverflow.com/a/52183343
accepted answer: http://stackoverflow.com/a/52184671
has body: I want to generate a in-memory (temp file) data stream in Python. One thread is filling the stream with data, and a other one consumes it. After checking the io - Core tools for working with streams , it seems to me that the io module is the best choice for it. So I made a simple example: #!/usr/local/bin/python3 # encoding: utf-8 import io if __name__ == '__main__': a = io.BytesIO() a.write("hello".encode()) txt = a.read(100) txt = txt.decode("utf-8") print(txt) My example does not work. "hello" is not written to a and can not be read after. So where is my error? How do I have to alter my code to get a file like object in memory?
answer count: 2
favorite count: 0
tagged with: io
score: 6
tagged with: python
possible better answer: http://stackoverflow.com/a/52183343
type: AnsweredQuestion

http://stackoverflow.com/comment/91558594
comment on: http://stackoverflow.com/a/52256469
has text: plt.plot(zz) plt.plot(peaks, zz[peaks],'o') ,, how do i get this to plot over t instead of starting from 0? so that my 2 graphs will be 1 instead?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91303091
has text: `df['order_n'] = df.groupby(level=0).cumcount()+1`
type: QuestionComment
comment on: http://stackoverflow.com/q/52176242
type: Comment
score: 0

http://stackoverflow.com/q/52162441
tagged with: arcpy
answer count: 2
has answer: http://stackoverflow.com/a/52163201
favorite count: 0
has answer: http://stackoverflow.com/a/52163768
type: UnansweredQuestion
has title: replace part of URL while exporting?
tagged with: python
has body: I have a list called shapelist that has: shapelist ['C:\\Users\\user\\Desktop\\pl\\v1\\ASTN\\ASTN.shp', 'C:\\Users\\user\\Desktop\\pl\\v2\\ASTN\\ASTN.shp'] and I want to replace the last part of the directory by maintaining part of the list's contents directory. Example: in this loop: for i in shapelist: arcpy.FeatureToLine_management([i],i.replace('\\ASTN\\ASTN.shp','\\exported\\ASTN_li')) Gives error: 000210 Description The output cannot be created. Potential reasons include data locking, an incorrect path, and limited access rights. If I do it like this it works though. arcpy.FeatureToLine_management([i],i.replace('ASTN.shp','ASTN_li')) The problem with this is that it saves it to a location that is not wanted. Do you know how to save it like the first attempt or an alternative way to save it in that specific location?
score: 0
tagged with: loops
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/comment/91224058
type: AnswerComment
has text: I just sharing a link of result getting `https://drive.google.com/open?id=1aRLhQM4UuOulJ9LobPkXOERCMAzAGQYw`. Why am I getting duplicate values?
score: 0
comment on: http://stackoverflow.com/a/52132145
type: Comment

http://stackoverflow.com/comment/91367929
score: 0
type: Comment
type: QuestionComment
has text: @curious_cosmo have you solved this? If so, I think you should mark it as solved so people don't keep posting answers
comment on: http://stackoverflow.com/q/52194717

http://stackoverflow.com/q/52215329
has title: How to go about monitoring change?
type: Question
has comment: http://stackoverflow.com/comment/91380881
has body: Backstory: I'm currently developing a program that has several qComboBox and qLineEdit elements that a user can enter data into or select a value. When the user selects "New File" or "Open File" I want to check if any values have changed, and present the user with the option to save their work. The output file is XML. Problem: Basically, I just need to know if any of the values are different than the default values. I'm not concerned with what exact values are different, I just need to know that they are different. I have tried using xmldiff by creating an Element Tree that contains the initial values when the program starts, then comparing that to a second Element Tree with the current values. It does not appear to be capable of just giving a true or false value, and the second Element Tree varies in size so I don't think I can simply do a 1 for 1 comparison. The second thing I tried was simply setting a boolean value when the element changed, but I couldn't account for an element being reset to a default value. For example if a qLineEdit box had no value, and a user input something, that would set the boolean value to "true"; however, if they went back in and changed that value back to the default value the result would be "true" as well. I was wondering if there is a "best practice" for doing this type of thing, or if someone could point me in the right direction. This seems like it should be trivial for the most part, but I don't know how to approach this. EDIT … Added example for second attempt. import sys from PyQt5.QtWidgets import * class Window(QWidget): def __init__(self): super(Window, self).__init__() self.modified = False self.edit1 = QLineEdit() layout = QGridLayout(self) layout.addWidget(self.edit1) self.edit1.editingFinished.connect(self.valueChanged) def valueChanged(self): print('valueChanged Event') self.modified = True def closeEvent(self, event): if self.modified: prompt = QMessageBox.warning( self, 'Save Changes?', 'This document has been modif…
linked to: http://stackoverflow.com/q/3765222
tagged with: pyqt
linked to: http://stackoverflow.com/q/1325673
answer count: 1
favorite count: 0
score: 0
has answer: http://stackoverflow.com/a/52215940
has comment: http://stackoverflow.com/comment/91407022
has comment: http://stackoverflow.com/comment/91379656
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91379644
linked to: http://stackoverflow.com/q/7905380
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91407406
tagged with: pyqt5
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91381033
linked to: http://stackoverflow.com/q/739654

http://stackoverflow.com/comment/91331455
type: Comment
type: QuestionComment
has text: if first word starts with No and last word ends with number(6 digit) then whole starting from first word till last digits will be output
comment on: http://stackoverflow.com/q/52190644
score: 0

http://stackoverflow.com/q/52230370
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52231003
has title: In the Python debugger, how to step into the second method call on a line?
tagged with: pdb
type: Question
tagged with: debugging
answer count: 2
possible better answer: http://stackoverflow.com/a/59685156
has answer: http://stackoverflow.com/a/52231003
score: 0
has body: I'm trying to debug something in Django, and at some point in ipdb I ended up at the following stack trace: ipdb&gt; u &gt; /Users/kurtpeek/Documents/Dev/lucy2/lucy-web/dashboard/views/base.py(191)get() 190 def get(self, request, *args, **kwargs): --&gt; 191 self.object = self.get_object() 192 return super().get(request, *args, **kwargs) I would like to step into the call to get_object(). However, if I type the s command, it steps into the self.object call (which is the __get__ method of the object, Django view): ipdb&gt; s --Call-- &gt; /Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django/db/models/manager.py(176)__get__() 175 --&gt; 176 def __get__(self, instance, cls=None): 177 if instance is not None: Is it possible to step into the second method call on the line, not the first one? I've tried perusing the commands on https://docs.python.org/3/library/pdb.html#debugger-commands but couldn't find any.
has answer: http://stackoverflow.com/a/59685156
tagged with: ipdb
tagged with: python

http://stackoverflow.com/a/52115337
has comment: http://stackoverflow.com/comment/91244248
has comment: http://stackoverflow.com/comment/91244172
answers question: http://stackoverflow.com/q/52115252
score: 0
type: AcceptedAnswer
has body: Note: It is not a good idea to use GET requests to perform side-effects (like updating or removing records in a database). Therefore I would advice to change such requests to a POST, DELETE or PATCH. More information at the bottom of this post. Based on the log you show, the delete call ships with two parameters in the querystring: operation and id. But the first if statement requires a text parameter as well: def basetest(request): cu_id = request.user.id if 'operation' in request.GET and "id" in request.GET and "text" in request.GET: operation = request.GET['operation'] pid=request.GET['id'] nodename=request.GET['text'] if "create_node" == operation: p=Buildkb4.objects.create (parent=pid,created_by=cu_id,text=nodename) p.save() elif "delete_node" == operation: Buildkb4.objects.filter(pk=pid).delete() elif "rename_node" == operation: Buildkb4.objects.filter(pk=pid).update(text=nodename) return render(request,"registration/basetest.html") So this will never reach the elif "delete_node" == operation: case. You can fix this by making the check less restrictive, something like: def basetest(request): cu_id = request.user.id if 'operation' in request.GET and "id" in request.GET: operation = request.GET['operation'] pid=request.GET['id'] if "delete_node" == operation: Buildkb4.objects.filter(pk=pid).delete() elif 'text' in request.GET: nodename=request.GET['text'] if "create_node" == operation: p=Buildkb4.objects.create(parent=pid,created_by=cu_id,text=nodename) elif "rename_node" == operation: Buildkb4.objects.filter(pk=pid).update(text=nodename) return render(request,"registration/basetest.html") Now it will work. But a GET is supposed to have no side-effects. So you are basically violating a contract of GET requests. Typically a delete is performed through a POST, or a DELETE request, not a GET request. Changing data is also handled by a POST or PATCH request, again not a GET request. By making GET requests with side-effects, it can happen that robots (like search eng…
type: Answer
accepted answer of: http://stackoverflow.com/q/52115252

pagination
tags question: http://stackoverflow.com/q/52212037
tag name: pagination
tags question: http://stackoverflow.com/q/52158893
type: Tag

http://stackoverflow.com/comment/91316315
has text: oh, that's unlucky, ty for your answer
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52183201
score: 0

http://stackoverflow.com/q/52184465
type: AnsweredQuestion
tagged with: selenium
possible better answer: http://stackoverflow.com/a/52184827
type: Question
has title: how to open different urls at the same time by using python selenium?
accepted answer: http://stackoverflow.com/a/52184657
has answer: http://stackoverflow.com/a/52184629
score: 0
answer count: 3
tagged with: multithreading
tagged with: python
has body: is this possible to open 50 different urls at the same time using selenium with python? is this possible using threading? If so, how would I go about doing this? If not, then what would be a good method to do so?
has answer: http://stackoverflow.com/a/52184827
has answer: http://stackoverflow.com/a/52184657

http://stackoverflow.com/a/52261799
has body: Your issue is that drop_duplicates is dropping based on the columns, which in this case is just 'State'. You want to keep non-duplicated indices so you should instead use pandas.Index.duplicated to mask the original DataFrame df[~df.index.duplicated(keep='first')]
upvote count: 2
has comment: http://stackoverflow.com/comment/91471394
score: 2
has comment: http://stackoverflow.com/comment/91471463
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52261675
answers question: http://stackoverflow.com/q/52261675
type: Answer
has comment: http://stackoverflow.com/comment/91471415

http://stackoverflow.com/a/52130579
downvote count: 0
has comment: http://stackoverflow.com/comment/91211507
type: Answer
accepted answer of: http://stackoverflow.com/q/52130403
upvote count: 1
has body: primeListreturns primes up to but less than x. If x in primeFactorizer is a prime number, x%p is never true inside the for-loop, therefore x never changes. Forget about the primes and test every number for factorization: def factorize(number): factors = [] for factor in range(2, number + 1): while number % factor == 0: factors.append(factor) number //= factor print(number) if number == 1: break return factors print(factorize(36))
answers question: http://stackoverflow.com/q/52130403
score: 1
has comment: http://stackoverflow.com/comment/91211767
type: AcceptedAnswer

http://stackoverflow.com/a/52128508
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91207549
has body: You can use map on the index of df to chek whether it is in df_res and set the value accordingly as shown below. df = pd.DataFrame() df['X'] = [1, 2, 3, 4, 5, 6] df['Y'] = [10, 20, 30, 40, 50, 60] df_res = df.loc[df['X'] &gt; 3] df['C'] = df.index.map(lambda x : 1 if x in df_res.index else 0) OR you can do like this df['C'] = [1 if x in df_res.index else 0 for x in df.index]
has comment: http://stackoverflow.com/comment/91207538
type: Answer
has comment: http://stackoverflow.com/comment/91207465
accepted answer of: http://stackoverflow.com/q/52128445
has comment: http://stackoverflow.com/comment/91207460
answers question: http://stackoverflow.com/q/52128445
score: 2
upvote count: 2

http://stackoverflow.com/a/52247172
accepted answer of: http://stackoverflow.com/q/52243451
answers question: http://stackoverflow.com/q/52243451
type: Answer
has body: Consider generating separate country plots with a secondary axis since you are tracking two metrics of different scales: Income and Fertility. For this setup, you will need to reshape your wide format to long with pandas.melt(). Then, iterate through the distinct countries to filter the data frames. Data import numpy as np import pandas as pd import matplotlib.pyplot as plt df1 = pd.DataFrame({'Country': ['A', 'B', 'C'], 'Year 1': [50, 70, 10], 'Year 2': [30, 20, 20], 'Year 3': [20, 90, 30]}) df1 = df1.melt(id_vars='Country', value_name='Income', var_name='Year') df2 = pd.DataFrame({'Country': ['A', 'B', 'C'], 'Year 1': [1.5, 2, 1], 'Year 2': [2.0, 2, 1], 'Year 3': [2.5, 3, 4]}) df2 = df2.melt(id_vars='Country', value_name='Fertility', var_name='Year') Plot for c in df1['Country'].unique(): fig, ax1 = plt.subplots(figsize=(10,4)) ax2 = ax1.twinx() df1[df1['Country']==c].plot(kind='line', x='Year', y='Income', ax=ax1, color='g', legend=False) df2[df2['Country']==c].plot(kind='line', x='Year', y='Fertility', ax=ax2, color='b', legend=False) plt.title('Country ' + c) ax1.set_xlabel('Years') ax1.set_ylabel('Average Income Per Year') ax2.set_ylabel('Fertility Rate') lines = ax1.get_lines() + ax2.get_lines() ax1.legend(lines, [l.get_label() for l in lines], loc='upper left') ax1.set_xticks(np.arange(3)) ax1.set_xticklabels(df1["Year"].unique()) plt.show() plt.clf() plt.close()
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91237394
type: Comment
type: QuestionComment
has text: OK, which part of that code is opening file handles?
comment on: http://stackoverflow.com/q/52119326
score: 0

http://stackoverflow.com/comment/91379598
comment on: http://stackoverflow.com/a/52215230
type: Comment
score: 0
type: AnswerComment
has text: That's a good idea - I usually use "for word in words" for sentence problems, but when I attempted the while loop it seemed odd to call it 'word', but your example using the name words_index makes sense to me now.

http://stackoverflow.com/q/52147707
tagged with: python
has title: Shorten for loop for getting paths
has comment: http://stackoverflow.com/comment/91245724
score: 0
type: UnansweredQuestion
tagged with: for-loop
answer count: 0
has comment: http://stackoverflow.com/comment/91245550
has body: I'm currently trying to get the whole pathname of txt files in multiple directories. The directory structure looks something like this containing a couple thousand image-folder: root_dir image1 image1.gt.txt image1.stuff.png image1.stuff2.png image2 image2.gt.txt etc The current code is: for root, dirs, files in os.walk(pathname, topdown=False): for file in files: if file.split('.')[-1] == 'txt': gt_txt = file full_path = os.path.join(root, gt_txt) Is there a way to shorten this loop in terms of code and/or runtime or is it even reasonable to shorten it?
type: Question

http://stackoverflow.com/q/52214698
accepted answer: http://stackoverflow.com/a/52214983
tagged with: recursion
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91378684
has title: Calculating Napier constant (e) using recursion
has body: I am attempting to approximate the value of e (~2.7) Defined by this, for each nth term using a recursive function in python. So far I have gotten this, def NapierConstant(runs): return 2 + 1/contfrac(1, 2, runs) def contfrac(v1, v2, limit): if v1 == limit: return (v1/v2) else: return v1+(v1/contfrac(v1+1, v2+1, limit)) print(NapierConstant(2)) this should output 2.72727 here, but instead I get 2.4, and the error margin get's worse for each following step. I have googled, and I can't manage to figure out how to set up the function recursively so that it outputs the expected values.
type: Question
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91378787
favorite count: 0
has answer: http://stackoverflow.com/a/52214983
tagged with: python
has comment: http://stackoverflow.com/comment/91378864
score: 1
tagged with: python-3.x
upvote count: 1

http://stackoverflow.com/comment/91257951
has text: Ok, did it with `unalias`. It's working now. Thanks!
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52153469

http://stackoverflow.com/comment/91282312
comment on: http://stackoverflow.com/a/52164125
type: AnswerComment
score: 0
has text: It doesn't work either... I get that : `Collecting pyasn1-modules Using cached https://files.pythonhosted.org/packages/19/02/fa63f7ba30a0d7b925ca29d034510fc1ffde53264b71b4155022ddf3ab5d/pyasn1_modules-0.2.2-py2.py3-none-any.whl Installing collected packages: pyasn1, pyasn1-modules Found existing installation: pyasn1 0.1.9 Cannot uninstall 'pyasn1'. 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.`
type: Comment

http://stackoverflow.com/comment/91432570
comment on: http://stackoverflow.com/a/52241995
has text: I'm thinking of scanning the folders; see updated question
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91433350
comment on: http://stackoverflow.com/q/52242489
type: Comment
score: 1
type: QuestionComment
has text: @BlackThunder I don't even understand the question haha.

http://stackoverflow.com/a/52239342
type: Answer
score: 3
answers question: http://stackoverflow.com/q/52239093
upvote count: 3
has comment: http://stackoverflow.com/comment/91509326
has comment: http://stackoverflow.com/comment/91432731
accepted answer of: http://stackoverflow.com/q/52239093
has comment: http://stackoverflow.com/comment/91427896
has body: Assuming the dataframe only contains data from a single week, do: cumulative_hours = df.groupby('Employee')['Hours1'].cumsum() ot_within_day = df.OT ot_within_week = np.where(cumulative_hours - df.Hours1 &gt; 40, df.Hours1, cumulative_hours - 40) ot_CA = np.where(cumulative_hours &gt; 40, ot_within_week, ot_within_day)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52130755
tagged with: deep-learning
answer count: 0
type: UnansweredQuestion
has body: I am trying to train a neural network for image classification. I am having trouble getting my data into a proper numpy array format. To feed into the network, my array must be of dimension (9068,184,184,1). The problem is if I check the length of the array, it just returns (9068,). If I check the length of an individual element in the array, it returns (184,184,1). How can I make it so that the whole array's length will be four dimensional (9068,184,184,1) so my neural network can take it as input? Below is my code. I have a (9068,2) dataframe with the file names. I am grabbing the file name, reading it in to an array as pixel information, and storing it into another array. path = '/home/vivek/Downloads/kaggle_ndsb2-master/data_segmenter_trainset/' for ii in pairing_table['image']: new_path = os.path.join(path,ii) img = Image.open(new_path) print type(ii) for ii in range(0,len(image_table['image'])): new_path = os.path.join(path,image_table['image'][ii]) img = Image.open(new_path) img2 = np.array(img.getdata()).reshape(184, 184, -1) #print(type(img)) image_table['image'][ii] = img2 img.close() for ii in range(0,len(image_table['mask'])): new_path = os.path.join(path,image_table['mask'][ii]) img = Image.open(new_path) img2 = np.array(img.getdata()).reshape(184, 184, -1) image_table['mask'][ii] = img2 img.close() print(image_table['image'][0].shape) #this is returning (184,184,1) print(image_table['image'].shape) #this is returning (9068,) should be (9068,184,184,1) print(image_table['mask'][0].shape) #this is returning (184,184,1) print(image_table['mask'].shape) #this is returning (9068,) should be (9068,184,184,1)
tagged with: python
has comment: http://stackoverflow.com/comment/91340879
has comment: http://stackoverflow.com/comment/91213112
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91211955
tagged with: arrays
tagged with: neural-network
has comment: http://stackoverflow.com/comment/91211975
has title: How to get data into proper numpy dimension format?
score: 0

http://stackoverflow.com/comment/91293089
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52169356
score: 0
has text: Don't confuse compilation and linking. extra_compile_args are for compilation, extra_link_args are for linking.

http://stackoverflow.com/comment/91188441
comment on: http://stackoverflow.com/q/52116717
has text: @VivekKumar thanks so much, I add the code but I think this is not the most important... maybe LDA isn't stability and so sensitive... and this is my question.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52249780
has comment: http://stackoverflow.com/comment/91447748
has answer: http://stackoverflow.com/a/52250349
type: UnansweredQuestion
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91447706
has answer: http://stackoverflow.com/a/52249815
tagged with: loops
type: Question
has title: Error with code, I am unsure of what the problem is but it seems to be looping
has body: name = ["Hetty", "Poppy", "Blue Skies", "Bay View", "Happy Days", "Summer Joy", "Walkers Rest", "Bertie","Green Forest Lodge", "Coppice Lodge" ] cap = [4, 4, 4, 6, 6, 6, 8, 8, 10, 10] peak = [400, 400, 500, 650, 695, 800, 950, 1050, 1200, 1500] offpeak = [250, 250, 350, 500, 550, 600, 750, 850, 950, 1150] onoff = False cost = 0 print("Here are our avaliable lodges") for elem in name: print("- " + elem) desired_room = (str(input("Enter The Name Of The Room You Would Like To Book: "))).lower() while True: for i in range (0,10): if desired_room == name [i].lower(): print("Name: ", name[i]) print("Capacity: ", cap[i]) print("Off Peak Rate: 0" + str(offpeak[i])) print("Peak Rate: 0" + str(peak[i])) exit print("Invalid Room Name Entered Try Again") desired_room = (str(input("Enter The Name Of The Room You Would Like To Book: "))).lower() week = int(input("Enter The Week Your Stay Starts ")) This is my code. When the user inputs the the name of the room it works but then for some reason it loops and asks the user which room they want to book. How can I fix it so "Enter The Week Your Stay Starts " is asked instead of the room that the user wants to book is inputted? Picture reference https://imgur.com/a/QAtnHT9
has answer: http://stackoverflow.com/a/52249840
answer count: 3

http://stackoverflow.com/comment/91435159
type: Comment
comment on: http://stackoverflow.com/a/52227264
type: AnswerComment
score: 0
has text: Can you tell me how can this be done by using POST and not GET?

http://stackoverflow.com/q/52127228
tagged with: sqlalchemy
type: Question
has body: I have a flask app that can be initialized successfully and connects to Postgresql database. However, when i try to dockerize this app, i get the below error message. "SQLALCHEMY_DATABASE_URI" is correct and i can connect to it, so i can't figure where I have gone wrong. docker-compose logs app_1 | File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/url.py", line 60, in __init__ app_1 | self.port = int(port) app_1 | ValueError: invalid literal for int() with base 10: 'None' Postgres database connects successfully in Docker container postgres_1 | LOG: database system is ready to accept connections config.py from os import environ import os RDS_USERNAME = environ.get('RDS_USERNAME') RDS_PASSWORD = environ.get('RDS_PASSWORD') RDS_HOSTNAME = environ.get('RDS_HOSTNAME') RDS_PORT = environ.get('RDS_PORT') RDS_DB_NAME = environ.get('RDS_DB_NAME') SQLALCHEMY_DATABASE_URI = "postgresql+psycopg2://{username}:{password}@{hostname}:{port}/{dbname}"\ .format(username = RDS_USERNAME, password = RDS_PASSWORD, \ hostname = RDS_HOSTNAME, port = RDS_PORT, dbname = RDS_DB_NAME) flask_app.py (entry point) def create_app(): app = Flask(__name__, static_folder="./static", template_folder="./static") app.config.from_pyfile('./app/config.py', silent=True) register_blueprint(app) register_extension(app) with app.app_context(): print(db) -&gt; This prints the correct path for SQLALCHEMY_DATABASE_URI db.create_all() db.session.commit() return app def register_blueprint(app): app.register_blueprint(view_blueprint) app.register_blueprint(race_blueprint) def register_extension(app): db.init_app(app) migrate.init_app(app) app = create_app() if __name__ == '__main__': app.run(host='0.0.0.0', port=8080, debug=True) Dockerfile FROM ubuntu RUN apt-get update &amp;&amp; apt-get -y upgrade RUN apt-get install -y python-pip &amp;&amp; pip install --upgrade pip RUN mkdir /home/ubuntu WORKDIR /home/ubuntu/celery-scheduler ADD requirements.txt /home/ubuntu/celery-scheduler/ RUN pip install -r re…
tagged with: flask
tagged with: docker
tagged with: postgresql
answer count: 2
has answer: http://stackoverflow.com/a/52342582
downvote count: 0
has answer: http://stackoverflow.com/a/52127513
has comment: http://stackoverflow.com/comment/91631418
favorite count: 0
has comment: http://stackoverflow.com/comment/91346787
possible better answer: http://stackoverflow.com/a/52127513
score: 13
tagged with: python
upvote count: 13
accepted answer: http://stackoverflow.com/a/52342582
type: AnsweredQuestion
has title: Docker, Flask, SQLAlchemy: ValueError: invalid literal for int() with base 10: 'None'

http://stackoverflow.com/comment/91324569
type: Comment
has text: Generic unpacking creates a **huge** tuple with all integers materialised (remember that `range()` is a very lightweight object). Chaining is better!
type: AnswerComment
comment on: http://stackoverflow.com/a/52187396
score: 15

http://stackoverflow.com/a/52191491
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91332995
has comment: http://stackoverflow.com/comment/91333050
has comment: http://stackoverflow.com/comment/91333123
answers question: http://stackoverflow.com/q/52191290
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91332879
has body: You can use Javascript and get all id's in list in one line, my only complain is xpath you used //*[@id="mainContent"]/div[1]/div/div[5]/ul. I'm pretty sure you can use much better selector: #ids is a list ids = browser.execute_script("return [...document.querySelectorAll('.left-panel li')].map(e =&gt; e.getAttribute('id'));") Also you can find some solutions here: Selenium: get_attribute one condition
has comment: http://stackoverflow.com/comment/91334220

http://stackoverflow.com/comment/91370343
score: 1
type: AnswerComment
type: Comment
has text: I have no idea what you mean. Your `Rank_order` is just `[1, 2, 3, 4]` which looks nothing like a ranking of anything. Further, I've shown that you can use `rank` with the parameter `method='dense'` to adjust for duplication. You haven't explained what `Rank_Order` is and you certainly don't help matters with a comment that simply states "Rank_Duplicates"
comment on: http://stackoverflow.com/a/52210350

http://stackoverflow.com/a/52221419
has body: A seed in a random generator ensures that the pseudo-random data that is generated will be the same for the next experiment. This is used to be able to replicate experiments with "random" data. The seed is usually given as a number, in this case the authors chose the number 19680801 as a number.
upvote count: 1
has comment: http://stackoverflow.com/comment/91403222
has comment: http://stackoverflow.com/comment/91406985
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52221393
type: Answer
answers question: http://stackoverflow.com/q/52221393
score: 1

http://stackoverflow.com/q/52127980
has title: Django - TypeError: object of type 'NoneType' has no len() occurred while doing Pagination
has comment: http://stackoverflow.com/comment/91207266
has comment: http://stackoverflow.com/comment/91207056
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/91207152
possible better answer: http://stackoverflow.com/a/52128053
type: Question
has body: TypeError: object of type 'NoneType' has no len() occurs when I'm adding a pagination to a list view. This happened when I clicked next button to go to page 2. It should have two more results to show. I guess it's because the value of search is wiped or the queryset becomes none somehow, when I click next (go to page 2), then it returns none. Error: Search Form: book/views: class SearchResultView(generic.ListView): template_name = 'book/search.html' model = Book context_object_name = 'book_list' paginate_by = 2 def get_queryset(self): queryset = super().get_queryset() search = self.request.GET.get('search') if search: return Book.objects.filter( title__icontains=search ) book/templates/book.html: {% csrf_token %} Search book/templates/search.html: {% block customContents %} {% if book_list %} {% for book in book_list %} {{ book.title }} {% empty %} {% endfor %} {% if is_paginated %} {% if page_obj.has_previous %} previous {% endif %} {% if page_obj.has_next %} next {% endif %} {% endif %} {% else %} No result found. {% endif %} {% endblock %} book/urls: app_name = 'book' urlpatterns = [ path('', views.HomePageView.as_view(), name='home'), path('search/', views.SearchResultView.as_view(), name='search'), path('<slug:slug>/', views.BookDetailView.as_view(), name='detail'), ] It only works fine like this: class SearchResultView(generic.ListView): template_name = 'book/search.html' model = Book context_object_name = 'book_list' paginate_by = 2 queryset = Book.objects.filter( title__icontains='Python' )
has comment: http://stackoverflow.com/comment/91207093
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/5755150
favorite count: 0
has comment: http://stackoverflow.com/comment/91206500
has comment: http://stackoverflow.com/comment/91207196
tagged with: python
has answer: http://stackoverflow.com/a/52128053
has answer: http://stackoverflow.com/a/52130289
accepted answer: http://stackoverflow.com/a/52130289
has comment: http://stackoverflow.com/comment/91208362
has comment: http://stackoverflow.com/comment/91206409
upvote count: 3
has comment: http://stackoverflow.com/comment/91206401
has comment: http://stackoverflow.com/comment/91206847
tagged with: django

http://stackoverflow.com/q/52168700
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52169164
linked to: http://stackoverflow.com/q/17226016
upvote count: 1
has comment: http://stackoverflow.com/comment/91287972
type: Question
has title: How to import from project level package in Django without conflicting with app level module with same name?
tagged with: python-import
accepted answer: http://stackoverflow.com/a/52169164
answer count: 1
downvote count: 0
tagged with: python-2.x
score: 1
favorite count: 0
has body: I have a Django project (Python 2.7.15) with the following structure: mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py polls/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py utils.py utils/ __init__.py filters.py In my utils/filters.py file I have a class MyFilter. From polls/admin.py, however, when I try to run from utils.filters import MyFilter, I get ImportError: No module named filters. How can I import my custom filter inside the polls app without renaming the polls/utils.py module or the utils package? NOTE: This it's not a circular import problem. This happens even if I don't import anything from utils/filters.py. It's a name conflict between utils/ and polls/utils.py. Python tries to find filters.MyFilter inside polls/utils.py and it doesn't find it so it throws the error. I just want to figure out a way to bypass this conflict and force python to look for filters.MyFilter inside the utils/ package in the project root.
has comment: http://stackoverflow.com/comment/91287762
tagged with: django

http://stackoverflow.com/comment/91190200
score: 1
comment on: http://stackoverflow.com/a/52116904
has text: Well, just `return` by itself won't help, since `return` by itself returns None, and None isn't an iterator.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91237235
comment on: http://stackoverflow.com/q/52143640
has text: can you post the sample data in your question? And post the traceback.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/91179194
has text: It means any low level logic should be implemented at the module level, and the top level should just put the pieces together and not get bothered with implementation details. Because boilerplate matters
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52114395
type: QuestionComment

http://stackoverflow.com/comment/91333394
score: 0
type: Comment
has text: @davidyeritsyan I didn’t realize you needed help doing the whole thing... I updated my answer to reflect this
type: AnswerComment
comment on: http://stackoverflow.com/a/52191405

http://stackoverflow.com/comment/91275214
type: QuestionComment
comment on: http://stackoverflow.com/q/52145782
type: Comment
has text: Done. Thanks @jezrael
score: 0

http://stackoverflow.com/q/52215154
score: 0
answer count: 1
tagged with: user-input
type: UnansweredQuestion
tagged with: python
has body: I would like to check if my option string and my option string int are equal to BOTH values D and D. Does not pair with them both. if option + option_2 == "D" and "D": rate = r() time = t() distance = velocity * time print (f"The distance traveled is {distance} meters") exit()`
has answer: http://stackoverflow.com/a/52215203
type: Question
has title: How to check two things in user input

http://stackoverflow.com/q/52146554
upvote count: 2
has answer: http://stackoverflow.com/a/52149776
has comment: http://stackoverflow.com/comment/91242985
tagged with: tensorflow
has title: How to pass a list of number using command line in running tensorflow?
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/52149776
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91243317
linked to: http://stackoverflow.com/q/15753701
tagged with: python
score: 2
linked to: http://stackoverflow.com/q/36901287
has body: In running python tensorflow, to pass a string or a single number, we can use tf.app.flags.DEFINE_string or tf.app.flags.DEFINE_integer. But can we pass a list such as [2,3,4] or [7,8,9,6] into python tensorflow?

http://stackoverflow.com/comment/91313453
type: QuestionComment
comment on: http://stackoverflow.com/q/52181696
has text: No, it's not possible.
score: 0
type: Comment

http://stackoverflow.com/comment/91339113
score: 0
type: Comment
type: QuestionComment
has text: Maybe you could sort `all_my_arrays` or a shallow copy of it. Then you only have to compare each array with the previous one to eliminate duplicates.
comment on: http://stackoverflow.com/q/52194717

http://stackoverflow.com/comment/91519190
comment on: http://stackoverflow.com/a/52269832
type: Comment
has text: Thanks Daniel for the help. Your example code got me to what I ended up settling on. My remaining concern is "can never have any URLs other than those for your viewset". I hope the solution above addresses this. Or at the very least, since the module only relates to one resource, it is okay to have just one viewset for the greeter resource. Thanks again :)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91376660
type: AnswerComment
comment on: http://stackoverflow.com/a/52213136
type: Comment
score: 2
has text: Note: Now that you've fixed your code per @wim, you might have noticed you don't need `__attrs_post_init__` at all. You could just define `accessed` as `accessed: str = attr.ib(init=False, factory=lambda: datetime.now().isoformat())` and now you don't need `__attrs_post_init__` at all (and you've avoided separating the information about the default value from the information about the attribute itself).

http://stackoverflow.com/a/52480549
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52146685
type: AcceptedAnswer
downvote count: 0
has body: Try adding: import multiprocessing multiprocessing.set_start_method('forkserver') at the top of your code, before running or importing anything. That's a well-known issue with multiprocessing in python.
type: Answer
answers question: http://stackoverflow.com/q/52146685
score: 1

http://stackoverflow.com/comment/91395268
type: AnswerComment
has text: Going for the other option, this works but the other option is a simpler overall solution.
comment on: http://stackoverflow.com/a/52221923
type: Comment
score: 0

http://stackoverflow.com/comment/91426012
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52225798
has text: Sorry for not being clearer. I am not setting any breakpoint in the library code, but in the user code. I am using pudb and when stepping into a function that is making use of the decorator, i get into the decorator library (the __call__ method).

http://stackoverflow.com/comment/91304778
score: 0
type: AnswerComment
has text: Still feel like I'm not entirely with you -- you're saying the exposition from C++ to Python is irrelevant but again I thought the original question was *exactly* about how to do that. Hence my suggestion was clearly a solution to this specific requests...
type: Comment
comment on: http://stackoverflow.com/a/52152328

http://stackoverflow.com/q/52212220
tagged with: python
tagged with: append
has answer: http://stackoverflow.com/a/52212398
has title: How do I append ndarray to a list and access the each stored ndarray from the list?
possible better answer: http://stackoverflow.com/a/52212398
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52212460
type: Question
tagged with: numpy-ndarray
answer count: 2
has body: I'm trying to create a list that store all ndarrays generated from my for loop: for index in range(len(fishim)): cropped_fishim = [] cropped_image = crop_img(fishim[index], labeled)#call function here. cropped_fishim.append(cropped_image) Then I want to use cropped_fishim[index] to access the each stored ndarray for further process. I have also tried to use extend instead of append method. The append method packed all ndarray as one array and does not allow me to access each individual ndarray stored in cropped_fishim. The extend method does store ndarray separately, but cropped_fishim[index] would only access the indexth col array. Any help would be appreciated.
has comment: http://stackoverflow.com/comment/91374460
score: 0
tagged with: multidimensional-array
accepted answer: http://stackoverflow.com/a/52212460

http://stackoverflow.com/comment/92071100
score: 1
type: Comment
has text: In this [issue](https://github.com/pyinstaller/pyinstaller/issues/1840) the community suggest to install [Microsoft Visual C++ 2010 Redistributable Package](https://www.microsoft.com/en-US/Download/confirmation.aspx?id=14632)
type: QuestionComment
comment on: http://stackoverflow.com/q/52120694

http://stackoverflow.com/q/52174391
has body: I am using NetworkX, opencv, numpy and python to find shortest_path in a graph. It doesn't always provide what I need. shortest_path function finds the path starting from the top of the image to bottom. My path is always varying. Starting point and target point are always known for each image. Thus, I want to find the shortest path between those points (start and target). However, when the source and target points are not nodes and not in the G, it doesn't give what I need. shortest_path(G, source=None, target=None, weight=None) How can I find the shortest_path between two specific coordinate points in the image? Moreover, how can I assign a pixel coordinates as source and target ? For example, source is [45 66] and target is [250 350]
upvote count: 2
type: UnansweredQuestion
tagged with: python
downvote count: 1
tagged with: networkx
has title: How to define source and target parameters as array for shortest_path?
has answer: http://stackoverflow.com/a/52174549
tagged with: opencv
score: 1
has comment: http://stackoverflow.com/comment/110308931
type: Question
tagged with: numpy
tagged with: shortest-path
has comment: http://stackoverflow.com/comment/110328610
answer count: 1
linked to: http://stackoverflow.com/q/51043824
favorite count: 0

http://stackoverflow.com/q/52270127
score: 0
answer count: 2
tagged with: django
has comment: http://stackoverflow.com/comment/91527739
type: UnansweredQuestion
has title: Saving category_id for new post in django
has body: I have a problem when saving/creating new post for blog. I already have Post model and each post has it's own category. so I have Category model too. In CreateView template I already got all categories from DB and displayed in select/option tag. The issue is I want to save category_id when I create new post. But I don't know how? How can I say if form POSTED get category_id and save it for Post model that has category_id field? View: class PostCreateForm(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'short_text', 'long_text', 'post_pic'] def get_context_data(self, **kwargs): context = super(PostCreateForm, self).get_context_data(**kwargs) context['categories'] = Category.objects.all().order_by('id') return context def form_valid(self, form, **kwargs): form.instance.author = self.request.user return super().form_valid(form) Model: class Category(models.Model): title = models.CharField(max_length=255) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=255) short_text = models.TextField() long_text = models.TextField() post_pic = models.ImageField(default="post_pic.jpg", blank=False, upload_to='post_pics') date_published = models.DateTimeField(default=timezone.now()) date_upadated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, default=None, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk})` post_form.html {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block title_head %} New Post {% endblock title_head %} {% block content %} {% csrf_token %} New Post {% for category in categories %} {{ category }} {% endfor %} Post {% endblock content %}
has comment: http://stackoverflow.com/comment/91490570
type: Question
has answer: http://stackoverflow.com/a/52270494
has answer: http://stackoverflow.com/a/52290110
tagged with: python

http://stackoverflow.com/q/52267314
type: AnsweredQuestion
tagged with: conv-neural-network
tagged with: tensorflow
score: 9
type: Question
answer count: 2
upvote count: 9
has answer: http://stackoverflow.com/a/52269521
tagged with: neural-network
downvote count: 0
tagged with: deep-learning
favorite count: 0
has answer: http://stackoverflow.com/a/52276803
accepted answer: http://stackoverflow.com/a/52276803
has body: I'm trying to convert a network that I'm using from using tf-slim's conv2d to using tf.layers.conv2d, since it looks like tf.layers is the more supported and future-proof option. The function signatures are fairly similar, but is there something algorithmically different between the two? I'm getting different output tensor dimensions than expected. x = tf.layers.conv2d(inputs=x, filters=256, kernel_size=[3,3], trainable=True) As opposed to this: x = slim.conv2d(x, 256, 3)
possible better answer: http://stackoverflow.com/a/52269521
has title: Difference between tf.layers.conv2d and tf.contrib.slim.conv2d
tagged with: python

http://stackoverflow.com/comment/91293287
comment on: http://stackoverflow.com/a/52171019
type: AnswerComment
type: Comment
score: 1
has text: Definitely the right ID. Looks like the issue was I was not passing the DriveId in a list. Works now, thanks!

http://stackoverflow.com/a/52123512
type: Answer
score: 1
upvote count: 1
has body: You could use a nested list comprehension: df2 = pd.DataFrame({ 'a': 1, 'b': [b for a, b in df1'a', 'b'.values for _ in range(a)]}) &gt;&gt;&gt; df2 a b 0 1 2 1 1 4 2 1 4 3 1 4 4 1 6 5 1 3 6 1 3 7 1 5
answers question: http://stackoverflow.com/q/52123449
downvote count: 0

http://stackoverflow.com/comment/91232242
type: Comment
has text: I could be wrong, but I don't think OP means multiple scripts running concurrently, just that he'd like to use this as a library routine in various scripts.
type: AnswerComment
comment on: http://stackoverflow.com/a/52140589
score: 0

python-itertools
tags question: http://stackoverflow.com/q/52206196
tags question: http://stackoverflow.com/q/52244670
tag name: python-itertools
tags question: http://stackoverflow.com/q/52211342
tags question: http://stackoverflow.com/q/52183321
type: Tag
tags question: http://stackoverflow.com/q/52230899
tags question: http://stackoverflow.com/q/52195887
tags question: http://stackoverflow.com/q/52243118

http://stackoverflow.com/a/52113616
type: Answer
answers question: http://stackoverflow.com/q/52113568
score: 1
upvote count: 1
downvote count: 0
has body: Use justify function and select first 3 columns: df = pd.DataFrame(justify(df.values,invalid_val=np.nan)[:, :3].astype(int), columns=list('xyz'), index=df.index) print (df) x y z 0 2 4 5 1 2 3 5 2 1 3 4 3 1 2 4 4 2 4 5

http://stackoverflow.com/q/52188382
tagged with: rows
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/91326941
has answer: http://stackoverflow.com/a/52188628
has body: As the title specifies, I'm trying to obtain a dataframe that is row repeated. The factor that decides the N repeats perform are based on the length of the unique values of a specific column present in the original dataframe. After the repeat process is performed, I would like to create a new column that applies all the same unique values of the specific column of the original dataframe to each new row created. I know that this is a bit confusing, but I can´t try to expose my doubt in a better way. So, to facilitate your understanding of my desired approach, were goes a breif example of my dataframe and the desired output dataframe: &gt;&gt; Original Dataframe Samp Age Cs 1 A 51 msi 2 B 62 cin 3 C 55 msi 4 D 70 ebv 5 E 56 gs .... As you can see, my Cs column has 4 unique values (which may not always be the same for different dataframes). So, my goal is to obtain a dataframe with the following structure: &gt;&gt; Desired Dataframe Samp Age Cs 1 A 51 msi 1 A 51 cin 1 A 51 ebv 1 A 51 gs 2 B 62 cin 2 B 62 msi 2 B 62 gs 2 B 62 ebv 3 C 55 msi 3 C 55 cin 3 C 55 ebv 3 C 55 gs 4 D 70 ebv 4 D 70 cin 4 D 70 msi 4 D 70 gs 5 E 56 gs 5 E 56 cin 5 E 56 msi 5 E 56 ebv .... As you can see, in my desired dataframe, all the rows were repeated 4 times (which is equal to the number of unique Cs column values) in exception the Cs column (which applies all its unique values in different rows).
favorite count: 0
has title: Repeat dataframe rows n times according to the unique column values and to each row repeat create a new column with different values
has answer: http://stackoverflow.com/a/52188823
tagged with: pandas
tagged with: repeat
tagged with: python
has answer: http://stackoverflow.com/a/52188769
possible better answer: http://stackoverflow.com/a/52188628
score: 2
upvote count: 2
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/32792263
accepted answer: http://stackoverflow.com/a/52188769
tagged with: dataframe

http://stackoverflow.com/comment/91341122
type: Comment
type: QuestionComment
score: 1
has text: I would say that's partly correct. Your problem is actually due to an unexpected chained comparison, but I suspect closing immediately as a duplicate wouldn't help you very much. Here is an example answer from Tim Peters: https://stackoverflow.com/a/45180967/674039
comment on: http://stackoverflow.com/q/52195635

http://stackoverflow.com/q/52244355
has comment: http://stackoverflow.com/comment/91437240
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/91437060
has comment: http://stackoverflow.com/comment/91437227
has comment: http://stackoverflow.com/comment/91437414
has comment: http://stackoverflow.com/comment/91437281
tagged with: python
has comment: http://stackoverflow.com/comment/91437894
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91437057
has title: Why am I facing with empty graph without any error?
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/91437128
has comment: http://stackoverflow.com/comment/91437008
has comment: http://stackoverflow.com/comment/91437618
has answer: http://stackoverflow.com/a/52244634
has comment: http://stackoverflow.com/comment/91437164
has comment: http://stackoverflow.com/comment/91437063
type: Question
has comment: http://stackoverflow.com/comment/91437537
accepted answer: http://stackoverflow.com/a/52244634
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91437880
has body: import matplotlib.pyplot as plt plt.figure(figsize=(20,10)) plt.plot(norway.Freedom, norway.Economy_GDP_per_Capita, color = 'navy', label = 'Norway') plt.legend(loc = 'upper left') plt.title('Effect of GDP against Freedom') plt.xlabel('Freedom') plt.ylabel('GDP') plt.show() Example row in the data: Output: I make a quick start to Data Science and I am trying to make some analysis on Kaggle. I write a kernel for plotting a line as you see in my code, although the graph is empty and I can not see anything. Besides that, there is no error or something. I need help with it. Please try to explain without going deep, I am a beginner. Thanks everybody who will help. I am not sure whether you guys can see my code and graph...

http://stackoverflow.com/a/52212131
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52209587
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52209587
has body: The problem is with the load call. It should be: tf.saved_model.loader.load(session, [tag_constants.SERVING], path) where tag_constants is located at tf.saved_model.tag_constants.
score: 9
upvote count: 9

http://stackoverflow.com/a/52157345
has body: For this X: In [734]: X = np.arange(24).reshape(8,3) In [735]: X.strides Out[735]: (24, 8) this as_strided produces the same array as your time_framer In [736]: np.lib.stride_tricks.as_strided(X, shape=(X.shape[0]-3, 3, X.shape[1]), strides=(24, 24, 8)) Out[736]: array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]], [[ 6, 7, 8], [ 9, 10, 11], [12, 13, 14]], [[ 9, 10, 11], [12, 13, 14], [15, 16, 17]], [[12, 13, 14], [15, 16, 17], [18, 19, 20]]]) It strides the last dimension just like X. And 2nd to the last as well. The first advances one row, so it too gets X.strides[0]. So the window size only affects the shape, not the strides. So in your as_strided version just use: new_strides = (data_to_frame.strides[0], data_to_frame.strides[0] , data_to_frame.strides[1]) Minor corrections. Set the default window size to 2 or larger. 1 produces an indexing error in the test. framed_data[0,1]==framed_data[1,0] Looking a getsizeof: In [754]: sys.getsizeof(X) Out[754]: 112 In [755]: X.nbytes Out[755]: 192 Wait, why is X size smaller than nbytes? Because it is a view (see line [734] above). In [756]: sys.getsizeof(X.copy()) Out[756]: 304 As noted in another SO, getsizeof has to be used with caution: Why the size of numpy array is different? Now for the expanded copy: In [757]: x2=time_framer(X,4) ... In [758]: x2.strides Out[758]: (96, 24, 8) In [759]: x2.nbytes Out[759]: 384 In [760]: sys.getsizeof(x2) Out[760]: 512 and the strided version In [761]: x1=strides_trick_time_framer(X,4) ... In [762]: x1.strides Out[762]: (24, 24, 8) In [763]: sys.getsizeof(x1) Out[763]: 128 In [764]: x1.astype(int).strides Out[764]: (96, 24, 8) In [765]: sys.getsizeof(x1.astype(int)) Out[765]: 512 x1 size is just like a view (128 because its 3d). But if we try to change its dtype, it makes a copy, and the strides and size are the same as x2. Many operations on x1 will loose the strided size advantage, x1.ravel(), x1+1 etc. It's mainly reduction operations like mean and …
answers question: http://stackoverflow.com/q/52149479
has comment: http://stackoverflow.com/comment/91292616
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91292091
type: Answer
has comment: http://stackoverflow.com/comment/91290549
accepted answer of: http://stackoverflow.com/q/52149479
has comment: http://stackoverflow.com/comment/91288816
upvote count: 2
has comment: http://stackoverflow.com/comment/91291123
score: 2

http://stackoverflow.com/a/52218528
upvote count: 1
downvote count: 0
has body: You can use a list comprehension as per @U9-Forward's solution. An alternative functional solution is possible with operator.mul and zip: from collections import Counter from operator import mul c = Counter({5: 3, 6: 2, 8: 1}) res = list(map(mul, *zip(*c.items()))) # [15, 12, 8] If you really need a set, wrap map with set instead of list. The difference is set is an unordered collection of unique items, while list is an ordered collection with no restriction on duplicates.
type: Answer
answers question: http://stackoverflow.com/q/52218107
score: 1

http://stackoverflow.com/q/52163992
has body: I'm stuck with creating a Django web app following this tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04#check-for-the-gunicorn-socket-file I think I've read all related questions on SO: django gunicorn sock file not created by wsgi Gunicorn not generating sock file https://github.com/benoitc/gunicorn/issues/1166 None of them helped. I'm following each step exactly as described but still the myapp.sock file is not created. The main project directory is /home/ubuntu/puchalatravel It's content: ubuntu@ip-172-31-35-104:~/puchalatravel$ ls -l total 60 -rw-r--r-- 1 ubuntu ubuntu 40960 Sep 4 09:37 db.sqlite3 -rwxrwxr-x 1 ubuntu ubuntu 545 Sep 4 07:42 manage.py drwxrwxr-x 3 ubuntu www-data 4096 Sep 4 09:32 puchalatravel drwxrwxr-x 4 ubuntu ubuntu 4096 Sep 4 07:41 puchalatravelenv drwxrwxr-x 3 ubuntu ubuntu 4096 Sep 4 09:34 static Access to the folder: ubuntu@ip-172-31-35-104:~$ ls -l total 1616 drwxrwxr-x 4 ubuntu ubuntu 4096 Aug 30 07:25 eb-virt -rw-rw-r-- 1 ubuntu ubuntu 1642522 Aug 30 07:11 get-pip.py drwxrwxr-x 6 ubuntu www-data 4096 Sep 4 09:37 puchalatravel Content of /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/puchalatravel ExecStart=/home/ubuntu/puchalatravel/puchalatravelenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/puchalatravel/puchalatravel.sock puchalatravel.wsgi:application [Install] WantedBy=multi-user.target Content of /etc/nginx/sites-available/puchalatravel server { sserver { listen 8000; server_name ec2-18-188-249-6.us-east-2.compute.amazonaws.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/puchalatravel; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/puchalatravel/puchalatravel.sock; } } I've ran pkill gunicorn sudo systemctl daemon-reload sudo systemctl star…
tagged with: django
tagged with: python
score: 4
accepted answer: http://stackoverflow.com/a/52164082
linked to: http://stackoverflow.com/q/39919053
answer count: 1
upvote count: 4
tagged with: nginx
tagged with: amazon-ec2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52164082
downvote count: 0
has title: Gunicorn not creating .sock file on AWS EC2
favorite count: 0
tagged with: gunicorn
type: Question
linked to: http://stackoverflow.com/q/47244074

http://stackoverflow.com/a/52236734
accepted answer of: http://stackoverflow.com/q/52235928
answers question: http://stackoverflow.com/q/52235928
upvote count: 15
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Make your variable length sequence a torch.Tensor and use torch.nn.functional.pad import torch import torch.nn.functional as F seq = torch.Tensor([1,2,3]) # seq of variable length print(F.pad(seq, pad=(0, 2), mode='constant', value=0)) 1 2 3 0 0 [torch.FloatTensor of size 5] Signature of F.pad is: input: input tensor that is your variable length sequence. pad: m-elem tuple, where (m/2) ≤ input dimensions and m is even. In 1D case first element is how much padding to the left and second element how much padding to the right of your sequence. mode: fill the padding with a constant or by replicating the border or reflecting the values. value: the fill value if you choose a constant padding.
score: 15

http://stackoverflow.com/comment/91312585
has text: OK, so the problem is you're working with `X = df.values`. Don't do this because a single NumPy array can only have one dtype. Internally with Pandas, each series has a separate NumPy array / dtype. You can use Pandas to take advantage of this.
type: Comment
comment on: http://stackoverflow.com/a/52180305
type: AnswerComment
score: 0

http://stackoverflow.com/q/52134579
tagged with: flask
favorite count: 0
tagged with: python
has title: How should I check and validate request format and parameters with flask?
upvote count: 0
has body: For now, my idea is to validate the below request by writing in decorators.py before the request is passed into the init.py including the endpoints. But Im not sure of how I can write the validation code of request with flask. Would anyone help me write this code ? This is the http request which will be sent from curl command. AUTH_HEADER=`echo -n ${ID}:${SECRET}|base64` curl ${URL_HEADER}/oauth/token -X POST -H "Authorization: Basic ${AUTH_HEADER}" –d "grant_type=xxx&amp;scope=yyy"
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/52135553
score: -1
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/91433429
has text: that works, can i do this in one line for all h1 tags on the page?
comment on: http://stackoverflow.com/a/52240690
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52249433
type: Answer
has body: In [5]: [(j, sum([i[1] for i in a if i[0] == j])) for j in set([i[0] for i in a])] Out[5]: [(0, 2), (1, 1), (2, 1), (3, 2), (4, 3), (5, 2)]
answers question: http://stackoverflow.com/q/52249282
score: 0
has comment: http://stackoverflow.com/comment/91447017
has comment: http://stackoverflow.com/comment/91447079

http://stackoverflow.com/a/52173880
type: Answer
has body: There is a "simple" but probably not "right" way to do that - I can classify that as "workaround". Firstly start your working container, I will use ubuntu as example but you can of course adjust that to your needs: docker run -dit --name work-container -v /path-to-code:/code ubuntu bash -c "while true; do sleep 10; done" So that command will start ubuntu for you in background with endless loop. In -v section you should mount your code which you change. So now open new console and type: docker exec -it work-container bash So that command start new shell inside that background container. So in that shell you can do whatever you want inside container e.g. cd /code &amp;&amp; ./do-something-with-your-python. As your code is mounted under /code in container you will see changes in real time and you can run some program a then hit ctrl+c and restart it after code changes.
answers question: http://stackoverflow.com/q/52172970
score: 0

http://stackoverflow.com/comment/91385165
comment on: http://stackoverflow.com/q/52217688
score: 0
type: Comment
type: QuestionComment
has text: Also and fwiw, you don't need a precompiled version of the Tolk.py file, the python runtime can use the source file just as well, so I'm not sure your problem has anything to do with python.

http://stackoverflow.com/a/58193809
upvote count: 8
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52236655
has comment: http://stackoverflow.com/comment/139121438
has body: You can achieve similar results using the area filter instead of geocodeArea. For your example: area[name="Berlin"]-&gt;.searchArea; ( node["amenity"="pub"](area.searchArea); way["amenity"="pub"](area.searchArea); relation["amenity"="pub"](area.searchArea); ); out body; &gt;; out skel qt; This could work, but for other areas maybe you need to be more specific with the tags used in the area filter, more information in the Language Guide for Overpass
score: 8

http://stackoverflow.com/a/52171883
upvote count: 3
answers question: http://stackoverflow.com/q/52171597
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52171597
type: AcceptedAnswer
type: Answer
has body: You have to change your way of thinking a bit: d = numpy.zeros_like(z) m = z &gt;= 0 m &amp;= z &lt; 0.5 d[m] = -24*z[m]**2 + 12*z[m] m = z &gt;= 0.5 m &amp;= z &lt;= 1 d[m] = -24*z[m]**2 + 36*z[m] - 12 The equations simplify quite a bit with a=1 in your example, but the idea is to use a mask to selectively apply the conditions (then reuse to save memory).
score: 3

http://stackoverflow.com/q/52188115
answer count: 1
favorite count: 0
has title: Calculate Cosine similarity without matrix with duplicate sum from coo_matrix to csr_matrix
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: scipy
type: Question
tagged with: cosine-similarity
has answer: http://stackoverflow.com/a/52188255
accepted answer: http://stackoverflow.com/a/52188255
has body: I want to calculate cosine similarity between products of a purchases dataset. I have more than 100000 rows ( row = user purchase event) and more than 80000 products. To avoid using pandas.crosstab to make the dataset in the format: &gt; user_id\item_id 1 2 3 4 ... &gt; 1 | 1 1 0 0 &gt; 2 | 0 1 0 0 &gt; 3 | 1 0 1 0 &gt; 4 | 0 0 0 0 &gt; 5 | 0 0 1 0 &gt; ... &gt; &gt; Matrix: Whether a user purchased an item or not I converted the purchases dataset to scipy.coo_matrix and thought that I have to then do tocsr() to do the normalization and similarities calculations between products, but found out that when we transform a coo_matrix to csr_matrix it sums the duplicates (which I don't want to happen, I only want 1 and 0 in my matrix). Is there a way to get around that and calculate cosine similarity?
tagged with: sparse-matrix
upvote count: 1

http://stackoverflow.com/a/52266794
has comment: http://stackoverflow.com/comment/91481516
upvote count: 2
answers question: http://stackoverflow.com/q/52266756
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91481510
type: Answer
score: 2
downvote count: 0
has body: df['column'].str.replace('.', '', regex=False) 0 Sam M Name: column, dtype: object
accepted answer of: http://stackoverflow.com/q/52266756

http://stackoverflow.com/q/52179919
has comment: http://stackoverflow.com/comment/91545576
has comment: http://stackoverflow.com/comment/91553996
has comment: http://stackoverflow.com/comment/91312813
answer count: 1
downvote count: 0
favorite count: 0
tagged with: fft
has comment: http://stackoverflow.com/comment/91545762
tagged with: python
accepted answer: http://stackoverflow.com/a/52296866
tagged with: ifft
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/91330956
tagged with: phase
upvote count: 3
has body: I have the data that has equivalent intervals and corresponding measurements at relevant points. As an example, here is the excerpt of the data I have: y =[2.118, 2.1289, 2.1374, 2.1458, 2.1542, 2.1615, 2.1627, 2.165 2.1687...] interval between the points is 0.1 So, what I need to get out of the data is the Amplitude spectrum (amplitude vs frequency) and also phase spectrum (phase angle vs frequency). In addition I should shift the phase of the data by negative 90 degrees (-pi/2). Upon shifting the phase and leaving the amplitude untouched, I need to do the inverse fft and get the new signal. I want to do this in Python. Could you please give me an example of performing this. The code that I have used, was taken from another SO question, but I have done some modifications ## Perform FFT WITH SCIPY signalFFT = np.fft.fft(y) ## Get Power Spectral Density signalPSD = np.abs(signalFFT) ** 2 signalPhase = np.angle(signalFFT) ## Shift the phase py +90 degrees new_signalPhase =(180/np.pi)*np.angle(signalFFT)+90 ## Get frequencies corresponding to signal fftFreq = np.fft.fftfreq(len(signalPSD), 0.1) ## Get positive half of frequencies i = fftFreq&gt;0 ## plt.figurefigsize=(8,4) #plt.plot(fftFreq[i], 10*np.log10(signalPSD[i])); plt.plot(fftFreq[i], new_signalPhase[i]); plt.ylim(-200, 200); plt.xlabel('Frequency Hz'); plt.ylabel('Phase Angle') plt.grid() plt.show() The problem is that I want to regenerate the signal, with the same amplitudes but shifted phase. I know that the answer is smth related to ifft, but how should I prepare data for it? Could you please advice me the further steps. output
has comment: http://stackoverflow.com/comment/91545201
has title: Amplitude and phase spectrum. Shifting the phase leaving amplitude untouched
has answer: http://stackoverflow.com/a/52296866
tagged with: signal-processing
type: Question
has comment: http://stackoverflow.com/comment/91545094
has comment: http://stackoverflow.com/comment/91550775

http://stackoverflow.com/a/52202935
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52201562
answers question: http://stackoverflow.com/q/52201562
type: AcceptedAnswer
downvote count: 0
has body: The problem is that the frame you are trying to use as separator is not in the same frame as the ImportSection and ExportSection because you don't specify its parent. When you don't specify a parent, tkinter will make the widget a child of the root window. This is also the reason why you can't pack app into the root window: self.sep is already put into root with grid. Change self.sep = tk.Frame(width=2, bd=1, relief='sunken') to self.sep = tk.Frame(self, width=2, bd=1, relief='sunken')
type: Answer
score: 2

http://stackoverflow.com/q/52114052
score: 2
tagged with: api
type: AnsweredQuestion
favorite count: 0
has title: Is there any way to change view of Django-rest-auth of register?
has body: I've created rest APIs using Django-rest-auth, in registration, it's returning { "detail": "Verification e-mail sent." } , But I need to add some status like success and message like email sent etc. Is there any way to override view of django-rest-auth for registration? class MyRegisterSerializer(RegisterSerializer): first_name = serializers.CharField() last_name = serializers.CharField() def get_cleaned_data(self): super(MyRegisterSerializer, self).get_cleaned_data() return { 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), 'first_name': self.validated_data.get('first_name', ''), 'last_name': self.validated_data.get('last_name', '') } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) user.address = self.cleaned_data.get('address') user.user_type = self.cleaned_data.get('user_type') user.save() return user
type: Question
upvote count: 2
tagged with: django-rest-auth
answer count: 2
accepted answer: http://stackoverflow.com/a/52115260
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/53319843
possible better answer: http://stackoverflow.com/a/52115291
downvote count: 0
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/52115260
has answer: http://stackoverflow.com/a/52115291
linked to: http://stackoverflow.com/q/52110466

http://stackoverflow.com/comment/91201687
has text: It looks like there is a parenthesis after the first read_items() call that should be moved to the end of the line.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52125297
type: Comment

http://stackoverflow.com/a/52118847
score: 7
answers question: http://stackoverflow.com/q/52118783
upvote count: 7
downvote count: 0
type: AcceptedAnswer
has body: vstack doesn't just accept two arrays. It accepts an iterable of rows to stack. You can directly do np.vstack([a, b, c, d, e]) or, generally np.vstack(my_arrays)
type: Answer
accepted answer of: http://stackoverflow.com/q/52118783

homebrew
tags question: http://stackoverflow.com/q/52187040
tag name: homebrew
tags question: http://stackoverflow.com/q/52154682
type: Tag
tags question: http://stackoverflow.com/q/52175456
tags question: http://stackoverflow.com/q/52136138
tags question: http://stackoverflow.com/q/52140867

http://stackoverflow.com/comment/91326291
has text: https://community.esri.com/thread/210489-python-write-new-row-based-on-comma-separated-values-in-table-column
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52188203
score: 0

http://stackoverflow.com/q/52199173
tagged with: python
type: AnsweredQuestion
has title: Simple Logistic Regression with Neural Networks Mindset
tagged with: logistic-regression
type: Question
answer count: 2
downvote count: 2
tagged with: neural-network
possible better answer: http://stackoverflow.com/a/55711670
has body: Got this simple exercise where I have to build a NN with the help of Logistic Regression. My dataset is built in this way : You are given a dataset ("data.h5") containing: a training set of m_train images labeled as cat (y=1) or non-cat (y=0) a test set of m_test images labeled as cat or non-cat each image is of shape (num_px, num_px, 3) where 3 is for the 3 channels (RGB). Thus, each image is square (height = num_px) and (width = num_px). To show an image from the database the text gives me an example : # Example of a picture# Examp index = 25 plt.imshow(train_set_x_orig[index]) print ("y = " + str(train_set_y[:,index]) + ", it's a '" + classes[np.squeeze(train_set_y[:,index])].decode("utf-8") + "' picture.") I have 2 questions : 1) I did not understand how this works : str(train_set_y[:,index]) 2) The big problem is that , due to site problem , I can not download this database and in order to do the exercise I would like to understand how is it built. Can someone intuitively tell me how it could be structured?
has answer: http://stackoverflow.com/a/55711670
upvote count: 4
favorite count: 0
score: 2
has answer: http://stackoverflow.com/a/52214675
accepted answer: http://stackoverflow.com/a/52214675

http://stackoverflow.com/comment/91417969
type: QuestionComment
has text: Thanks guys, I guess asking questions and experimenting will help me learn more, ill watch a video on the curses module
comment on: http://stackoverflow.com/q/52230554
score: 0
type: Comment

http://stackoverflow.com/q/52154593
has title: Python.Pandas/:/What is the difference between the first and second codes, so did the following code occur?
has comment: http://stackoverflow.com/comment/91259667
upvote count: 1
accepted answer: http://stackoverflow.com/a/52154658
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91259428
score: 0
tagged with: pandas
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52154658
has body: everybody. Why do files in the first code run and files in the second code fail? import pandas SD2=pd.read_csv('C:/Users/Jangsu/AppData/Local/Programs/Python/Python36-32/Sample data1.csv') DF2=pd.DataFrame(SD2) SD3=pd.read_csv('C:/Users/Jangsu/AppData/Local/Programs/Python/Python36-32/Sample data2.csv') DF3=pd.DataFrame(SD3) SD4=pd.read_csv('C:/Users/Jangsu/AppData/Local/Programs/Python/Python36-32/Sample data3.csv') DF4=pd.DataFrame(SD4) SD5=pd.read_csv('C:/Users/Jangsu/AppData/Local/Programs/Python/Python36-32/Sample data4.csv') DF5=pd.DataFrame(SD5)( result = pd.concat([DF1,DF2,DF3,DF4],axis=1, ignore_index=False) print(result) result.to_csv("savessssssssdata.csv",index=False) When you run the code of the first file, you see that the file running on that code is saved normally. So let me show you the second code. import pandas as pd import serial import time SD=[] DF=[] for i in range(1,4): SD1=pd.read_csv('C:/Users/Jangsu/Desktop/Sample data'+str(i)+".csv") SD.append(SD1) DF1=pd.DataFrame(SD1) DF.append(DF1) DF1.to_csv('C:/Users/Jangsu/Desktop/Samspsle data'+str(i)+".csv",index=False) resul=pd.concat([DF],axis=1, ignore_index=False) print(resul) resul.to_csv("'C:/Users/Jangsu/Desktop/ssssssscccc.csv", index=False) The first code acts as a combination of files. The second code is the code that will be entered into the DF, which will read each csv file, and then use the code stored in a list format to create and store a single data frame. But the second code has the following error: Traceback (most recent call last): File "C:/Users/Jangsu/AppData/Local/Programs/Python/Python36-32/csv-testss.py", line 14, in &lt;module&gt; resul=pd.concat([DF],axis=1, ignore_index=False) File "C:\Users\Jangsu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\reshape\concat.py", line 225, in concat copy=copy, sort=sort) File "C:\Users\Jangsu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\reshape\concat.py", line 286, in __init__ raise T…
tagged with: python
has comment: http://stackoverflow.com/comment/91259490
type: AnsweredQuestion

http://stackoverflow.com/a/52125135
downvote count: 0
has comment: http://stackoverflow.com/comment/91201293
has comment: http://stackoverflow.com/comment/91201344
answers question: http://stackoverflow.com/q/52124961
has comment: http://stackoverflow.com/comment/91201389
score: 4
accepted answer of: http://stackoverflow.com/q/52124961
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91201275
has body: What you're asking is not possible. From the array docs: This module defines an object type which can compactly represent an array of basic values: characters, integers, floating point numbers ... The type is specified at object creation time by using a type code The only supported types are as follows (notice the absence of list): Type code C Type Python Type 'b' signed char int 'B' unsigned char int 'u' Py_UNICODE Unicode character 'h' signed short int 'H' unsigned short int 'i' signed int int 'I' unsigned int int 'l' signed long int 'L' unsigned long int 'q' signed long long int 'Q' unsigned long long int 'f' float float 'd' double float It seems like you might be confusing the array module, with a native implementation of numpy arrays. This is not the case.
type: Answer
upvote count: 4

http://stackoverflow.com/comment/91326503
has text: Thank you very much.I used my previous code and tried to flatten it. But there is something wrong. Please help me out. import numpy as np from numpy import random rows = 6 cols = 6 a = np.matrix(np.random.randint(220,376, size=(rows,cols))) np.fill_diagonal(a,0) print (a) np.array((a).flatten(),10, replace=False) Output gives an error message; TypeError Traceback <ipython-input-120-94177c27aee1> in <module>() 3 4 ----> 5 np.array((a).flatten(),10, replace=False) TypeError: data type not understood
type: Comment
comment on: http://stackoverflow.com/a/52187837
score: 0
type: AnswerComment

http://stackoverflow.com/q/52185043
has title: Django SQLite view returns Empty Queryset []
has comment: http://stackoverflow.com/comment/91326680
tagged with: sql-view
has comment: http://stackoverflow.com/comment/91324208
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/91320859
tagged with: python
answer count: 0
has body: Hi I'm new to Django / SQLite and i'm getting an empty qurty set when i read from a view. Other tables and views that i've created are behaving normally. when i use DB Browser for SQLite, I can see the data is there. #nmsdb_app.models.py class V_WSW_Table_People_Chooser(models.Model): Username = models.CharField(max_length=31) Record_ID = models.CharField(max_length=11) Display_Text = models.CharField(max_length=255) def __str__(self): return self.Username #stop django from trying to treat sql views as tables class Meta: managed = False python manage.py shell: from nmsdb_app.models import V_WSW_Table_People_Chooser V_WSW_Table_People_Chooser.objects.all() &lt;QuerySet []&gt; to make the view on the SQLite server: 1. do the model 2. makemigrations 3. migrate 4. drop the SQLIte table and replace with the view 5. add managed = False to the model class I've tried the Record_ID field as Text and Integer but it makes no difference. When i use DB Browser for SQLite, the view data appears correctly. Any help received with thanks.
has comment: http://stackoverflow.com/comment/91331027
type: Question
has comment: http://stackoverflow.com/comment/91320706
score: 0
has comment: http://stackoverflow.com/comment/91322110
tagged with: sqlite

http://stackoverflow.com/a/52267937
has body: You're comparing very different sized arrays here. In your first example, although you create an array of zeros, you simply use random.choice(100000, 100000), which pulls 100000 random values between 1-100000. In your second example your are shuffling a (100000, 3) shape array. &gt;&gt;&gt; x.shape (100000, 3) &gt;&gt;&gt; np.random.choice(N, N, replace=False).shape (100000,) Timings on more equivalent samples: In [979]: %timeit np.random.choice(N, N, replace=False) 2.6 ms ± 201 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [980]: x = np.arange(100000) In [981]: %timeit np.random.shuffle(x) 2.29 ms ± 67.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [982]: x.shape == np.random.choice(N, N, replace=False).shape Out[982]: True
has comment: http://stackoverflow.com/comment/91502550
answers question: http://stackoverflow.com/q/52267788
score: 2
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/a/52190536
has comment: http://stackoverflow.com/comment/91386801
score: 3
has comment: http://stackoverflow.com/comment/91330914
answers question: http://stackoverflow.com/q/52190474
has body: If the order is not important, you can use unique X = np.matrix([[1, 1, 1, 2, 0, 3, 1], [1, 2, 2, 0, 3, 3, 1]]) np.unique(X, axis=1) results in array([[0, 1, 1, 2, 3], [3, 1, 2, 0, 3]]) If preserving the order is important, it will be a bit slower: X = np.matrix([[1, 1, 1, 2, 0, 3, 1], [1, 2, 2, 0, 3, 3, 1]]) idxs = np.sort(np.unique(X, axis=1, return_index=True)[1]) answer = X[:, idxs] answer will then be: matrix([[1, 1, 2, 0, 3], [1, 2, 0, 3, 3]])
downvote count: 0
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/91377738

http://stackoverflow.com/q/52269786
accepted answer: http://stackoverflow.com/a/52269920
tagged with: frequency
has title: Extracting data values belonging to a day and compute average value to each day
tagged with: python
upvote count: 4
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/52269920
linked to: http://stackoverflow.com/q/52265151
type: Question
has body: I have a dataset with a date range from January 12th to August 3rd 2018 with some values: The dimensionality of df_luminosidad DataFrame is: df_luminosidad.shape (9752, 2) Each row of data has a half-hour frequency. The first row begins at 2018-01-12 df_luminosidad.iloc[0] Fecha: 2018-01-12 00:17:28 Luz (lux) 1 Name: 0, dtype: object And the last row ends at 2018-08-03 df_luminosidad.tail(1) Fecha: Luz (lux) 9751 2018-08-03 23:44:59 1 There are many rows which correspond to one day such as denoted above. I want to create a new dataframe selecting only 1 day as a value for the Fecha: column (no a repeated date) and select the average value from all existing value for the selected date of the Luz(lux) column This would look like this: | Fecha: | Luz(lux) - Average each day values | | 2018-01-12 | 9183.479167 | | 2018-01-13 | 7431.8125 | | 2018-01-14 | 11073.1875 | | 2018-01-15 | 11456.25 | | . . | | . . | | . . | | 2018-08-03 | 11331.229167 | I am using pd.date_range() function to create a dataframe with the values from df_luminosidad previous dataframe to a specified frequency such as denoted @piRSquared in this answer From January 12 to August 03 there are 203 days (28 weeks), then I choose 204 like period attribute, and I am using a freq attribute calendar day frequency D df = pd.DataFrame(dict( Date=pd.date_range('2018-01-12', periods=204, freq='D'), Value=df_luminosidad['Luz (lux)'].mean() )) Until here, the approach is well, but I have a doubt about of how to compute the mean of Luz (lux) values to each day selected with pd.date_range, because, at this moment I just get an average same value for all days from 2018-01-12 until 2018-08-03 such as follow: | Date | Value | | 2018-01-12 | 11228.888331 | | 2018-01-13 | 11228.888331 | | 2018-01-14 | 11228.888331 | | 2018-01-15 | 11228.888331 | | . . | | . . | | . . | | 2018-08-03 | 11331.229167 | I've already generated a dataframe by each Fecha: column values, and separately I could get their average, but this force me…
has comment: http://stackoverflow.com/comment/91487095
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/52270317
answer count: 2
downvote count: 2
tagged with: pandas
favorite count: 0
tagged with: series
has answer: http://stackoverflow.com/a/52270317

http://stackoverflow.com/q/52190431
has answer: http://stackoverflow.com/a/52190475
has answer: http://stackoverflow.com/a/68402347
score: 0
answer count: 2
has title: Python 3.5x, 3.6x and 3.7x Install Fails on Windows 7 even with Universal C runtime updated
type: UnansweredQuestion
tagged with: python
has body: I have tried installing 3.5x, 3.6x and 3.7x on my windows 7 pro 64 bit OS with both the executable installer and the web based one from https://www.python.org/downloads/windows/ , I updated my Universal C runtime, restarted, uninstalled all previous versions, disabled my firewall in the event of the downloads being blocked, all return the same error, the setup freezes on 0%, then crashes with "i399: Apply complete, result: 0x80072f7d," in the log file. Any help appreciated
type: Question

http://stackoverflow.com/comment/91476638
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52264058
type: Comment
has text: It is 1000 line with four columns the first column is the line number I do not really need it for the equation the 2n,3rd and 4th are the x, y, and z coordinates of a 3d point. I need to do a calculation on x,y and z for all 1000 rows and at the end know how many lines met the equation standard

http://stackoverflow.com/comment/91223465
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52136318
score: 0
has text: hum , I used the forms.ModelForm and the class Meta to make my form there is no id input possible. How should I do to pass the id ?

http://stackoverflow.com/a/52263815
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52240857
has body: I figured out the issue. The if statement to show the btn, was being ignored, because it was after json dumped the data back to the file.
answers question: http://stackoverflow.com/q/52240857
score: 0

http://stackoverflow.com/q/52241904
has comment: http://stackoverflow.com/comment/91502262
type: Question
has comment: http://stackoverflow.com/comment/91558710
has body: I am learning about thread and copied an example code from the book. The code is exactly the same but the outcome is different according to which way the the code is launched in Pycharm. Here is my code: import threading g_count = 0 def thread_main(): global g_count for i in range(100000): g_count += 1 threads = [] for i in range(50): th = threading.Thread(target=thread_main) threads.append(th) for th in threads: th.start() for th in threads: th.join() print("g_count = {:,}".format(g_count)) When I run the code with 'Run' (ctrl+shift+F10) the outcome is always 5,000,000, which is not expected. When I run the code with 'debug' (alt+shift+F10) the outcome is always different as expected. How come 'run' mode always prints 5,000,000 in this case?
has title: Pycharm_Why the outcome is different when I run the code with normal mode and debug mode?
score: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: pycharm
tagged with: multithreading
has comment: http://stackoverflow.com/comment/91564229

http://stackoverflow.com/a/52127441
has comment: http://stackoverflow.com/comment/91207600
answers question: http://stackoverflow.com/q/52127379
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91206868
has body: It looks like you copied that code from a class. In Python, by convention (PEP 8), "self" refers to the current instance of an object. If your code is outside of a class, self will not be defined, as there is no instance. You should change def convertProjection(self,x,y,from_crs,to_crs): to def convertProjection(x,y,from_crs,to_crs): and then call the function without "self.".
upvote count: 1

http://stackoverflow.com/q/52210911
has comment: http://stackoverflow.com/comment/91371481
tagged with: trigonometry
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/91371196
type: AnsweredQuestion
downvote count: 2
accepted answer: http://stackoverflow.com/a/52222132
type: Question
possible better answer: http://stackoverflow.com/a/57925212
has answer: http://stackoverflow.com/a/57925212
score: 4
tagged with: coordinates
has comment: http://stackoverflow.com/comment/91392361
tagged with: distance
answer count: 2
has body: I need to calculate distance between two points, using their coordinates (x, y, z) on a unit sphere. Both Haversine and Great Arc Distance use φ and λ (longitude and latitude). How do i write those Formulas for x, y, z?
has comment: http://stackoverflow.com/comment/91371543
favorite count: 0
has answer: http://stackoverflow.com/a/52222132
linked to: http://stackoverflow.com/q/4913349
has comment: http://stackoverflow.com/comment/91391268
has title: Great Circle Distance between two "P = (x, y, z)" points on a unit sphere

http://stackoverflow.com/comment/91345291
score: 1
type: Comment
type: QuestionComment
has text: I believe concatenate the vertex would not break `convexHull`. as this is just what the function is for.
comment on: http://stackoverflow.com/q/52197918

http://stackoverflow.com/comment/91186311
has text: You're supposed to put that command into the terminal, not the python interpreter.
comment on: http://stackoverflow.com/q/52117685
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91394933
comment on: http://stackoverflow.com/q/52223045
score: 0
has text: Please show your attempts based on what you found in your research and we can explain why it didn't work as expected.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52220126
has comment: http://stackoverflow.com/comment/91392070
type: Answer
answers question: http://stackoverflow.com/q/52204739
has comment: http://stackoverflow.com/comment/91395838
has comment: http://stackoverflow.com/comment/91391971
has comment: http://stackoverflow.com/comment/91456813
score: 0
has comment: http://stackoverflow.com/comment/91462315
has comment: http://stackoverflow.com/comment/91396445
has body: Are you aware of Google Cloud DataLab? This is basically Jupyter hosting service on GCP. Anyway, the following code snipplet (when run from inside a notebook, Python=3) will take your notebook, convert it to slides and upload to Cloud Storage. You can serve your flies from cloud storage publicly: import datalab.storage as gcs slides = !jupyter nbconvert &lt;your_notebook&gt;.ipynb --to slides --stdout gcs.Bucket('&lt;your_bucket_name&gt;').item('slides.html').write_to("".join(slides[1:]),'text/html') To make it public, in your bucket permissions, add "allUsers" member with "Storage Object Viewer" role. Please note this will make your bucket publicly available on the internet. If you are not using DataLab, you may need to add datalab.storage as a dependency to your Python env. I think it is way easier in your case and safer than configuring firewalls on a VM and exposing it to inbound traffic.

http://stackoverflow.com/comment/91219993
type: AnswerComment
has text: Recursion is not my strong suit. Thanks, buddy! :)
type: Comment
comment on: http://stackoverflow.com/a/52134796
score: 1

http://stackoverflow.com/a/52131155
answers question: http://stackoverflow.com/q/52128951
type: Answer
has comment: http://stackoverflow.com/comment/91553561
score: 5
type: AcceptedAnswer
upvote count: 5
has body: I eventually found a solution in Is there any good python library for generating and rendering text in image format?. Although it is based on a third-party executable, as mentioned it is easy to wrap in Python. Exact steps were as follows: Install ImageMagick from https://www.imagemagick.org/script/download.php#windows Set environment variable MAGICK_HOME to installation folder Install Pillow to be able to manipulate easily the resulting image in Python (conda install pillow) Download and install the Symbola font from https://fontlibrary.org/en/font/symbola And my test script: import os import subprocess import PIL.Image to_render = '' output_file = 'rendered_emoji.bmp' subprocess.run([ os.path.join(os.environ['MAGICK_HOME'], 'magick.exe'), 'convert', '-font', 'Symbola', '-size', '50x50', '-gravity', 'center', f'label:{to_render}', output_file]) image = PIL.Image.open(output_file) image.show()
accepted answer of: http://stackoverflow.com/q/52128951
downvote count: 0
has comment: http://stackoverflow.com/comment/91553351

http://stackoverflow.com/q/52233459
tagged with: python
has body: As i'm trying to show the battery percentage in the button text. I have imported the package like GUI (PyQt) and psutil package to get the system information. When i try to print the battery status can able to show in the console. But when i try to show inside the PyQt button i'm getting error. import sys import psutil battery = psutil.sensors_battery() print(battery.percent) class App(QWidget): def __init__(self): super().__init__() self.title = 'PyQt5 simple window - pythonspot.com' self.left = 10 self.top = 10 self.width = 640 self.height = 480 self.initUI() self.battery = psutil.sensors_battery() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) #------&gt;psutil.sensors_battery() button = QPushButton(psutil.sensors_battery(), self) button.setToolTip('This is an example button') button.move(100, 70) self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_()) Below is error code Traceback (most recent call last): File "F:/PY3/helloworld.py", line 45, in &lt;module&gt; ex = App() File "F:/PY3/helloworld.py", line 31, in __init__ self.initUI() File "F:/PY3/helloworld.py", line 37, in initUI button = QPushButton(psutil.sensors_battery(), self) TypeError: arguments did not match any overloaded call: QPushButton(parent: QWidget = None): argument 1 has unexpected type 'sbattery' QPushButton(str, parent: QWidget = None): argument 1 has unexpected type 'sbattery' QPushButton(QIcon, str, parent: QWidget = None): argument 1 has unexpected type 'sbattery' So how can set the battery percentage in the button?
type: AnsweredQuestion
tagged with: python-3.x
type: Question
tagged with: qt
has answer: http://stackoverflow.com/a/52233579
answer count: 1
accepted answer: http://stackoverflow.com/a/52233579
has title: How to show the battery percentage in the button using PyQt5 and psutil
score: 0

http://stackoverflow.com/q/52263689
favorite count: 0
tagged with: protocol-buffers
type: UnansweredQuestion
tagged with: python
has title: Save and Load Model as .pb Using TFLearn?
answer count: 0
score: 1
upvote count: 1
tagged with: tensorflow
type: Question
tagged with: tflearn
has body: I've trained DNN model using tflearn and saved it as checkpoint file, and the model performed well. I need to freeze the model so I can use it on android device later. I've been searching a way to freeze my model directly from TFLearn but apparently tflearn hasn't provided such function as of now so I have to do it with tensorflow using this code to freeze my model into protobuf file. And I also got my output node name from tensorboard by using this (same user) because using the name of output node I've explicitly given in my model apparently doesn't work in TFLearn and it just froze 0 variables from it. It seemed to work fine as I successfully froze it into .pb file, but when I load that frozen graph in different runtime and make a prediction from it using model.predict(), it gave me a very wrong prediction as if my model hasn't even been trained yet. This is my NN architecture. convnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 3], name='masuk') convnet = conv_2d(convnet, 40, 2, activation='relu') convnet = max_pool_2d(convnet, 4) convnet = conv_2d(convnet, 40, 2, activation='relu') convnet = max_pool_2d(convnet, 4) convnet = conv_2d(convnet, 80, 2, activation='relu') convnet = max_pool_2d(convnet, 4) convnet = conv_2d(convnet, 160, 2, activation='relu') convnet = max_pool_2d(convnet, 4) convnet = fully_connected(convnet, 500, activation='relu') convnet = dropout(convnet, 0.75) convnet = fully_connected(convnet, 32, activation='softmax') convnet = regression(convnet, optimizer='adam', learning_rate=LR, loss='categorical_crossentropy', name='keluar') model = tflearn.DNN(convnet, tensorboard_dir='log') This is the code I used to try loading my .pb file. with tf.Session() as sess: with gfile.FastGFile(MODEL_NAME + '.frozen_graph.pb','rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) sess.graph.as_default() tf.import_graph_def(graph_def, name='') This is for my assignment and I'm kinda new to tensorflow (and machine learning in general) so is…
downvote count: 0

http://stackoverflow.com/a/52206290
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/91362074
has comment: http://stackoverflow.com/comment/91361860
has body: You just need the ensure_ascii=False option in json.dump. If you're creating this file in the first place, just pass that option. If someone else gave you this JSON file and you want to change it to use Unicode characters directly in strings (as opposed to Unicode escapes as it is now), you can do something like this: import json with open('input.txt', 'r') as infile: with open('output.txt', 'w') as outfile: for line in infile: data = json.loads(line) json.dump(data, outfile, ensure_ascii=False) outfile.write('\n')
downvote count: 0
has comment: http://stackoverflow.com/comment/91361925
has comment: http://stackoverflow.com/comment/91362111
type: Answer
answers question: http://stackoverflow.com/q/52205673

http://stackoverflow.com/a/52158712
answers question: http://stackoverflow.com/q/52150602
score: 0
type: Answer
has body: You can do this with a for loop in Bash. $ for i in *.tar; do tar xvf "$i"; done $ for j in *.tar.gz; do tar zxvf "$j"; done

http://stackoverflow.com/comment/91344326
score: 0
comment on: http://stackoverflow.com/q/52196407
type: QuestionComment
type: Comment
has text: Run this with the following data:data = \ [ { "name": 20, "price": "thirty"}, ] it will still be showing only one error and not two errors.

http://stackoverflow.com/q/52153886
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/91354027
has comment: http://stackoverflow.com/comment/91268906
has body: I am a building a model in Keras with input data X of variable length (N_sample, 50, 128). Each sample has 50 time-steps and at each time step, I have 128 features. However, I have used zero-padding to generate the input X, because not all Samples have 50 time-steps. There are two ways of padding zeros. For each sample, I feed the true data, say (20,128) in the beginning and then the remaining (30,128), I pad zero. I pad the first 30 rows with zero and add data to the last 20 rows. I then use sample_weight to assign a zero weight to the padded time steps. However, in these two settings, I get completely different AUC on the test set. What happens if zero padded samples are fed before or after the true data in an LSTM network with sample_weights? Is it due to the initialization of the hidden state in the LSTM? How would I know, which is correct? Thank you. My model is as below: model = Sequential() model.add(TimeDistributed(Dense(64, activation='sigmoid'), input_shape=(50, 128))) model.add(LSTM(32, return_sequences=True)) model.add(TimeDistributed(Dense(8, activation='sigmoid'))) model.add(TimeDistributed(Dense(1, activation='sigmoid'))) model.compile(loss='binary_crossentropy', optimizer='rmsprop',sample_weight_mode='temporal', metrics=['accuracy']) model.fit(X_train, y_train, epochs=100, batch_size=32, verbose=2, sample_weight=Sample_weight_train)
type: UnansweredQuestion
tagged with: python
has title: Different model performance using LSTM keras sample_weight, when padding before or after the actual data
answer count: 0
downvote count: 0
score: 1
type: Question
tagged with: lstm
tagged with: padding
upvote count: 1
has comment: http://stackoverflow.com/comment/94545113

http://stackoverflow.com/comment/91277597
type: Comment
comment on: http://stackoverflow.com/q/52163981
has text: It looks like a case for some custom parser. [`(?m)^"([^"]+)"(?:\n#.*)*\s*.*?=>[^\w"]*(?:{(?=.*}))?(.*?)[^\w"]*$`](https://regex101.com/r/qFlivd/2) looks too fragile and cumbersome already.
score: 0
type: QuestionComment

http://stackoverflow.com/a/52118030
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91290163
has comment: http://stackoverflow.com/comment/91187226
score: 0
has body: Do not convert the Member.objects.all to a list. It must return a QuerySet not a list. So remove the list from mem_list = list(Member.objects.all()) and it must be mem_list = Member.objects.all()
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91190646
accepted answer of: http://stackoverflow.com/q/52117935
answers question: http://stackoverflow.com/q/52117935
type: Answer
has comment: http://stackoverflow.com/comment/91192197

http://stackoverflow.com/comment/91464504
comment on: http://stackoverflow.com/q/52257843
score: 0
type: QuestionComment
type: Comment
has text: @jy.chua Additionally, update the question with the parent node of all the 3 child ` ` nodes.

http://stackoverflow.com/q/52242489
tagged with: dictionary
has answer: http://stackoverflow.com/a/52243497
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/91433350
has body: topic_dic = { 'Sports': ['play', 'football', 'cricket', 'ball', 'FIFA', 'Basketball', 'Referee', 'Sachin Tendulkar', 'messi', 'ronaldo', 'EPL', 'manchester united', 'real Madrid', 'juventus', 'contract', 'paul pogba', 'Barcelona', 'transfer'], 'Politics': ['Barack Obama', 'Donald Trump', 'Prime Minister', 'PM', 'President', 'BJP', 'Amit Shah', 'Lok Sabha', 'Election', 'Modi', 'Government', 'Supreme Court', 'SC', 'India', 'USA', 'Offical', 'Court', 'Legal', 'Judgement'], 'Science': ['NASA', 'Space', 'James Webb Space', 'Telescope', 'Alien', 'Dawn', 'Mission', 'Galaxy', 'Habitat', 'Magnet', 'Wave', 'Thermals', 'Temperature', 'Orbit', 'Neutrons', 'Mass', 'Discovery'], 'Social Entertainment': ['Music', 'Dance', 'Singing', 'Concert', 'Audio', 'Playback', 'Competition', 'Movie', 'Drama', 'Theatre'], 'General Topics': ['Celebrity', 'Culture', 'Society', 'Business', 'Development', 'Country'] } topics = ['real','retirement','moment,','messi','pogba','play'] I have created a dictionary containing key as topics and items related to that topic. I have a list containing some words which I want to compare with the dictionary items. How to I compare every elements of list topic with items in dictionary and return the key where the item is matching with the list element?? Can i store the keys in different array?
has comment: http://stackoverflow.com/comment/91449239
type: Question
upvote count: 0
downvote count: 5
accepted answer: http://stackoverflow.com/a/52243497
has comment: http://stackoverflow.com/comment/91434845
answer count: 2
score: -5
has comment: http://stackoverflow.com/comment/91433359
has answer: http://stackoverflow.com/a/52242586
favorite count: 0
has comment: http://stackoverflow.com/comment/91433314
has title: How to I match a list of word with dictionary items and return the key in python?
possible better answer: http://stackoverflow.com/a/52242586
tagged with: python
has comment: http://stackoverflow.com/comment/91433363

http://stackoverflow.com/q/52258852
has answer: http://stackoverflow.com/a/52259084
type: AnsweredQuestion
score: 2
linked to: http://stackoverflow.com/q/29576430
upvote count: 2
has title: Shuffle rows by a column in pandas
accepted answer: http://stackoverflow.com/a/52258881
has body: I have the following example of dataframe. c1 c2 0 1 a 1 2 b 2 3 c 3 4 d 4 5 e Given a template c1 = [3, 2, 5, 4, 1], I want to change the order of the rows based on the new order of column c1, so it will look like: c1 c2 0 3 c 1 2 b 2 5 e 3 4 d 4 1 a I found the following thread, but the shuffle is random. Cmmiw. Shuffle DataFrame rows
type: Question
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52258881
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52259084
tagged with: python

http://stackoverflow.com/comment/91182994
type: Comment
comment on: http://stackoverflow.com/a/52115473
score: 0
type: AnswerComment
has text: I am formulating the additional data sample.

http://stackoverflow.com/q/52256001
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52256116
has title: How to convert str into int through map function?
has body: p1 = int(input("Enter the probablity of rain")) pab = input("Enter the probablity of Alice taking bus") pmb = input("Enter the probablity of mark taking bus") Final_Outcome_in_int = map(int,pab) print(type(p1)) print(type(pab)) print(type(pmb)) In this p1 is showing int but for pab its still showing str although I used map function.
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91459228
score: -1
has answer: http://stackoverflow.com/a/52256159
answer count: 2
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52268531
has body: In a unit test for a function that outputs timestamp and say hostname on it along with other values. In the unit test if i add some timestamp and a hostname in expected output it will fail as the timestamp from the function will change every time the function is called and the hostname will change every time it is run in a different machine. What is the workaround for this? I'd appreciate your input. output from a function: {'datetime': '09-10-2018 23:23:23', 'hostname': 'abc.xyz.com',...} # and it can change every time we run it but this datetime and hostname changes depending on time, of course, and machine expected output that i think i will use in unit test to assertEqual or assertDictEqual: {'datetime': '09-10-2018 23:23:23', 'hostname': 'abc.xyz.com',...} Is some other assertion check better suited for this situation?
downvote count: 0
tagged with: unit-testing
type: Question
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52268832
accepted answer: http://stackoverflow.com/a/52268832
tagged with: assertion
upvote count: 1
answer count: 1
favorite count: 0
tagged with: datetime
tagged with: python
has title: Python unit test for a function that has timestamp

http://stackoverflow.com/a/52200580
answers question: http://stackoverflow.com/q/52156566
has body: why not just? while (driver.FindElements(By.ClassName("more")).Count &gt; 0) { driver.FindElement(By.ClassName("more")).Click(); //Some delay to wait lazyload to complete } c# example. pretty sure that it can be done with python as well
score: 0
type: Answer

http://stackoverflow.com/comment/91196577
has text: Possible duplicate of [this question](https://stackoverflow.com/q/48028782/1735215). There, the solution was to update to ChromeDriver 2.35. What ChromeDriver version are you using?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52121506
type: QuestionComment

http://stackoverflow.com/a/52136064
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52136002
has comment: http://stackoverflow.com/comment/91221992
answers question: http://stackoverflow.com/q/52136002
type: Answer
has comment: http://stackoverflow.com/comment/91221944
has comment: http://stackoverflow.com/comment/91222166
upvote count: 2
has body: Your NameError is nothing to do with the function, it is because you are trying to use a variable, a, when initialising a list which you haven't defined. It looks like you meant to test with a string instead: func([20, 'a', 4, 40]) But nevertheless, your try..except still wont catch the TypeError thrown when trying to sum a list which rather than the NameError: contains a string, you should catch this for the wrong type. You should also catch ValueError in case less than two grades were entered: def func(grades): try: first,*middle,last=grades avg=sum(middle)/len(middle) print(avg) except (ZeroDivisionError, ValueError): print("At least 3 grades must be inputed") except TypeError: print("no letters are allowed in Grades") which warns the user if the wrong data type is passed: &gt;&gt;&gt; func([20, 'a', 4, 40]) no letters are allowed in Grades

http://stackoverflow.com/comment/91342711
comment on: http://stackoverflow.com/q/52196699
score: 0
type: Comment
type: QuestionComment
has text: Either way, without seeing your inputs and calling code, it's really difficult to say anything.

http://stackoverflow.com/comment/91334486
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52188570
has text: As an update - I don't think the issue is happening in prettify(), it's happening in soup = BeautifulSoup(differencehtml, 'html.parser') because when I print soup immediately afterwards, it has the weird symbols

http://stackoverflow.com/q/52266872
downvote count: 0
favorite count: 0
tagged with: click
tagged with: python-3.x
tagged with: python
has body: Im using python 3.7 and windows 10 I got this script: import pyautogui pyautogui.click() It runs fine on my computer untill i until i launch a specific program (program A), then it completely stop working. It does not only not work when this program (program A) is highlighted but also in every other program (program B, C, ..) that is currently running. Before program A is started my code works fine in the other programs (B ,C ,...). I do not get any errors, the code still executes as expected but without actually doing a mouse click. one thing worth noting is that if i use pyautogui.moveTo(x,y) the mouse do still move. Any ideas on why this is happening? and/or how I can work around / solve the problem ? Note: I have seen answers where the .click() function doesen't work within specific applications, but in my case it stops working within the entire os (any application) as long as Program A is running. Note #2: i have tried this on an other computer as-well, problem is the same. Note #3: I do run everything as an admin
score: 2
answer count: 0
has title: python 3 pyautogui.click() "blocked" by not active application
upvote count: 2
type: UnansweredQuestion
type: Question
tagged with: debugging
has comment: http://stackoverflow.com/comment/91481774
has comment: http://stackoverflow.com/comment/91481667
tagged with: pyautogui

http://stackoverflow.com/comment/138055929
score: 0
type: AnswerComment
has text: @iBug changing the order like this `self.next.prev, self.next = node, node` will work as intended ,right? the `self.next.prev` is the assigned first before changing the value of `self.next`, right?
type: Comment
comment on: http://stackoverflow.com/a/52143588

http://stackoverflow.com/a/52131790
upvote count: 1
answers question: http://stackoverflow.com/q/52131535
downvote count: 0
has body: The number may off, since when there are only have two same values, I do not know you need the which one. Using user3483203 's setting up df['flag'] = df.Value.ne(0) df['Target']=df.sort_values(['flag'],ascending=False).drop_duplicates(['Group1','Group2']).Value df['Target'].fillna(0,inplace=True) df Out[20]: Group1 Group2 Value Target_Column Target 0 1 3 0 0 0.0 1 1 3 1 1 1.0 2 1 4 1 1 1.0 3 1 4 1 0 0.0 4 2 5 5 5 5.0 5 2 5 1 0 0.0 6 2 6 0 0 0.0 7 2 6 1 1 1.0
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/91214309

http://stackoverflow.com/comment/91309856
has text: By default, Atom does not run code. It would be helpful to know which package you use to run code.
type: Comment
comment on: http://stackoverflow.com/q/52176031
score: 0
type: QuestionComment

http://stackoverflow.com/q/52203775
tagged with: list
downvote count: 0
has comment: http://stackoverflow.com/comment/91356694
type: Question
has comment: http://stackoverflow.com/comment/91360302
score: 5
tagged with: algorithm
has comment: http://stackoverflow.com/comment/91356676
has comment: http://stackoverflow.com/comment/91356861
tagged with: pandas
has body: I have two very large python lists that look like this: List A: [0,0,0,0,0,0,0,1,1,1,1,2,2,3,3,3,4.........] List B: [0,0,0,0,0,0,2,2,2,2,3,3,4,4.........] These lists go on to very large numbers, but I specify a maximum value, say 100 and after that I can discard the rest. Now I need to calculate for each value (0,1,2..100) the ratio: occurrences in list A / occurrences in list B. And since this value is not always possible I decided to calculate this value only if there's more than 5 occurrences of the value in each list, and if this condition is not true, then combine the occurrences of the previous value(s) and will give the same ratios for combined values if this condition is correct. For example for the above lists, I want to create a Series that looks like this: 0 : 7/6=1.166 1 : 9/6 = 1.5 2 : 9/6 = 1.5 3 : 9/6 = 1.5 . . . 100 : some_number
has answer: http://stackoverflow.com/a/52204109
has title: Efficiently counting items in large python lists
has comment: http://stackoverflow.com/comment/91356853
has comment: http://stackoverflow.com/comment/91357983
accepted answer: http://stackoverflow.com/a/52204109
answer count: 1
has comment: http://stackoverflow.com/comment/91358094
favorite count: 0
has comment: http://stackoverflow.com/comment/91356982
upvote count: 5
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/91293794
has text: Docs didn't have a reference to skipnan for quantile function, that's why I asked.. DataFrame.quantile(q=0.5, axis=0, numeric_only=True, interpolation='linear') @sacul kindly highlighted the correct comparator, which I didn't know existed, in np.nanpercentile Thanks all
comment on: http://stackoverflow.com/q/52171333
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91575730
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52262308
has text: yes. And my guess is that for this particular example both Hessian and Jacobian approximations are wrong. I came to this conclusion when I altered the code and used `‘L-BFGS-B` without jac and hess and I got an output. I'm going to add this to my answer.
score: 0

http://stackoverflow.com/comment/91369854
type: AnswerComment
comment on: http://stackoverflow.com/a/52190910
has text: The last two lines print as follows: 7303 and 334562. Do you have a reference I use to read up on? I am guessing that there are rows of all Nulls?
score: 0
type: Comment

http://stackoverflow.com/a/52180189
downvote count: 0
has comment: http://stackoverflow.com/comment/91310591
score: 1
has comment: http://stackoverflow.com/comment/91318293
answers question: http://stackoverflow.com/q/52180117
has body: &lt;input name="customer_account_number" &lt;/input&gt; YOu are missing closing bracket here.
accepted answer of: http://stackoverflow.com/q/52180117
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/91187617
comment on: http://stackoverflow.com/q/52118339
score: 0
has text: Are you treally trying to add ones to a, or are you eventually trying to solve something else, like a convolution?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52238579
accepted answer: http://stackoverflow.com/a/52239891
type: AnsweredQuestion
favorite count: 0
tagged with: python-3.x
type: Question
has body: I'm having some issues trying to connect to a Flask SocketIO implementation. I followed the examples and set up a server with the following code: from flask_socketio import SocketIO, send application = Flask(__name__) socketio = SocketIO(application) @socketio.on('message') def doStuff(msg): print(msg) if __name__=="__main__": socketio.run(application, port=8080) and a client in Python: import websocket from websocket import create_connection ws = create_connection("ws://SERVER_IP:8080/") print(ws) print("Sending 'Hello, World'...") ws.send("Hello, World") print("Sent") print("Receiving...") result = ws.recv() print("Received '%s'" % result) ws.close() Nonetheless when I try to connect, I get WebSocketBadStatusException: Handshake status 200 OK. All the examples I've seen of connection to SocketIO involve having a static page with javascript but I want to use this as a Desktop application or use it with Kotlin. What am I missing?
has title: Connecting to Flask SocketIO implementation
tagged with: python
linked to: http://stackoverflow.com/q/48160130
has comment: http://stackoverflow.com/comment/91428593
has comment: http://stackoverflow.com/comment/91428612
has comment: http://stackoverflow.com/comment/91428307
score: 0
has answer: http://stackoverflow.com/a/52239891
upvote count: 1
answer count: 1
downvote count: 1
tagged with: socket.io
tagged with: flask

http://stackoverflow.com/a/52164272
has body: You can do it on one iteration. d = {1:0, 2:1, 3:2} # Save the minimum value and the key that belongs to it as we go min_val = None result = None for k, v in d.items(): if v and (min_val is None or v &lt; min_val): min_val = v result = k print(result) Some assumptions: Negative values will be considered It will return the first key that found If it helps, min_val will hold the minimum value
answers question: http://stackoverflow.com/q/52164137
score: 6
downvote count: 0
type: Answer
upvote count: 6

http://stackoverflow.com/comment/91262422
has text: I think you got the shapes exchanged. `p.shape` is (21, 1), try wit p.T
score: 1
comment on: http://stackoverflow.com/q/52153966
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91377444
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52211025
has text: Have you tried other type of weights? Is the accuracy different then? What about test scores?
score: 0

http://stackoverflow.com/q/52164441
type: AnsweredQuestion
downvote count: 0
has body: I have a pandas dataframe of shape ~ [200K, 40]. The dataframe has a categorical column (one of many) with over 1000 unique values. I can visualizee the value counts of each such unique column by using: df['column_name'].value_counts() How do i now club values with: value_count less than a threshold value, say, 100, and map them to, say, "miscellaneous"? OR based on the cumulative row count % ?
type: Question
score: 4
possible better answer: http://stackoverflow.com/a/52164683
has answer: http://stackoverflow.com/a/52164683
answer count: 3
tagged with: pandas
has title: map column values to 'miscellaneous' if value counts is below a threshold - Categorical Column - Pandas Dataframe
favorite count: 0
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/52164689
has answer: http://stackoverflow.com/a/52184358
accepted answer: http://stackoverflow.com/a/52164689

http://stackoverflow.com/q/52220569
has title: Save and open dictionary
has comment: http://stackoverflow.com/comment/91389732
downvote count: 3
accepted answer: http://stackoverflow.com/a/52220595
has comment: http://stackoverflow.com/comment/91389593
answer count: 1
has comment: http://stackoverflow.com/comment/91390479
score: -3
has body: I saved a dictionary to a txt file using this code dic = {1:'a', 2:'b', 3:'c'} f = open("dict.txt","w") f.write( str(dic) ) f.close() Now I am wondering how I can import it again into a dictionary?
has comment: http://stackoverflow.com/comment/91389639
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/52220595
favorite count: 0
has comment: http://stackoverflow.com/comment/91389663
has comment: http://stackoverflow.com/comment/91389698
type: Question
has comment: http://stackoverflow.com/comment/91389772
tagged with: python

http://stackoverflow.com/comment/91482338
has text: show your .kv....
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52267177
type: Comment

http://stackoverflow.com/comment/91402668
score: 1
type: AnswerComment
has text: Awesome that you're making answers! I hope you wouldn't mind just a few pointers? When someone has an error, especially if OP is new on the site, it's often reasonable to assume that the OP does not know what this error means. If you provide links and a description of why the error happens, you can expect to get a lot more rep on your answers! Again: it's great that you're trying to help, and that's only what I'm trying to do too!
type: Comment
comment on: http://stackoverflow.com/a/52226158

http://stackoverflow.com/comment/134043107
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/75977162
has text: @KevinD Updated, the response time now expanded to waiting and download time.

http://stackoverflow.com/comment/91329047
score: 0
type: QuestionComment
type: Comment
has text: @d_kennetz Added more explanation.
comment on: http://stackoverflow.com/q/52188764

http://stackoverflow.com/comment/91421022
score: 0
has text: what if the input is `[['sd', 'pd', 'od'], ['sd', 'pd1', 'od2'], ['sd2', 'pd2', 'od'],['sd2', 'pd2', 'od3']]`. what is the desired output?
comment on: http://stackoverflow.com/q/52236217
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91284095
has text: @imsaiful: no. If you want that, you should work with celery, or a cronjob.
type: AnswerComment
comment on: http://stackoverflow.com/a/52166162
score: 0
type: Comment

http://stackoverflow.com/q/52233549
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91416035
has answer: http://stackoverflow.com/a/52233603
favorite count: 0
has comment: http://stackoverflow.com/comment/91416049
tagged with: python
tagged with: regex
has title: Getting two digits from a string in python with regex
has body: I have multiple strings like this 90'4 I want to extract the digits from the string and sum them up to get 94. I tried compiling the pattern. pattern="\d'\d" re.compile(pattern) I tried the methods findall and match, but did not get what I wanted. I need to use regex I cannot use .split()
has comment: http://stackoverflow.com/comment/91416033
tagged with: digit
has comment: http://stackoverflow.com/comment/91416061
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91416065
accepted answer: http://stackoverflow.com/a/52233603
type: Question

http://stackoverflow.com/comment/91338650
has text: Are you sure that (a) you only have a single Python, and (b) you installed the 32-bit versions of pywin32 and pyinstaller? (If you installed everything via `pip`, then (b) isn't a problem, but if you downloaded and ran the installers, it could be, and since that's still the way the pywin32 website recommends installing it, most people do.)
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52194396

http://stackoverflow.com/comment/91324112
comment on: http://stackoverflow.com/a/52186858
type: Comment
score: 0
has text: What do you mean "the ternary operator is applied at compile time"? It is a real conditional evaluated at runtime (unlike a C preprocessor #ifdef, for example).
type: AnswerComment

http://stackoverflow.com/comment/91377245
comment on: http://stackoverflow.com/q/52213564
score: 0
type: Comment
type: QuestionComment
has text: Are all intervals disjoint?

http://stackoverflow.com/q/52229298
type: Question
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52229393
has title: Python 2: Passing global variable to factory decorator
tagged with: python
tagged with: python-2.x
tagged with: python-decorators
has body: In the below script I would like to use the name_type global variable in the decorator while calling the get_names functions. Please don't worry about the program logic. name_type=None def main(): global name_type name_type="FEMALE" get_names() def superNameDecorator(value): def nameDecorator(func): if value in ["MALE"]: def wrapper1(*args,**kwargs): original_result=func(*args,**kwargs) modified_result= "&lt;MALE&gt;"+original_result + "&lt;\MALE&gt;" return modified_result return wrapper1 elif value in ["FEMALE"]: def wrapper2(*args,**kwargs): original_result=func(*args,**kwargs) modified_result= "&lt;FEMALE&gt;"+original_result + "&lt;\FEMALE&gt;" return modified_result return wrapper2 return nameDecorator @superNameDecorator(name_type) def get_names(): name='AMY' return name if __name__ == "__main__": main() This works fine when I pass direct string either "MALE"/"FEMALE" but throws below error when passing name_type What am I missing here? Traceback (most recent call last): File "GlobalTesting.py", line 29, in &lt;module&gt; main() File "GlobalTesting.py", line 5, in main get_names() TypeError: 'NoneType' object is not callable
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52229393

http://stackoverflow.com/q/52239401
type: Question
tagged with: max
upvote count: 3
has answer: http://stackoverflow.com/a/52239456
tagged with: python
tagged with: dictionary
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/52240015
downvote count: 0
type: AnsweredQuestion
score: 3
has title: Find the key of maximum values of maximum key in a dictionary in case of duplicates of values
has answer: http://stackoverflow.com/a/52239472
linked to: http://stackoverflow.com/q/268272
possible better answer: http://stackoverflow.com/a/52239456
has answer: http://stackoverflow.com/a/52239415
accepted answer: http://stackoverflow.com/a/52239415
has body: In Python I want to find the maximum value out of dictionary which has the duplicates, for example : my_dict = {1: 0, 12: 2, 36: 2, 24: 2, 33: 2, 4: 1} and the maximum value is 2. And I want to find the maximum key of the maximum value which is 36:2 in this example.

http://stackoverflow.com/comment/91333719
comment on: http://stackoverflow.com/q/52191417
score: 0
type: QuestionComment
type: Comment
has text: I've seen that example but it's not using flask-appbuilder views.

http://stackoverflow.com/q/52119454
has answer: http://stackoverflow.com/a/68955877
has comment: http://stackoverflow.com/comment/139940465
has answer: http://stackoverflow.com/a/78533797
type: Question
score: 74
has answer: http://stackoverflow.com/a/74609143
has answer: http://stackoverflow.com/a/79448214
downvote count: 0
linked to: http://stackoverflow.com/q/12544056
has answer: http://stackoverflow.com/a/64226030
has answer: http://stackoverflow.com/a/75683730
has answer: http://stackoverflow.com/a/78484596
has answer: http://stackoverflow.com/a/73673295
accepted answer: http://stackoverflow.com/a/52119628
linked to: http://stackoverflow.com/q/5137497
has answer: http://stackoverflow.com/a/60565289
has answer: http://stackoverflow.com/a/79058859
has body: Is there a function to obtain a Notebook's path? I've Googled a little on the subject but didn't find a simple way to do it... I want to obtain the Notebook's path so I can then use it elsewhere. This way I could save/use files in the same path as the notebook without worrying about where it got saved. Right now my solution is to put the following code on top but obviously this poses at least the problem of manually having to execute a cell and also if the working directory changes this will stop working. import os current_path = os.getcwd()
tagged with: jupyter
possible better answer: http://stackoverflow.com/a/73673295
answer count: 15
has answer: http://stackoverflow.com/a/62470185
favorite count: 0
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/78320798
has answer: http://stackoverflow.com/a/73610736
has comment: http://stackoverflow.com/comment/138360033
tagged with: python
has comment: http://stackoverflow.com/comment/129989324
linked to: http://stackoverflow.com/q/39125532
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/78396734
has answer: http://stackoverflow.com/a/52119628
has title: How to obtain Jupyter Notebook's path?
has comment: http://stackoverflow.com/comment/91190190
upvote count: 74
linked to: http://stackoverflow.com/q/63583062
has comment: http://stackoverflow.com/comment/135667657

http://stackoverflow.com/q/52221769
answer count: 4
favorite count: 0
score: -1
downvote count: 2
upvote count: 1
type: AnsweredQuestion
tagged with: comparison
has answer: http://stackoverflow.com/a/52221883
type: Question
has body: I have two floats no_a and no_b and a couple of ranges represented as two element lists holding the lower and upper border. I want to check if the numbers are both in one of the following ranges: [0, 0.33], [0.33, 0.66], or [0.66, 1.0]. How can I write that statement neatly in python code?
possible better answer: http://stackoverflow.com/a/52221884
has answer: http://stackoverflow.com/a/52221864
has answer: http://stackoverflow.com/a/52221884
has answer: http://stackoverflow.com/a/52225456
accepted answer: http://stackoverflow.com/a/52221864
has comment: http://stackoverflow.com/comment/91392187
has title: Check whether two floats are in any of a given list of ranges
tagged with: python

http://stackoverflow.com/q/52204931
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52841863
tagged with: python
has title: Sketch Engine API search query: How to get frequency?
score: 1
tagged with: corpus
upvote count: 1
type: Question
has body: is anyone familiar with the Python Sketch Engine API and could tell us how to get the frequency of an n-gram? So far we have this (example from website): import requests base_url = 'https://api.sketchengine.co.uk/bonito/run.cgi' data = { 'corpname': 'bnc2', 'format': 'json', 'lemma': 'book', 'lpos': '-v', 'username': '...', 'api_key': '...' # get it here: https://the.sketchengine.co.uk/auth/api_access/ } d = requests.get(base_url + '/wsketch', params=data).json() print("frequency=", d['freq']) This gives us the frequency of a lemma, but not an n-gram.
tagged with: api
answer count: 1
downvote count: 0
favorite count: 0
tagged with: n-gram
tagged with: frequency

http://stackoverflow.com/comment/91330489
type: QuestionComment
comment on: http://stackoverflow.com/q/52175281
has text: 'External tools' utility does the work. If you post this comment as an answer, I will be able to accept as the answer of the question. Thanks. @LazyOne
score: 0
type: Comment

http://stackoverflow.com/a/52171825
score: 0
answers question: http://stackoverflow.com/q/52129192
type: Answer
has body: I want to post my findings. The most difficult part was figuring out expect+pbrun. Because there are 2 interactive questions I had to pause for a sec after first question. My expect code: #!/usr/bin/expect -f set timeout 300 set usr [lindex $argv 0]; set pwd [lindex $argv 1]; set query_file [lindex $argv 2]; spawn -noecho pbrun $usr &amp; expect -re "Password:" send "$pwd\r" sleep 1 expect "Enter reason for this privilege access:" send "test\r" send "kinit -k -t /opt/Cloudera/keytabs/`whoami`.`hostname -s`.keytab `whoami`/`hostname -f`@YOUR_FQDN_NAME.NET;ssl=true\r" send "beeline -u 'jdbc:hive2://bigdataplatform-your_dev.net:10000/;principal=hive/bigdataplatform-your_dev.net@YOUR_FQDN_NAME.NET;ssl=true' --outputformat=csv2 --verbose=false --fastConnect=true --silent=true -f $query_file;\r" expect "*]$\ " {send "exit\r"} expect eof Query: select * from gfocnnsg_work.pytest LIMIT 1000000; The rest is Python and paramiko. I create Transport object, execute expect script, and save standard output on Windows OS. Data access path: Windows desktop-&gt; SSH-&gt; Linux login-&gt; pbrun service login-&gt; kinit beeline-&gt; SQL-&gt; save echo on Windows Here's a Python script with details: hivehoney
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52129192

opengl
tags question: http://stackoverflow.com/q/52126087
type: Tag
tags question: http://stackoverflow.com/q/52128972
tags question: http://stackoverflow.com/q/52146796
tag name: opengl
tags question: http://stackoverflow.com/q/52242272

http://stackoverflow.com/comment/91429676
type: Comment
type: QuestionComment
has text: Could you please format your code? Place the code portions in backticks `\`\``
score: 0
comment on: http://stackoverflow.com/q/52240403

http://stackoverflow.com/q/52257398
type: Question
tagged with: discord.py
has answer: http://stackoverflow.com/a/52259450
has comment: http://stackoverflow.com/comment/91465775
answer count: 1
downvote count: 0
tagged with: discord
favorite count: 0
accepted answer: http://stackoverflow.com/a/52259450
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91466078
tagged with: python
has comment: http://stackoverflow.com/comment/91462138
type: AnsweredQuestion
has body: Hi I'm having a bit of a conundrum with a line of my code which is not outputting a message. How it should work If lurker role is in member roles returns I've found some lurkers ready to be kicked, would you like to kick them?. - else if members with no lurker returns No lurkers around to kick today. The issue I'm having is the message No lurkers around to kick today is not outputting. Here is what I'm working with to give you an idea on what I'm trying to achieve: @commands.command(pass_context=True, no_pm=True) @checks.is_owner() async def check_lurkers(self, ctx, *_): """Manually check for lurkers""" serverid = '465536300452151298' server = self.bot.get_server(serverid) # Soon to change to ctx.message.server lurker_role = discord.utils.get(server.roles, name="Lurker") member_role = discord.utils.get(server.roles, name="Members") any_lurkers = False for member in list(server.members): if member_role not in member.roles and lurker_role in member.roles: await self.bot.say("I've found some lurkers ready to be kicked, would you like to kick them?") msg = await self.bot.wait_for_message(timeout=10) if msg is None or msg.content.lower().strip() in ("no", "n"): await self.bot.say("No lurkers were kicked.") elif msg.content.lower().strip() in ("yes", "y"): await self.bot.kick(member) any_lurkers=True if any_lurkers: await self.bot.say("Adios lurkerinos! :wave:") else: await self.bot.say("No lurkers around to kick today. :raised_hands: ") else: await self.bot.say("No lurkers around to kick today. :raised_hands: ") This is the line that is not outputting anything. What am I doing wrong here? Help would be appreciated.
score: 1
has comment: http://stackoverflow.com/comment/91462182
upvote count: 1
has title: await statement not outputting message

http://stackoverflow.com/comment/138691639
comment on: http://stackoverflow.com/a/52249610
has text: To summarize, use the new `SCOPE`, delete and regenerate `token.json`.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91237505
score: 0
type: Comment
type: QuestionComment
has text: Of course nested for loop is not preferred
comment on: http://stackoverflow.com/q/52143854

http://stackoverflow.com/a/52185645
score: 1
has comment: http://stackoverflow.com/comment/91383386
upvote count: 1
has comment: http://stackoverflow.com/comment/91403010
answers question: http://stackoverflow.com/q/52185229
has comment: http://stackoverflow.com/comment/91472102
accepted answer of: http://stackoverflow.com/q/52185229
has body: You could use os.walk like this: not_parseble_files = ['.txt', '.csv'] for root, dirs, files in os.walk(root_folder):#This recursively searches all sub directories for files for file in files: _,file_ext = os.path.splitext(file)#Here we get the extension of the file file_path = os.path.join(root,file) if file_ext in not_parseble_files:#We make sure the extension is not in the banned list 'not_parseble_files' print("File %s is not parseble"%file_path) continue #This one continues the loop to the next file if os.path.isfile(file_path): for email in get_emails(file_to_str(file_path)): print(email)
has comment: http://stackoverflow.com/comment/91321065
has comment: http://stackoverflow.com/comment/91472140
has comment: http://stackoverflow.com/comment/91475520
has comment: http://stackoverflow.com/comment/91347751
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91377827
has comment: http://stackoverflow.com/comment/91394100
type: Answer
has comment: http://stackoverflow.com/comment/91337254
has comment: http://stackoverflow.com/comment/91321213

http://stackoverflow.com/comment/91297340
has text: So, `nltk.parse.corenlp` doesn't work for some reason. It says `No module named corenlp` but `nltk.parse.stanford` works for me. I have unzipped both stanford-corenlp-full-2018-02-27 and stanford-parser-full-2018-02-27. I have models.jar and parser.jar file as mentioned in the link . Also I tried `from nltk.parse import CoreNLPParser` which didn;t work as well. Also, I am not able to find englishPCFG file but I have the lexparser shell script file. I downloaded the PCFG file from github. It said `NLTK was unable to find the JAVA file Set the JAVAHOME environment variables`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52161069
type: Comment

http://stackoverflow.com/a/52209734
score: 1
has body: Try this one from bs4 import BeautifulSoup file = open('./test.xml') data = "\n".join(file.readlines()) soup = BeautifulSoup(data, "lxml") titles = soup.find_all('main_title') for title in titles: lsts = title.parent.find_all('a_listing') for lst in lsts: infos = lst.find_all('info') for info in infos: print(f"{title.text} | {lst.sub_title.text} | {info['name']}")
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52208117
answers question: http://stackoverflow.com/q/52208117
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/91243542
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52146501
has text: @EthanField Thanks, I didn't realize I was being unclear. I'll add more context in the original post.

http://stackoverflow.com/q/52137856
tagged with: markov
possible better answer: http://stackoverflow.com/a/68288454
score: 4
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/52138246
accepted answer: http://stackoverflow.com/a/52138246
has answer: http://stackoverflow.com/a/68288454
downvote count: 0
has title: Steady State Probabilities (Markov Chain) Python Implementation
favorite count: 0
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/121397943
type: AnsweredQuestion
tagged with: scipy
type: Question
has body: Hi I am trying to generate steady state probabilities for a transition probability matrix. Here is the code I am using: import numpy as np one_step_transition = np.array([[0.125 , 0.42857143, 0.75 ], [0.75 , 0.14285714, 0.25 ], [0.125 , 0.42857143, 0. ]]) def steady_state_prop(p): dim = p.shape[0] q = (p-np.eye(dim)) ones = np.ones(dim) q = np.c_[q,ones] QTQ = np.dot(q, q.T) bQT = np.ones(dim) return np.linalg.solve(QTQ,bQT) steady_state_matrix = steady_state_prop(one_step_transition.transpose()) print (steady_state_matrix) #result is : #array([0.38268793, 0.39863326, 0.21867882]) #Expected Result = (0.4,0.4,0.2) My question is why the outcome is slightly different from exact answer?

http://stackoverflow.com/a/52216761
has body: Check given number is divisible by 17 or not # function to check recursively if the # number is divisible by 17 or not def isDivisible(n): # if n=0 or n=17 then yes if (n == 0 or n == 17): return True # if n is less then 17, not divisible by 17 if (n &lt; 17): return False # reducing the number by floor(n/16) return isDivisible((int)(n &gt;&gt; 4) - (int)(n &amp; 15)) # driver code to check the above function n = 12 if (isDivisible(n)): print(n,"is divisible by 17") else: print(n,"is not divisible by 17")
answers question: http://stackoverflow.com/q/52216489
has comment: http://stackoverflow.com/comment/91382181
score: 0
has comment: http://stackoverflow.com/comment/91382829
type: Answer

http://stackoverflow.com/a/52176050
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/91302888
has comment: http://stackoverflow.com/comment/91302668
has body: Add the following code to the end of your python file. input('Press any key to exit') It will prevent the Command prompt close immediately unless you press some keys.
has comment: http://stackoverflow.com/comment/91305046
has comment: http://stackoverflow.com/comment/91302749
answers question: http://stackoverflow.com/q/52175880
has comment: http://stackoverflow.com/comment/91302854
has comment: http://stackoverflow.com/comment/91302631

http://stackoverflow.com/q/52221330
favorite count: 0
tagged with: hex
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52221923
type: Question
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/52221923
has body: I am running the below function in python (3x) to generate a random IP Address def get_ip_address(self): x = ".".join(map(str, (random.randint(0, 255) for _ in range(4)))) return x However I need to convert the IP address generated into a hex value, I dont need to do anything complicated and am happy to either convert x post creation or do it in the create Ip address function. I need to be able to easily see what the IP address is I am creating and converting as this is part of a test Suite and at the other end the Hex IP Address is converted back. I also need it in the format 0xb15150ca
has title: Create an IP Address as a hex value
has answer: http://stackoverflow.com/a/52221794
accepted answer: http://stackoverflow.com/a/52221794

http://stackoverflow.com/q/52128936
type: Question
has comment: http://stackoverflow.com/comment/91208328
score: 0
has comment: http://stackoverflow.com/comment/91208555
has title: Django - global dictionary
answer count: 0
has body: I'm trying to make a teacher/student model where every student has one (or zero) teacher and teachers have multiple students. The teacher should be able to see a list of students and the students don't need to see anything other than their own teacher. The differences between the teacher and student are few for my uses. So, I made just one custom model User and when registering you can choose whether you are a student or administrator. If you are an administrator, you must enter a "class code" for which students can sign up under your name. class User(AbstractBaseUser, PermissionsMixin): "username, password, email, etc.. goes here" usertype = models.CharField(max_length=140, null=True) classcode = models.CharField(max_length=140, null = True, unique=True) teacher = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null = True ) objects = UserManager() USERNAME_FIELD = "username" REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] def __str__(self): return self.username For teachers the teacher field would be null and for students, obviously, there would be a link to the teacher. I'm trying to manage the signup right now. def create_user(self, email, username, password, first_name, last_name): user = self.model( email = self.normalize_email(email), username = username, first_name = first_name, last_name = last_name) if user.usertype == "admin": # user is a teacher user.is_staff = True ### put code here ### user.set_password(password) user.save() return user I was thinking that when a teacher signs up, I would have a dictionary from {classCode: teacher's username (or teacher object themself(?))}. I realized that making a global variable to do this is difficult. Is there a different, easier way I might approach this without using a dictionary?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91208645
tagged with: django
tagged with: python

http://stackoverflow.com/a/54853481
score: -1
has body: Try this: from ciscoconfparse import CiscoConfParse bgp = confparse.find_blocks(r"^router bgp 65500")
downvote count: 1
answers question: http://stackoverflow.com/q/52151063
type: Answer
has comment: http://stackoverflow.com/comment/138838126
upvote count: 0

http://stackoverflow.com/q/52212262
has title: pandas groupby multiple columns values
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52212309
has body: I was try to get a average columns for all the std columns I want to add one more column to calculate the average value from Std_4-Std_10 values. Not sure should I use groupby or pivot. Thanks
linked to: http://stackoverflow.com/q/34734940
type: Question
has comment: http://stackoverflow.com/comment/91373927
duplicate of: http://stackoverflow.com/q/34734940
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/91373931
has comment: http://stackoverflow.com/comment/91374978

http://stackoverflow.com/q/52176002
downvote count: 2
possible better answer: http://stackoverflow.com/a/58240913
has answer: http://stackoverflow.com/a/52176076
accepted answer: http://stackoverflow.com/a/52176076
tagged with: string
favorite count: 0
tagged with: python
answer count: 4
linked to: http://stackoverflow.com/q/12007686
tagged with: list
has answer: http://stackoverflow.com/a/65013866
has answer: http://stackoverflow.com/a/52176084
has comment: http://stackoverflow.com/comment/91302695
has comment: http://stackoverflow.com/comment/91302857
type: Question
tagged with: quotes
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/58240913
has body: I want to know the quickest way to add single quotes to each element in a Python list created by hand. When generating a list by hand, I generally start by creating a variable (e.g. my_list), assigning it to list brackets, and then populating the list with elements, surrounded by single quotes: my_list = [] my_list = [ '1','baz','ctrl','4' ] I want to know if there is a quicker way to make a list, however. The issue is, I usually finish writing my list, and then go in and add single quotes to every element in the list. That involves too many keystrokes, I think. A quick but not effective solution on Jupyter NB's is, highlighting your list elements and pressing the single quote on your keyboard. This does not work if you have a list of words that you want to turn to strings, however; Python thinks you are calling variables (e.g. my_list = [1, baz, ctrl, 4 ]) and throws a NameError message. In this example, the list element baz would throw: NameError: name 'baz' is not defined I tried this question on SO, but it only works if your list already contains strings: Join a list of strings in python and wrap each string in quotation marks. This question also assumes you are only working with numbers: How to convert list into string with quotes in python. I am not working on a particular project at the moment. This question is just for educational purposes. Thank you all for your input/shortcuts.
has title: Python: How to add single quotes to a long list
tagged with: nameerror
upvote count: 2
linked to: http://stackoverflow.com/q/16054870
score: 0

http://stackoverflow.com/comment/91267937
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52157531
type: AnswerComment
has text: @Onyambu Oh i miss-copied it

http://stackoverflow.com/comment/91307211
type: QuestionComment
comment on: http://stackoverflow.com/q/52178302
has text: @CertainPerformance We _could_ also do it with a variable width lookbehind, but that is a performance killer, error prone, and not really what regex is intended to be doing.
score: 0
type: Comment

http://stackoverflow.com/comment/91356417
comment on: http://stackoverflow.com/q/52202924
score: 0
has text: When does the UnicodeEncodeError show up? When doing `print` in a Python console? Which python version? Which operating system?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91223519
has text: an example of a curl request to the api above?
type: Comment
comment on: http://stackoverflow.com/a/52133321
score: 0
type: AnswerComment

http://stackoverflow.com/a/52232928
has body: So I finally able to get the configuration of all the devices on the server. Problem was, the above approach works for XProtect Enterprise and XProtect Professional only, if you have an XProtect Corporate, you need a NTLM authentication and you have to call GetConfiguration function on the Server SOAP protocol. r2= '&lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"&gt;&lt;soap:Body&gt;&lt;GetConfiguration xmlns="http://videoos.net/2/XProtectCSServerCommand"&gt;&lt;token&gt;' + str(myToken) + '&lt;/token&gt;&lt;/GetConfiguration&gt;&lt;/soap:Body&gt;&lt;/soap:Envelope&gt;' data_len = str(len(r2)) s.sendall("POST /ManagementServer/ServerCommandService.svc HTTP/1.1\r\nHost: server-ip\r\nContent-Type: text/xml; charset=utf-8\r\nAuthorization: Basic (base64 encoded '*[BASIC]\username:password*')\r\nContent-Length: "+data_len+"\r\nSOAPAction: http://videoos.net/2/XProtectCSServerCommand/IServerCommandService/GetConfiguration\r\n\r\n"+ r2)
accepted answer of: http://stackoverflow.com/q/52209121
answers question: http://stackoverflow.com/q/52209121
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/q/52250064
type: UnansweredQuestion
has title: How to remove space between print and user num
linked to: http://stackoverflow.com/q/12700558
downvote count: 1
type: Question
score: -1
upvote count: 0
answer count: 1
favorite count: 0
has body: old newbie in Python, and I came across a problem. print('Adding the two numbers gives',user_num,', which is different from',str(number1 + number2),'.') output: Adding the two numbers gives 24 , which is different from 1212 . Question: How do you remove the space between 24 and the comma, and the space between 1212 and .?
has answer: http://stackoverflow.com/a/52250078
tagged with: python
duplicate of: http://stackoverflow.com/q/12700558
has comment: http://stackoverflow.com/comment/91448289

http://stackoverflow.com/q/52203111
has comment: http://stackoverflow.com/comment/91356515
score: 2
has comment: http://stackoverflow.com/comment/91355427
downvote count: 0
type: Question
type: AnsweredQuestion
has body: I was trying to filter some .txt files that are named after a date in YYYYMMDD format and contain some data about active regions in the Sun. I made a code that, given a date in YYYYMMDD format, can list the files that are within a time range which I expect the active region I am looking for to be and parse the information based on that entry. An example of these txts can be seen below and more information about it (if you feel curious) can be seen on SWPC website. :Product: 0509SRS.txt :Issued: 2012 May 09 0030 UTC # Prepared jointly by the U.S. Dept. of Commerce, NOAA, # Space Weather Prediction Center and the U.S. Air Force. # Joint USAF/NOAA Solar Region Summary SRS Number 130 Issued at 0030Z on 09 May 2012 Report compiled from data received at SWO on 08 May I. Regions with Sunspots. Locations Valid at 08/2400Z Nmbr Location Lo Area Z LL NN Mag Type 1470 S19W68 284 0030 Cro 02 02 Beta 1471 S22W60 277 0120 Cso 05 03 Beta 1474 N14W13 229 0010 Axx 00 01 Alpha 1476 N11E35 181 0940 Fkc 17 33 Beta-Gamma-Delta 1477 S22E73 144 0060 Hsx 03 01 Alpha IA. H-alpha Plages without Spots. Locations Valid at 08/2400Z May Nmbr Location Lo 1472 S28W80 297 1475 N05W05 222 II. Regions Due to Return 09 May to 11 May Nmbr Lat Lo 1460 N16 126 1459 S16 110 The code I am using to parse over these txt files is: import glob def seeker(noaa_number, t_start, path = None): ''' This function will open an SRS file and look for each line if the given AR (specified by its NOAA number) is there. If so, this function should grab the entries and return them. ''' #defaulting path if none is given if path is None: #assigning path = 'defaultpath' #listing the items within the directory files = sorted(glob.glob(path+'*.txt')) #finding the index in the list of #the starting time index = files.index(path+str(t_start)+'SRS.txt') #looping over each file for file in files[index: index+20]: #opening file f = open(file, 'r') #reading the lines text = f.readlines() #looping over each line in the text for line in…
favorite count: 0
tagged with: python-3.x
has title: Filtering and parsing text over Solar Region Summary files
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52203307
answer count: 1
accepted answer: http://stackoverflow.com/a/52203307

http://stackoverflow.com/q/52231890
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91413191
accepted answer: http://stackoverflow.com/a/52231969
type: Question
answer count: 2
has title: Fairly New to Python - Global Varibable Issue
score: 0
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52231969
linked to: http://stackoverflow.com/q/19158339
has answer: http://stackoverflow.com/a/52231971
has body: was wondering if I someone could lend a hand with the issue I am having with my python 3.4 code. I have found it hard to word my problem and searching the web for an answer has been difficult, so I thought it would be easier if I were to show the code and the issue to be resolved. cola_cost = 2 surcharge = 0 def calc_takeaway(cost): global surcharge cost = cost * 1.05 surcharge = surcharge + (cost * 0.05) cola_place = input("Do you want your cola to go? ") if cola_place == "yes": calc_takeaway(cola_cost) print("$"cola_cost) ## cola cost should be $2.10 but instead prints out $2 print("$"surcharge) Basically, my cola_cost will not change its global value after being passed into the calc_takeaway function. Sorry if this is too basic I would kist like to get this issue solved. Thank you. EDIT: I'd also like to mention that I would like to use the function on different cost variables (i.e fanta_cost, water_cost...) as well.
possible better answer: http://stackoverflow.com/a/52231971

http://stackoverflow.com/comment/91347169
type: QuestionComment
comment on: http://stackoverflow.com/q/52189626
score: 0
type: Comment
has text: And you can also contact the sklearn authors on [the mailing list](https://mail.python.org/mailman/listinfo/scikit-learn)

http://stackoverflow.com/q/52173662
has comment: http://stackoverflow.com/comment/91298281
answer count: 1
accepted answer: http://stackoverflow.com/a/52173764
tagged with: python
tagged with: pygame
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52173764
has body: Just making a simple game to practise more than anything where ants start in a nest they leave if they can and find the nearest food that isn't already targeted, so they each have their own path and target. They do this already but whenever I actually move the sprites all the sprites in this group position attributes seem to follow one ants instead of their own path. import pygame import settings import random vec = pygame.math.Vector2 class Ant(pygame.sprite.Sprite): def __init__(self, world): self.world = world pygame.sprite.Sprite.__init__(self, self.world.ants, self.world.all_sprites) self.image = pygame.Surface((settings.ANT_RADIUS*2, settings.ANT_RADIUS*2)) self.draw() self.rect = self.image.get_rect() self.pos = self.world.nest.pos self.rect.center = self.pos self.in_nest = True self.image.set_colorkey((0, 0, 0)) self.target = False def update(self): if self.in_nest: self.try_leave_nest() else: if self.target != False: self.move_to_food() else: self.target = self.find_food() def draw(self): pygame.draw.circle(self.image, settings.ANT_COLOUR, (settings.ANT_RADIUS, settings.ANT_RADIUS), settings.ANT_RADIUS) def move_to_food(self): self.direction = vec(self.target.pos-self.pos).normalize() self.pos += self.direction self.rect.center = self.pos print(self.pos) def find_food(self): self.closest = settings.WINDOW_WIDTH self.closest_food = False for food in self.world.food: if not food.taken: self.distance = self.pos.distance_to(food.pos) if self.distance &lt;= self.closest: self.closest = self.distance self.closest_food = food self.closest_food.taken = True return self.closest_food def try_leave_nest(self): leave_chance = settings.ANT_LEAVE_CHANCE leave_num = random.random() if leave_num &lt; leave_chance: self.in_nest = False
tagged with: sprite
has title: One instance of a pygame sprite is changing a whole groups pos
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91313796

http://stackoverflow.com/a/52158058
downvote count: 2
score: 0
has body: try this one def check_not_exist(d,k): #if keys exists in dict,raise it if k in d: raise else: return True
type: Answer
answers question: http://stackoverflow.com/q/52157937
upvote count: 2

http://stackoverflow.com/comment/91313698
comment on: http://stackoverflow.com/a/52181353
has text: i suggest you work with your environment from AWS lambda SDK which you can easily require in your script/file. see invoking lambda functions https://docs.aws.amazon.com/lambda/latest/dg/invoking-lambda-functions.html
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52214791
accepted answer of: http://stackoverflow.com/q/52214400
has body: For loops are not usually used for checking ranges. Comparison operators (&lt;, &gt;, &lt;=, &gt;=) are used for this type of task. In your case, income is a float, so there are 9325 * 2**64 checks that you must do if you want to use a for loop to check all possible incomes. But if you want to make it work, you can do import struct def reinterpretAsInt(f): return struct.unpack('Q', struct.pack('d', f))[0] def reinterpretAsFloat(n): return struct.unpack('d',struct.pack('Q', n))[0] for testIncome in range(0,reinterpretAsInt(9325)): # print('Checking income amount: ' + str(reinterpretAsFloat(testIncome))) if income == reinterpretAsFloat(testIncome): print("Your tax rate is 10%") break If you run this code, you will realise how inefficient it is to check each possible income level using a for loop. You should be using comparison operators for this type of problem. Your current code is fine, but you could condense all the thing == "1" checks into a single if statement.
has comment: http://stackoverflow.com/comment/91403475
answers question: http://stackoverflow.com/q/52214400
type: AcceptedAnswer
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91399812

http://stackoverflow.com/comment/92212899
score: 0
has text: This is common error in Windows OS. Try and install Microsoft Visual Studio Redistributable Package. Choose correct version compatible to your python version. This will solve the issue. Worked for me.
comment on: http://stackoverflow.com/q/52120694
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91328072
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52187482
type: Comment
has text: I know that it is weir but if I use `navMenu.click()` i get error" element not visible" and the script doesn't even click anything. In case of `browser.execute_script(navMenu.click())` script clicks the element and crashes afterwards because of the error from first post.

http://stackoverflow.com/q/52174473
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/52174591
has title: Interact with the UI of an application in python
tagged with: python
linked to: http://stackoverflow.com/q/136734
upvote count: 3
has body: I want to open a program and interact very briefly with the UI of it. For now I managed to open the program with this line: subprocess.call([r"C:\Users\path\to\program\program.exe", "first-parameter", "second-parameter"]) The program displays at the start a small warning box with the button "Ok". I would like to simulate a key press "Enter" so that the program moves on. I tried to implement it like it was explained in in this question: import subprocess import win32com.client as comctl wsh = comctl.Dispatch("WScript.Shell") subprocess.call([r"C:\Users\path\to\program\program.exe", "first-parameter", "second-parameter"]) wsh.AppActivate("program.exe") wsh.SendKeys("{Enter}") The SendKeys() argument was not reached until I closed the program.exe. After I closed the program.exe the "Enter" key got pressed. Is there a way to interact with the UI of program.exe or do the KeyPress() so it gets reached?
answer count: 1
has answer: http://stackoverflow.com/a/52174591
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/91472094
type: QuestionComment
comment on: http://stackoverflow.com/q/52259978
has text: I'm still not following why you need it to be interactive. Please give me context about what you're trying to do with Python. I suspect this is an [XY problem](http://xyproblem.info/).
score: 0
type: Comment

http://stackoverflow.com/q/52120651
has answer: http://stackoverflow.com/a/52120751
type: Question
has body: I can not find a way to save properly and retrieve properly a multi-indexed pandas dataframe, so that to retain the multi-indexed column structure. For a reproducible example: toy_data.to_json() '{"["GOOG","Shares"]":{"1521849600000":null,"1521936000000":null,"1522368000000":null,"1522454400000":694548763.0,"1522540800000":null},"["GOOG","ROE"]":{"1521849600000":null,"1521936000000":null,"1522368000000":null,"1522454400000":0.1076,"1522540800000":null},"["FB","Shares"]":{"1521849600000":null,"1521936000000":null,"1522368000000":null,"1522454400000":2398606201.0,"1522540800000":null},"["FB","ROE"]":{"1521849600000":null,"1521936000000":null,"1522368000000":null,"1522454400000":0.2465,"1522540800000":null}}' toy_data.to_csv('toy_data.csv') toy_data1 = pd.read_csv('toy_data.csv')
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/52120751
tagged with: python
has comment: http://stackoverflow.com/comment/91192635
score: 0
answer count: 2
has title: Saving and Loading a Multindexed Pandas Dataframe and retaining the Column Structure
tagged with: multi-index
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52120809
has answer: http://stackoverflow.com/a/52120809

http://stackoverflow.com/q/52250564
favorite count: 0
type: Question
has title: merge 2 different lists to dictionary
tagged with: python
has comment: http://stackoverflow.com/comment/91449015
has answer: http://stackoverflow.com/a/52250604
score: 0
answer count: 2
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91448975
accepted answer: http://stackoverflow.com/a/52250604
has body: I am trying to merge two lists with different lengths to dictionary. Pls help listA = ['2','4','6','8','10','12','14','16','18','20','22','24','26','28'] listB = ['host1','host2','host3','host4'] expected output: { host1: [2,10,18,26], host2: [4,12,20,28], host3: [6,14,22], host4 : [8,16,24] }
possible better answer: http://stackoverflow.com/a/52250608
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52250608

onnx-coreml
tags question: http://stackoverflow.com/q/52171143
type: Tag
tag name: onnx-coreml

http://stackoverflow.com/comment/96120802
has text: Check that, as of version 1.2.1.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52136757

http://stackoverflow.com/comment/91485020
score: 0
type: Comment
type: QuestionComment
has text: [here](https://stackoverflow.com/questions/20015550/read-file-data-without-saving-it-in-flask/20017830#20017830)
comment on: http://stackoverflow.com/q/52268433

http://stackoverflow.com/a/52342425
has body: So... I was getting annoyed with the fact that it wasn't working. I decided to close pycharm, delete .idea, and reload it. I did that, it didn't work. I deleted .idea again, but before running it, changed the interpreter... IT. WORKED. I guess it didn't save the interpreter in .idea properly...
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52248061
score: 0
answers question: http://stackoverflow.com/q/52248061

http://stackoverflow.com/a/52132481
type: Answer
answers question: http://stackoverflow.com/q/52132331
has body: An alternative to concatenate approach is to make a recipient array, and copy values to it: In [483]: a = np.arange(300).reshape(100,3) In [484]: b=np.array([8,9]) In [485]: res = np.zeros((100,5),int) In [486]: res[:,:3]=a In [487]: res[:,3:]=b sample timings In [488]: %%timeit ...: res = np.zeros((100,5),int) ...: res[:,:3]=a ...: res[:,3:]=b ...: ...: 6.11 µs ± 20.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [491]: timeit np.concatenate((a, b.repeat(100).reshape(2,-1).T),1) 7.74 µs ± 15.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [164]: timeit np.concatenate([a, np.ones([a.shape[0],1], dtype=int).dot(np.array([b]))], axis=1) 8.58 µs ± 160 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52132331

http://stackoverflow.com/comment/91196294
has text: Share code you're using with locators, steps and try add waits
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52122354

http://stackoverflow.com/comment/91434372
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52243000
has text: Please help me check this problem again. Thank you

http://stackoverflow.com/q/52240213
score: 1
linked to: http://stackoverflow.com/q/46525786
type: Question
accepted answer: http://stackoverflow.com/a/52240284
downvote count: 0
has body: I am interested in a very 'Pandas-like' solution in the following problem. I have a straightforward implementation with looping over rows and checking conditions in both columns. I'm working on an NLP problem and need to locate tokens in sentences. I have two dataframes, one is the with start_0 and end_0 positions of tokens (drugs) and the second dataframe contains start_1 and end_1 of sentences. For example: Position of tokens: df_0 = start_0 end_0 token 0 20 27 aspirin 1 50 59 trazodone 2 81 88 placebo 3 121 127 haldol Position of sentences: df_1= start_1 end_1 0 0 17 1 17 29 2 29 46 3 46 64 4 64 76 5 76 81 6 81 97 7 97 227 I need to create a new column in df_1 and put in a corresponding row the token, namely: df_1= start_1 end_1 token 0 0 17 NaN 1 17 29 aspirin 2 29 46 NaN 3 46 64 trazodone 4 64 76 NaN 5 76 81 NaN 6 81 97 placebo 7 97 227 haldol Simply match two data frame if the position of a token is within the sentence. There must a simple solution with Pandas functionality, rather then looping over rows and checking both boundaries.
has title: An efficient way to find rows in pandas with columns satisfying certain conditions
answer count: 2
tagged with: pandas
favorite count: 0
possible better answer: http://stackoverflow.com/a/52240380
has answer: http://stackoverflow.com/a/52240284
has answer: http://stackoverflow.com/a/52240380
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/91324266
score: 0
type: Comment
type: QuestionComment
has text: You are passing a function call to `.execute_script`, you need to pass it a string, or just call `navMenu.click()`
comment on: http://stackoverflow.com/q/52187248

http://stackoverflow.com/comment/91429176
type: AnswerComment
has text: Happy to help. Please accept my answer if you are happy with it.
comment on: http://stackoverflow.com/a/52229457
type: Comment
score: 0

http://stackoverflow.com/comment/91424089
has text: This code is not caused by any of the code you have posted here. Somewhere you are doing either `reverse('songs', ('all',))` in Python, or `{% url 'songs' 'all' %}` in a template. That is the code you need to post.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/52237276
type: Comment

http://stackoverflow.com/a/52256244
answers question: http://stackoverflow.com/q/52255926
upvote count: 1
score: 1
has body: Short answer : what you ask for is not possible, period. Longer answer : given that a django production setup will run more than one Django process (yes, even with one single server), there's no such thing as "THE" django server and the only way to "share data" from celery workers to the django processes is to store them in "something" that is 1/ available to all the workers and all the django processes and 2/ supports concurrent access - IOW in a database server process of some sort (your SQL db for persistant data, Redis for transiant data).
has comment: http://stackoverflow.com/comment/91460116
has comment: http://stackoverflow.com/comment/91461056
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91459877
has comment: http://stackoverflow.com/comment/91460863
accepted answer of: http://stackoverflow.com/q/52255926
type: Answer
has comment: http://stackoverflow.com/comment/91461805

http://stackoverflow.com/q/52168164
score: 3
answer count: 0
has comment: http://stackoverflow.com/comment/91286852
downvote count: 0
has comment: http://stackoverflow.com/comment/91287606
has comment: http://stackoverflow.com/comment/91286577
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91287547
linked to: http://stackoverflow.com/q/15455048
has comment: http://stackoverflow.com/comment/91286453
has comment: http://stackoverflow.com/comment/91302771
has comment: http://stackoverflow.com/comment/91300579
upvote count: 3
has comment: http://stackoverflow.com/comment/91294830
has comment: http://stackoverflow.com/comment/91288592
has comment: http://stackoverflow.com/comment/91288187
has comment: http://stackoverflow.com/comment/91320084
linked to: http://stackoverflow.com/q/27418943
has body: I have a super huge numpy array which memory allocated to it never gets free again. I simply demonstrate my situation so you can see the problem yourself. Memory allocated to simple numpy arrays will immediately freed up after that variable can be remove (like below which I delete it): import numpy as np X = np.ones((40000, 40000)) X.nbytes 12800000000 del(X) When I run the code above, all the 12 GB memory will free up immediately. But in case of nested numpy arrays things get complicated: import numpy as np import random foo = np.array([np.array([np.ones((256,)) for j in range(random.randint(100, 150))]) for i in range(40000)]) sum(f.nbytes for f in foo) 10240481280 del(foo) Now the 10 GB of memory will never gets freed even if you run gc.collect() explicitly. Do you guys have any clue? P.S: The env: Ubuntu + Python 2.7 + numpy 1.15.1
has comment: http://stackoverflow.com/comment/91309701
has comment: http://stackoverflow.com/comment/91320051
linked to: http://stackoverflow.com/q/39255371
has comment: http://stackoverflow.com/comment/91287795
favorite count: 0
has comment: http://stackoverflow.com/comment/91286995
type: UnansweredQuestion
tagged with: memory-leaks
tagged with: python
has comment: http://stackoverflow.com/comment/91287780
has comment: http://stackoverflow.com/comment/91289006
has comment: http://stackoverflow.com/comment/91287738
has title: How to free up memory allocated to nested numpy arrays?

http://stackoverflow.com/comment/91443128
score: 2
has text: You have to ``return self`` in the ``__enter__`` method.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52247573

http://stackoverflow.com/q/52127046
has answer: http://stackoverflow.com/a/78008073
upvote count: 8
type: Question
tagged with: github-api
answer count: 2
has title: How can I pull private repo data using GitHub API?
has comment: http://stackoverflow.com/comment/91264605
has body: I am a member of an organization which has a lot of private repositories on GitHub. I need to use the GitHub API to get data from the private repositories. I am using the following python code: url = "https://api.github.com/orgs/myorg/repos?access_token=[mytokenhere]" headers = {"Authorization": "token [myPATHhere]"} session = requests.Session() response = session.get(url, headers = headers) content = response.text my_json = json.loads(response.text) for item in my_json: print(item['html_url']) Where PAT = my access token. This still only returns the public repositories. I've seen the related question but the listed solutions do not solve my problem. Note that I've authorized my access token to get into the private repository. I've also tried api.github.com/users/repos and api.github.com/users/[myorghere] and still no private repos are returned. Am I not submitted the token correctly?
accepted answer: http://stackoverflow.com/a/52251751
favorite count: 0
score: 8
linked to: http://stackoverflow.com/q/20396329
linked to: http://stackoverflow.com/q/21907278
tagged with: python
has answer: http://stackoverflow.com/a/52251751
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/78008073

http://stackoverflow.com/a/52175642
type: Answer
score: 2
downvote count: 0
has body: Using a 600x600 pixel image homograpy-test.jpg: import cv2 import numpy as np #load image img = cv2.imread('homography-test.jpg', cv2.IMREAD_COLOR) #corners of book covers (before) frontCoverPtsBefore = np.array([[32, 48], [279, 136], [247, 430], [39, 281]], dtype="float32") backCoverPtsBefore = np.array([[279, 136], [474, 36], [463, 316], [247, 430]], dtype="float32") #corners of book covers (after) frontCoverPtsAfter = np.array([[0, 0], [299, 0], [299, 599], [0, 599]], dtype="float32") backCoverPtsAfter = np.array([[300, 0], [599, 0], [599, 599], [300, 599]], dtype="float32") #get the transformation matrices for both covers M_front = cv2.getPerspectiveTransform(frontCoverPtsBefore, frontCoverPtsAfter) M_back = cv2.getPerspectiveTransform(backCoverPtsBefore, backCoverPtsAfter) #warpPerspective both images img_front = cv2.warpPerspective(img, M_front, (600, 600)) img_back = cv2.warpPerspective(img, M_back, (600, 600)) #copy half of the warped back cover into the warped front cover np.copyto(img_front[:, 300:, :], img_back[:, 300:, :]) #display before and after cv2.imshow('img', img) cv2.imshow('img_front', img_front) cv2.waitKey(0) cv2.destroyAllWindows() Before and After:
accepted answer of: http://stackoverflow.com/q/52175245
upvote count: 2
answers question: http://stackoverflow.com/q/52175245
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91306232

http://stackoverflow.com/a/52195600
has comment: http://stackoverflow.com/comment/91505591
answers question: http://stackoverflow.com/q/52188775
has comment: http://stackoverflow.com/comment/91411076
has body: You need to send rank to your get_details callback using meta: def parse(self, response): for movie in response.xpath(".//tbody[@class='lister-list']/tr/td[@class='titleColumn']"): movie_rank = movie.xpath('./text()').re_first(r'(\d+)') movie_url = movie.xpath('./a/@href').extract_first() movie_full_url = response.urljoin(movie_url) print("FOOOOOOOOOnd URL: " + movie_url) yield scrapy.Request(movie_full_url, callback=self.get_details, meta={"rank": movie_rank}) def get_details(self, response): item = IMDB_dict() item['rank'] = response.meta["rank"] item['name'] = response.xpath(".//div[@class='title_bar_wrapper']/div[@class='titleBar']/div[@class='title_wrapper']/h1/text()").extract_first().strip("\t\r\n '\"") item['phone'] = response.xpath(".//div[@class='titleBar']/div[@class='title_wrapper']/h1/span[@id='titleYear']/a/text()").extract_first().strip("\t\r\n '\"") item['email'] = response.xpath(".//div[@class='plot_summary ']/div[@class='summary_text']/text()").extract_first().strip("\t\r\n '\"") # Return that item to the main spider method: yield item UPDATE If you check logs you'll find this error AttributeError: 'NoneType' object has no attribute 'strip' Sometimes .extract_first() returns None and you can't strip() it. I recommend you to use Scrapy Item Loaders
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52188775
score: 1
has comment: http://stackoverflow.com/comment/91501202
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/52141393
has body: I have two machines A and B. Machine A is my dev environment and machine B is my deployment machine. Machine A has a bunch of pip libraries installed. Is there a way for me to install those same pip libraries on machine B. The only way I can think of right now is to do a pip list and install those libraries one by one. Is there a faster approach ?
has comment: http://stackoverflow.com/comment/91232557
tagged with: pip
type: AnsweredQuestion
has title: Is there a command / procedure to replicate pip libraries
has comment: http://stackoverflow.com/comment/91232582
type: Question
linked to: http://stackoverflow.com/q/23640182
possible better answer: http://stackoverflow.com/a/52141407
has comment: http://stackoverflow.com/comment/91232566
has answer: http://stackoverflow.com/a/52141417
has answer: http://stackoverflow.com/a/52141407
has answer: http://stackoverflow.com/a/52141414
has comment: http://stackoverflow.com/comment/91232570
accepted answer: http://stackoverflow.com/a/52141414
score: 0
answer count: 3
tagged with: python

http://stackoverflow.com/comment/91350102
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52200369
has text: got it. Please check the edited answer
score: 0

http://stackoverflow.com/q/52221144
answer count: 1
has body: I have a complicated use case which I've distilled down to just incrementing a variable in Tensorflow. a = tf.Variable(1, trainable=False) b = tf.constant(2) a = tf.assign_add(a, b) In [32]: type(a) Out[32]: tensorflow.python.framework.ops.Tensor My actual use case is actually generating a new random tensor under certain conditions each time my custom Keras layer is called, but seems like it boils down to a variable turning into a tensor if I do anything to it. Is the correct use case to wrap each a = tf.Variable(tf.assign(a, b)) and have a change everytime my keras layer is called?
score: 0
has answer: http://stackoverflow.com/a/52226204
has title: Keep changing the same variable in Tensorflow
tagged with: python
type: AnsweredQuestion
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/52226204

http://stackoverflow.com/q/52193571
has title: Adding an Average Column to a Pandas Multiindex Dataframe
answer count: 2
downvote count: 0
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52193802
has body: I have a dataframe df first bar baz second one two one two A 0.487880 -0.487661 -1.030176 0.100813 B 0.267913 1.918923 0.132791 0.178503 C 1.550526 -0.312235 -1.177689 -0.081596 I'd like to add a average columns and then move the average to the front df['Average'] = df.mean(level='second', axis='columns') #ERROR HERE cols = df.columns.tolist() df = df[[cols[-1]] + cols[:-1]] I get the error: ValueError: Wrong number of items passed 2, placement implies 1 Maybe, I could add each column df['Average', 'One'] = ... in the mean one at a time but that seems silly especially as the real life index is more complicated. Edit: (Frame Generation) arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] tuples = list(zip(*arrays)) index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) df = DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index)
accepted answer: http://stackoverflow.com/a/52193725
has answer: http://stackoverflow.com/a/52193802
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: dataframe
tagged with: multi-index
has comment: http://stackoverflow.com/comment/91336979
type: Question
has answer: http://stackoverflow.com/a/52193725

http://stackoverflow.com/q/52269056
upvote count: 3
has comment: http://stackoverflow.com/comment/91492214
downvote count: 2
has body: import matplotlib.pyplot as plt import numpy as np from scipy.signal import find_peaks import pdb file = open("Data1r2.txt", 'r') lines = file.readlines() file.close() t = [] z = [] y = [] x = [] with open("Data1r2.txt", 'r') as f: for line in f: parts = line.split(", ") x.append(float(parts[0][2:])) y.append(float(parts[1][2:])) z.append(float(parts[2][2:])) t.append(float(parts[3][2:])) This part im mainly annotating the highest peak value of the graph, but how can i annotate all peak values at a fixed distance? say distance = 10,000 fig = plt.figure() ax = fig.add_subplot(111) line, = ax.plot(t, z) ymax = max(z) xpos = z.index(ymax) xmax = t[xpos] text= "x={:.1f}, y={:.1f}".format(xmax, ymax) #Annotation(correct) ax.annotate(text, xy=(xmax, ymax), xytext=(xmax, ymax), arrowprops=dict(facecolor='black', shrink=0.05), ) plt.legend() plt.show() This is what i currently have annotating only the peak value: Data X:-241, Y:-31, Z:17, T:73823 X:-241, Y:-31, Z:17, T:73952 X:-240, Y:-30, Z:26, T:74073 X:-240, Y:-30, Z:26, T:74191 X:-240, Y:-30, Z:26, T:74312 X:-240, Y:-32, Z:39, T:74432 X:-240, Y:-32, Z:39, T:74549 X:-240, Y:-32, Z:39, T:74668 X:-239, Y:-21, Z:12, T:74785 X:-239, Y:-21, Z:12, T:74904 X:-239, Y:-21, Z:12, T:75022 X:-246, Y:15, Z:18, T:75142 X:-246, Y:15, Z:18, T:75260 X:-246, Y:15, Z:18, T:75378 X:-250, Y:19, Z:14, T:75498 X:-250, Y:19, Z:14, T:75615 X:-250, Y:19, Z:14, T:75732 X:-239, Y:-5, Z:27, T:75854 X:-239, Y:-5, Z:27, T:75972 X:-239, Y:-5, Z:27, T:76102 X:-236, Y:-19, Z:46, T:76240 X:-236, Y:-19, Z:46, T:76369 X:-236, Y:-19, Z:46, T:76489 X:-235, Y:-14, Z:32, T:76610 X:-235, Y:-14, Z:32, T:76727 X:-235, Y:-14, Z:32, T:76845 X:-244, Y:-16, Z:22, T:76963 X:-244, Y:-16, Z:22, T:77081 X:-244, Y:-16, Z:22, T:77201 X:-220, Y:-25, Z:-3, T:77346 X:-220, Y:-25, Z:-3, T:77464 X:-220, Y:-25, Z:-3, T:77580 X:-229, Y:24, Z:2, T:77699 X:-229, Y:24, Z:2, T:77814 X:-229, Y:24, Z:2, T:77934 X:-248, Y:-20, Z:0, T:78052 X:-248, Y:-20, Z:0, T:78171 X:-248, Y:-20, Z:0, …
has comment: http://stackoverflow.com/comment/91559072
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91520794
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/50756793
has comment: http://stackoverflow.com/comment/115831011
answer count: 1
has comment: http://stackoverflow.com/comment/91492169
score: 1
has answer: http://stackoverflow.com/a/52272655
has title: How do i annotate all peak values
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/comment/91390423
score: 0
type: Comment
has text: @Dennis how can I confirm it, I just ran the install command.
type: QuestionComment
comment on: http://stackoverflow.com/q/52220670

timer
tag name: timer
type: Tag
tags question: http://stackoverflow.com/q/52146501

http://stackoverflow.com/comment/91341921
comment on: http://stackoverflow.com/q/52195658
score: 0
type: Comment
has text: nevermind, I think i got it. looks great now live testing. ;) thanks alot
type: QuestionComment

http://stackoverflow.com/a/52125788
downvote count: 0
has comment: http://stackoverflow.com/comment/91202592
has body: You need to import the module itself not just logging: In [1]: import logging In [2]: 'config' in dir(logging) Out[2]: False In [3]: import logging.config In [4]: 'config' in dir(logging) Out[4]: True Why? It looks like it is not a module included when you import the package, since it is not a namespace of __init__.py in the logging package, however it is in the directory, hence you can still import it explicitly: &gt; pwd /usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging ls -1 *py __init__.py config.py handlers.py
type: Answer
answers question: http://stackoverflow.com/q/52125707
has comment: http://stackoverflow.com/comment/91202297
score: 16
accepted answer of: http://stackoverflow.com/q/52125707
upvote count: 16
has comment: http://stackoverflow.com/comment/91202548
type: AcceptedAnswer

pca
tags question: http://stackoverflow.com/q/52235314
tag name: pca
type: Tag
tags question: http://stackoverflow.com/q/52182048

http://stackoverflow.com/q/52225400
answer count: 1
has comment: http://stackoverflow.com/comment/91450436
tagged with: python
has comment: http://stackoverflow.com/comment/91759485
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52606030
accepted answer: http://stackoverflow.com/a/52606030
tagged with: plotly
type: Question
has body: I didn't succeed to use scaleanchor for Surface plot in Plotly: x = np.linspace(0,9,100) y = np.linspace(0,3,100) mx, my = np.meshgrid(x,y) mz = np.sin(my) * np.cos(mx) trace = go.Surface(x=mx, y=my, z=mz) layout = go.Layout( yaxis={'scaleanchor':'x'}, # zaxis={'scaleanchor':'x'}, ) py.iplot([trace], layout) Two issues: zaxis is not allowed in Layout yaxis={'scaleanchor':'x'} has no effect, a cube from the top is not a square. Here is the result I want from the top (1 has same length in x and in y): done with import matplotlib.pylab as plt plt.axes().set_aspect('equal', 'datalim') plt.contour(mx, my, mz) Any idea how to see a cube as a cube and any shape as it is in 3D graphics with Plotly? Olivier.
has title: Orthonormal axes with 3D Surface in Plotly
score: 0

http://stackoverflow.com/a/52246428
has body: With Python 3.6+ you should consider formatted string literals (PEP 498): x = 8.5 y = 9.0 z = 8.05 for i in (x, y, z): print(f'{i:.9g}') 8.5 9 8.05 Manually, you can define a function to compare float and int values: def make_str(x): float_val = float(x) int_val = int(float_val) if float_val == int_val: return str(int_val) return str(float_val) make_str(9.0) # '9' make_str(8.5) # '8.5'
upvote count: 3
answers question: http://stackoverflow.com/q/52246391
has comment: http://stackoverflow.com/comment/91441482
has comment: http://stackoverflow.com/comment/91441062
has comment: http://stackoverflow.com/comment/91441470
score: 3
has comment: http://stackoverflow.com/comment/91441124
has comment: http://stackoverflow.com/comment/91441324
has comment: http://stackoverflow.com/comment/91441260
downvote count: 0
type: Answer

http://stackoverflow.com/a/52133068
accepted answer of: http://stackoverflow.com/q/52120756
answers question: http://stackoverflow.com/q/52120756
score: 0
type: AcceptedAnswer
type: Answer
has body: Perform 1-nearest neighbor classification using your centers only. No need for anything special here. Just assign to the nearest center.

http://stackoverflow.com/comment/91309388
has text: This does not work since most of the information would be lost (there are multiple identical values in the original dictionary, but keys need to be unique).
comment on: http://stackoverflow.com/a/52179532
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52189260
tagged with: pywin32
has comment: http://stackoverflow.com/comment/91699954
type: UnansweredQuestion
has body: Relating to a previous question of mine... win32file.ReadDirectoryChangesW doesn&#39;t find all moved files (Relative code is in there) Is there a way to actually wait for a notification that all drag and dropped files have been moved or copied? I am currently utilizing win32file.WaitForSingleObject(*args, **kwargs) to attain each individually dropped file. This is not beneficial when I need to detect a wide range of files at varying amounts (I need to detect how many files had been dropped). I have tried utilizing win32fil.WaitForMultiplObjects(*args, **kwargs), but does not seem to provide the actual amount (I cannot seem to figure out how to read the total that had been transferred or read that anything was moved in totality, it continues to only read each one as it moves). I also cannot determine when the detection ends (when the files have finished moving, totally). The result of what I want, is to detect all of them together, to inevitably create a queue (file management). For example, when you move 10 files from one directory to another, a progress window pops up alerting you of how many are being moved (10). I need to detect the amount in Python, but only AFTER the files have moved. Thank you, Sir James
tagged with: python
has comment: http://stackoverflow.com/comment/91338609
answer count: 0
has comment: http://stackoverflow.com/comment/91346370
tagged with: winapi
has comment: http://stackoverflow.com/comment/91353113
has title: win32file.WaitForMultipleObjects how to wait for all objects
has comment: http://stackoverflow.com/comment/91353444
type: Question
linked to: http://stackoverflow.com/q/49799109
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/91329641
has comment: http://stackoverflow.com/comment/91357046

http://stackoverflow.com/comment/91285493
has text: then I would check to make to see what data is making it into the request by using the debugger
type: AnswerComment
comment on: http://stackoverflow.com/a/52163092
score: 0
type: Comment

http://stackoverflow.com/q/52126270
tagged with: python
possible better answer: http://stackoverflow.com/a/52126429
linked to: http://stackoverflow.com/q/17409829
score: 1
has title: Python SQL - keep saying 'unsupported format character 'f' (0x66) at index 81' even all attributes' types are correct
upvote count: 1
tagged with: psycopg2
accepted answer: http://stackoverflow.com/a/52126587
duplicate of: http://stackoverflow.com/q/17409829
type: AnsweredQuestion
has body: insert_stat = """INSERT INTO measurement VALUES (%(Station)s, %(Date)s, %(Level)f, %(MeanDischarge)f, %(Discharge)f, %(Temp)f, %(EC)f)""" Here is my insert statement for inserting data into the table. Here is how my data looks like and the error. OrderedDict( [('Station', '219018'), ('Date', datetime.date(2004, 12, 31)), ('Level', 0.219), ('MeanDischarge', 1.996), ('Discharge', 1.731), ('Temp', None), ('EC', None)]) . db error: unsupported format character 'f' (0x66) at index 81 . I cannot figure out why it keeps showing this error, as all attributes' types are correct. The question solved. Before I did not know the psycopg converts data type automatically, so I only need to use '%s' instead of use '%f%' even though the data type is float.
tagged with: database
type: Question
answer count: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91203533
has answer: http://stackoverflow.com/a/52126587
tagged with: sql
has answer: http://stackoverflow.com/a/52126429

http://stackoverflow.com/q/52187913
tagged with: machine-learning
type: Question
tagged with: opencv
tagged with: neural-network
has answer: http://stackoverflow.com/a/52188478
tagged with: deep-learning
has body: I followed this tutorial: https://www.pyimagesearch.com/2017/09/11/object-detection-with-deep-learning-and-opencv/ I changed this part where I converted the image feed to grayscale before inserting it to the neural network frame = vs.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) frame = imutils.resize(frame, width=400) (h, w) = frame.shape[:2] blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 0.007843, (300, 300), 127.5) net.setInput(blob) detections = net.forward() However this error occurs: OpenCV(3.4.1) Error: Assertion failed (ngroups &gt; 0 &amp;&amp; inpCn % ngroups == 0 &amp;&amp; outCn % ngroups == 0) in cv::dnn::ConvolutionLayerImpl::getMemoryShapes, file D:\Build\OpenCV\opencv-3.4.1\modules\dnn\src\layers\convolution_layer.cpp, line 234 Traceback (most recent call last): File "C:/Users/Toshiba/PycharmProjects/real-time-object-detection/study7ver2.py", line 75, in &lt;module&gt; detections = net.forward() cv2.error: OpenCV(3.4.1) D:\Build\OpenCV\opencv-3.4.1\modules\dnn\src\layers\convolution_layer.cpp:234: error: (-215) ngroups &gt; 0 &amp;&amp; inpCn % ngroups == 0 &amp;&amp; outCn % ngroups == 0 in function cv::dnn::ConvolutionLayerImpl::getMemoryShapes Line 75 is: detections = net.forward() Why do I want to convert it to grayscale? Because I need to do histogram equalization before feeding the image to neural network so that the image feed at night time will be clearer.
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52188478
type: AnsweredQuestion
score: 2
has title: Neural network doesn't accept grayscale images
upvote count: 2

http://stackoverflow.com/q/52208325
has title: Jupyter Kernel is busy after code execution
favorite count: 0
has comment: http://stackoverflow.com/comment/91370951
has comment: http://stackoverflow.com/comment/91370522
has answer: http://stackoverflow.com/a/52320118
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/91370562
tagged with: jupyter-notebook
has body: I'm using Jupyter Notebook with conda and Python 3. Recently, the kernel is busy even after the code execution is finished and the execution time is way longer than usual. I have been searching around but there is no result. Any suggestions? Edit: I'm sorry for being too general. I am trying to identify the problem myself so any direction will be appreciated. After re-running the code a few times, it seems like whenever I run the following block of code, it happens: train_X = np.array(train_X) train_Y = np.array(train_Y) The previous code is as following: # In[1]: import pandas as pd from collections import OrderedDict # In[2]: df = pd.read_csv('df.csv') people_list = df['ID'].unique() product_list = df['product'].unique() # Out[2]: ID product M1 M2 M3 class 0 0 A 1 2 6 1 1 1 B 2 3 7 1 2 2 C 3 4 3 0 3 0 C 4 3 2 1 4 1 A 5 4 3 1 5 2 B 6 6 1 0 # In[3]: people_dict = {} target_dict = {} for i in range(len(people_list)): key = people_list[i] new_df = df[df['ID'] == people_list[i]] new_df = new_df.transpose() new_df.columns = new_df.iloc[1] new_df = new_df[2:-1] people_dict[key] = new_df target_dict[key] = df.iat[i, 5] for key in people_dict.keys(): for i in product_list: if i not in people_dict[key].columns: people_dict[key][i] = [0]*3 people_dict[key] = people_dict[key].reindex(sorted(people_dict[key].columns), axis = 1) # In[5]: people_values = OrderedDict() target_values = OrderedDict() # extract the value of the dataframe for key in people_dict.keys(): people_values[key] = people_dict[key].values target_values[key] = target_dict[key] # In[6]: n_samples = 1 timestes = 3 n_features = 3 train_input = list(people_values.values()) train_target = list(target_values.values()) train_X = [] train_Y = [] for i in range(len(train_input)): train_X.append(train_input[i]) train_Y.append(train_target[i]) # In[7]: train_X = np.array(train_X) train_Y = np.array(train_Y) Essentially, I am trying to do some classification with Keras LSTM and the input is historical sales of 1 person, t…
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/16819261
type: Question
accepted answer: http://stackoverflow.com/a/52320118
has comment: http://stackoverflow.com/comment/91366077
has comment: http://stackoverflow.com/comment/91366504
downvote count: 0
answer count: 1
tagged with: jupyter

http://stackoverflow.com/comment/91241375
type: QuestionComment
has text: Here is the last time the question got asked: https://stackoverflow.com/questions/44958544/python-exchangelib-how-to-access-shared-public-folders-and-calendars (it did not get an answer)
comment on: http://stackoverflow.com/q/52145707
score: 0
type: Comment

http://stackoverflow.com/q/52146092
has comment: http://stackoverflow.com/comment/91274836
type: Question
has comment: http://stackoverflow.com/comment/91391076
upvote count: 0
has body: I want to monitor my gradient boost classifier fit function monitor = make_monitor(10) # a callback funtion gs.fit(Xtrain, ytrain, monitor=monitor) which gives TypeError: fit() got an unexpected keyword argument 'monitor' Any idea how to fix this?
tagged with: monitoring
downvote count: 4
has comment: http://stackoverflow.com/comment/91353573
answer count: 1
has comment: http://stackoverflow.com/comment/91242909
tagged with: scikit-learn
has title: Python SKlearn fit() monitor TypeError
favorite count: 0
has comment: http://stackoverflow.com/comment/91271180
type: UnansweredQuestion
tagged with: python
tagged with: data-fitting
has answer: http://stackoverflow.com/a/52221426
has comment: http://stackoverflow.com/comment/91242218
score: -4

http://stackoverflow.com/comment/91274323
comment on: http://stackoverflow.com/q/52160119
has text: Maybe split by the dashes first then do a match comparison, then do another split by white spaces and match comparsion
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91638593
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [Pytorch installation issue under Anaconda](https://stackoverflow.com/questions/51735017/pytorch-installation-issue-under-anaconda)
comment on: http://stackoverflow.com/q/52244707

http://stackoverflow.com/comment/91303199
has text: I just thought should I remove the screen inheritance and just inherit from button?
comment on: http://stackoverflow.com/a/52168802
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52134236
tagged with: web-scraping
tagged with: python-requests
answer count: 1
has answer: http://stackoverflow.com/a/52135206
type: AnsweredQuestion
has title: How to web scrape MLB batting order to excel?
downvote count: 0
accepted answer: http://stackoverflow.com/a/52135206
score: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: python
tagged with: regex
has body: I am scraping baseball lineups and importing the python code into excel using pandas. What I am looking for: Remove quotation marks from names Remove brackets from start and end of each team Split names into different cells Example of current output for Team 1: ['Daniel Norris', 'Masahiro Tanaka', 'Mikie Mahtook', etc.] All of the above names have quotation marks, commas, and brackets attached to them. They are all listed in the same cell, too. Example of preferred excel output for Team 1: Daniel Norris Masahiro Tanaka Miki Mahtook etc. As you can see above I would like all of the quotation marks, commas and brackets removed. Also, I would like all of the players names from each team to be in their own respective cells. I have been looking for the right code online. So far I have seen three examples on stackoverflow.com but they look different than mine. I will show all three. Perhaps one of these can be used in this case. Example 1 using string method: s = s.strip(['o','1']) Example 2 using replace method: s = s.replace("World", "") Example 3 using remove method: x = [1,2,3,4,2,2,3] def remove_values_from_list(the_list, val): for i in range(the_list.count(val)): the_list.remove(val) remove_values_from_list(x, 2) print(x) Is it possible to implement one of these codes to do the three items I listed above? If not, perhaps someone can offer me some insight on how to better achieve my goals. I have seen some people online suggest a regex filter. I am not aware of how to use those, though. Thanks in advance for your time and effort! By the way, I am brand new to coding and scraping. I am very thankful for any help that I may receive. Please let me know if you have any questions or if I can add more detail to better assist you. Here is my code so far: from bs4 import BeautifulSoup import requests import pandas as pd url = 'http://www.baseballpress.com/lineups' soup = BeautifulSoup(requests.get(url).text, 'html.parser') all_games = [] for g in soup.find_all(class_="game")…
upvote count: 1

http://stackoverflow.com/q/52132913
has answer: http://stackoverflow.com/a/62720456
type: Question
tagged with: discord.py
downvote count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/95180578
accepted answer: http://stackoverflow.com/a/52133159
has comment: http://stackoverflow.com/comment/91216865
has answer: http://stackoverflow.com/a/74308983
tagged with: discord
favorite count: 0
has title: Discord.py --> channel.mention
has answer: http://stackoverflow.com/a/52133159
tagged with: python
possible better answer: http://stackoverflow.com/a/62720456
type: AnsweredQuestion
score: 3
has body: I'm trying to make a bot for a discord server that simply listens for specific messages, deletes them and then refers the user to a different text channel (in a clickable link by mentioning it) Here's what I have now: import Discord import asyncio client = discord.Client() @client.event async def on_message(message): msg = '{0.author.mention}\nWrong text channel\nUse '.format(message) if message.content.startswith('!p'): await client.delete_message(message) await client.send_message(message.channel, msg) return client.run('') Ideally, I'd also want to search through a list with startswith() instead of just ('!p') &amp; to ignore all messages from a specific text channel as well but I'm not sure how to do those either
upvote count: 3

http://stackoverflow.com/q/52262686
favorite count: 0
tagged with: python-internals
has comment: http://stackoverflow.com/comment/91473182
type: UnansweredQuestion
tagged with: python
has title: Inspect/disable bytecode check & regeneration in Python 2
has body: I would like to force Python to use pre-compiled bytecode files that I provide, and avoid any other behavior that 'runs the script' but wastes time trying to regenerate the bytecode. Python however is designed to make this behavior generally transparent to the user, so I can't find any obvious ways to control (or even inspect) what it's doing in this regard. My question(s): Is my only option to remove the .py source, leaving only .pyc files? (I don't want to do that because keeping the source around has proven very useful for debugging in this scenario.) How can I check up on this behavior to see what's really happening? Background &amp; Motivation I am creating a package of Python modules to be distributed over read-only network file system, and I include pre-compiled bytecode as .pyc along with the Python packages. I can guarantee that the end users will always be using it with the same version of Python, on the same Linux OS, with the same kernel, in the same environment, etc, and therefore should never have to regenerate the bytecode. (This is a special setup for a mid-sized scientific experiment where we enforce these things in the environment we provide for our software developers. The package manager in this environment refuses to set up packages that don't match each other in the ways we specify.) In this context, I want to ensure that Python does not try to regenerate bytecode or write .pyc's because we want to avoid slow startup times importing some large modules (matplotlib, scipy, and some others). Python's default behavior, as I understand it, is to always check if the .pyc files are stale always regenerate this bytecode if it is stale always try to overwrite the .pyc file with the new bytecode, and never tell the user if overwriting the .pyc failed. Step 1 should not be necessary, but I'm not too worried about it because it only requires checking a few bytes. I think it doesn't take much time (even on our network file system, which is optimized for ser…
score: 2
downvote count: 0
answer count: 0
type: Question
tagged with: performance
upvote count: 2
tagged with: python-import

http://stackoverflow.com/a/52231779
accepted answer of: http://stackoverflow.com/q/52231766
answers question: http://stackoverflow.com/q/52231766
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91413084
score: 5
type: Answer
has body: You need to change the 'Nan' to np.nan, then using stack with groupby join df=df.replace('Nan',np.nan) df.stack().groupby(level=0).agg(','.join) Out[570]: 0 A,B 1 A,C 2 C 3 A,B,C dtype: object #df['column-d']= df.stack().groupby(level=0).agg(','.join)
has comment: http://stackoverflow.com/comment/91413117
upvote count: 5

http://stackoverflow.com/comment/91369369
type: QuestionComment
comment on: http://stackoverflow.com/q/52209943
score: 1
has text: Knowing the purpose is critical in designing an efficient data structure and algorithm. What is the goal that you are trying to achieve? If you merely want a word count, simply use a hashmap (dictionary) since it has O(1) operations.
type: Comment

http://stackoverflow.com/q/52124417
tagged with: dataframe
score: -1
answer count: 2
tagged with: pandas
downvote count: 1
has answer: http://stackoverflow.com/a/52127297
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 0
has body: I scraped a bunch of tables of financial data using pandas.read_excel. I am trying to search through the list of dataframes and select only the ones that contain a certain value/string. Is it possible to do that? I had thought I could do something like: search = [x.isin('string') for x in df_list]
has answer: http://stackoverflow.com/a/52124431
has title: Searching a list of dataframes for a specific value
type: Question

http://stackoverflow.com/a/68073303
has body: Instead of using list st = [] use a dict dt = {}. Also, in your case for performance looping over a set is better than going through all list elements, count method did this for you just loop over a set instead. At the end get index of maximum value of dictionary dt: def freq(L): dt = {} for i in set(L): dt[i] = L.count(i) return max(dt, key=lambda k: dt[k]) print(freq([4, 6, 4, 3, 9, 1, 4])) #4
score: 0
answers question: http://stackoverflow.com/q/52194235
type: Answer

http://stackoverflow.com/a/52178631
has comment: http://stackoverflow.com/comment/91308173
has comment: http://stackoverflow.com/comment/91313253
has comment: http://stackoverflow.com/comment/91307950
answers question: http://stackoverflow.com/q/52178474
score: 0
has comment: http://stackoverflow.com/comment/91312126
type: Answer
has body: Use regex pattern r"\"variants\":\[(.*?)\]" Demo: from bs4 import BeautifulSoup import json import re s = """ """ soup = BeautifulSoup(s, "html.parser") src = soup.find("script") m = re.search(r"\"variants\":\[(.*?)\]", src.string) if m: data = json.loads(m.group(1)) print(data) Output: {u'sku': u'1725205212', u'title': u'Black', u'id': 37834367948L, u'option2': None, u'option3': None, u'option1': u'Black'}
has comment: http://stackoverflow.com/comment/91308698
has comment: http://stackoverflow.com/comment/91308043
has comment: http://stackoverflow.com/comment/91307721
has comment: http://stackoverflow.com/comment/91308111
has comment: http://stackoverflow.com/comment/91308241

http://stackoverflow.com/q/52189823
favorite count: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91329410
downvote count: 0
score: 1
type: Question
has body: i have created a virtual environment for python for developement. I need module openpyxl for my work. first i have downloaded .tar.gz file then i am using the command pip install repo/openpyxl-2.5.6 tar.gz where 'repo" is directory where i have kep my .tar.gz file .. After using this error i am getting the following error- [venv] sccj019251&gt; pip install repo/openpyxl-2.5.6.tar.gz Processing ./repo/openpyxl-2.5.6.tar.gz Collecting jdcal (from openpyxl==2.5.6) Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fc0f1ecccf8&gt;, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/jdcal/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fc0f1ea6320&gt;, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/jdcal/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fc0f1ea65c0&gt;, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/jdcal/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fc0f1ea6dd8&gt;, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/jdcal/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fc0f1ea66a0&gt;, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/jdcal/ Could not find a version that satisfies the requirement jdcal (from openpyxl==2…
has title: could not find a version that satisfies the requirement jdcal
upvote count: 1
has comment: http://stackoverflow.com/comment/91330094

http://stackoverflow.com/a/52171767
type: Answer
has body: tf.layers.conv2d has a padding parameter that you can use to do this. The default is "valid" which means no padding is done, so each convolution will slightly shrink the input. You can pass padding="same" instead. This will apply padding such that the output of the convolution is equal in size to the input. This is before strides, so using a stride of 2 will still downsample by a factor 2. In your example, using padding="same" should result in the convolution output to have size 128x128.
accepted answer of: http://stackoverflow.com/q/52166594
score: 0
answers question: http://stackoverflow.com/q/52166594
type: AcceptedAnswer

http://stackoverflow.com/q/52143917
tagged with: python
has body: I would like to make a class for taking inputs from the user and then return all these inputs for later process. An example, after taking inputs from the users (filenames) then the program stores the names in list. The program later will load the list and perform the process based on each filename for one process. More explanations: User inputs 3 filenames, 3 output filenames, Name of item within file, Json filenames. I will create a class(Reason I create it so that it looks nice and wont be too messy since it doesnt contain in a function or class) to take these inputs and then return it. Program reads the input one by one and perform the process in one script. My code: class ReturnAllInput(): def __init__(self,Morefilenames, Yourfilename, YourJsonName, Outputname, NameWithin): self.Morefilenames = Morefilenames self.Yourfilename = Yourfilename self.YourJsonName = YourJsonName self.Outputname = Outputname self.NameWithin = NameWithin def allInput(): Morefilenames = [] while True: a = input("Please enter your Morefilenames " ) if a == "Complete": break else: Morefilenames .append(a) # user typed complete print("You entered {} Morefilenames ".format(len(Morefilenames ))) for n in Morefilenames : print('{}.txt'.format(n)) Yourfilename= input("Yourfilename") YourJsonName= input("YourJsonName") Outputname= input("Outputname") NameWithin= input("NameWithin") return ReturnAllInput(Morefilenames , Yourfilename, YourJsonName, Outputname, NameWithin) for l in allinput(): #this is the section I do not know how to change it so that I could loop my return values of Morefilenames) if __name__ == "__main__": If my codes arent good enough, please do let me know so that I could improve more. I am still a beginner and would like to learn more. Thank you in advance.
linked to: http://stackoverflow.com/q/419163
tagged with: list
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91238126
has comment: http://stackoverflow.com/comment/91238071
has title: return multiple values by using class to take inputs from users
type: Question
has answer: http://stackoverflow.com/a/52144237
tagged with: class
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91238299
has comment: http://stackoverflow.com/comment/91238181

http://stackoverflow.com/comment/91276697
type: Comment
type: QuestionComment
has text: @Rose, at this point I think you should be critical of your data and/or models. The code is now working, so this is no longer a coding problem but a data analysis problem :). Try plotting your data and model to do a visual inspection of what could be wrong. These 'nan' are probably caused by evaluating a function such as `asin` or `sqrt` with an illegal argument. Read from [here](https://symfit.readthedocs.io/en/latest/tutorial.html#evaluating-the-model) to the end of that page on how to evaluate and plot `symfit` models.
score: 0
comment on: http://stackoverflow.com/q/52146955

http://stackoverflow.com/a/52244724
accepted answer of: http://stackoverflow.com/q/52240633
type: Answer
answers question: http://stackoverflow.com/q/52240633
score: 19
downvote count: 0
type: AcceptedAnswer
has body: Based on your values, here is one solution using plt.text import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) values = [7, 57, 121, 192, 123, 240, 546] labels = ['1950s', '1960s', '1970s', '1980s', '1990s', '2000s', '2010s'] plt.plot(range(len(labels)), values, 'bo') # Plotting data plt.xticks(range(len(labels)), labels) # Redefining x-axis labels for i, v in enumerate(values): ax.text(i, v+25, "%d" %v, ha="center") plt.ylim(-10, 595) plt.show() Output
upvote count: 19
has comment: http://stackoverflow.com/comment/91439128

http://stackoverflow.com/comment/91430103
comment on: http://stackoverflow.com/q/52240646
has text: @jasonharper I understand that much. The confusion is in why it would overwrite the attributes of other instances
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52201028
has body: Python newbie question. I run the following example: class Polygon: def __init__(polygonType): print('Polygon is a ', polygonType) class Triangle(Polygon): def __init__(self): Polygon.__init__('triangle') print(issubclass(Triangle, Polygon)) print(issubclass(Triangle, list)) print(issubclass(Triangle, (list, Polygon))) print(issubclass(Polygon, (list, Polygon))) This is the output: True False True True Why do the two last print statements yield true? Does it have any practical meaning or only theoretical?
has comment: http://stackoverflow.com/comment/91351120
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91351137
answer count: 0
upvote count: 2
score: 1
has title: Python inheritance example
downvote count: 1
has comment: http://stackoverflow.com/comment/91351701
type: Question
has comment: http://stackoverflow.com/comment/91351052
tagged with: inheritance
has comment: http://stackoverflow.com/comment/91351202
has comment: http://stackoverflow.com/comment/91351334
favorite count: 0
has comment: http://stackoverflow.com/comment/91351286

http://stackoverflow.com/comment/91257956
type: QuestionComment
score: 2
has text: Try: `n = str(n)` instead. Note that `series_sum(5)` has no effect as it does not return, output, or mutate anything.
comment on: http://stackoverflow.com/q/52153899
type: Comment

python-keyring
type: Tag
tag name: python-keyring
tags question: http://stackoverflow.com/q/52264818

http://stackoverflow.com/comment/91441179
has text: You can also use formatted string literals in Python 3.6+, e.g. `f'{8.5:.9g}'`. +1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52246545
score: 2

http://stackoverflow.com/q/52247221
has comment: http://stackoverflow.com/comment/91442402
has body: I am trying to import data from a csv file and convert the data to an int. but i am receiving this error: year = int(i[0]) ValueError: invalid literal for int() with base 10: '' I also get this error for converting month and day to an int with open('tide.csv', 'w') as tides_data: tides = csv.writer(tides_data, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) with open('test_csv.csv', 'r') as data_file: data = csv.reader(data_file, delimiter=',') for i in data: year = 2018 #the program has a bug here. please change so it can bring in the year from the csv file month = int(i[1]) day = int(i[2]) time = str(i[3])
has comment: http://stackoverflow.com/comment/91442474
has comment: http://stackoverflow.com/comment/91442420
has comment: http://stackoverflow.com/comment/91442454
answer count: 0
has comment: http://stackoverflow.com/comment/91442397
has comment: http://stackoverflow.com/comment/91442408
type: Question
has comment: http://stackoverflow.com/comment/91442441
has comment: http://stackoverflow.com/comment/91442535
tagged with: type-conversion
has comment: http://stackoverflow.com/comment/91442736
score: 0
has comment: http://stackoverflow.com/comment/91442495
has comment: http://stackoverflow.com/comment/91442658
has comment: http://stackoverflow.com/comment/91442386
has title: why am i receiving this python error when importing data from a csv file?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91442787
has comment: http://stackoverflow.com/comment/91442581
tagged with: python

http://stackoverflow.com/q/52252779
has title: Find a string in file with combinaison of loop For and If
tagged with: loops
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52252854
tagged with: if-statement
has comment: http://stackoverflow.com/comment/91452925
score: 0
has body: I'm beginner on python, and I can't managed to get my loop and if condition working on this case as below. I'm searching for a server passed in argument (host), If founded it return, the string in column 16th, if not : not founded. In my code it returns not founded in the loop, I just want only one time. I also tried with one break without luck. Thanks for your help. with open('file', 'r') as f: for line in f: parts = line.split('`') if host in line: model = parts[16] print("You have selected this server model: " + host + " " + model) else: print("not founded")
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91452918
favorite count: 0
has comment: http://stackoverflow.com/comment/91452947
has comment: http://stackoverflow.com/comment/91452980
tagged with: python
accepted answer: http://stackoverflow.com/a/52252854
type: AnsweredQuestion

http://stackoverflow.com/a/52219264
type: Answer
has comment: http://stackoverflow.com/comment/91394776
has body: I assume that the PDF has more than one page? This should work: from pdftables.pdf_document import PDFDocument from pdftables.pdftables import page_to_tables filepath = ... page_number = ... with open(filepath, 'rb') as file_object: pdf_doc = PDFDocument.from_fileobj(file_object) pdf_page = pdf_doc.get_page(pagenumber) tables = page_to_tables(pdf_page) print(tables) You can iterate over several pages, too: for page_number, page in enumerate(pdf_doc.get_pages()): tables = page_to_tables(page) print(tables)
score: 2
has comment: http://stackoverflow.com/comment/91440613
answers question: http://stackoverflow.com/q/52219133
has comment: http://stackoverflow.com/comment/91391307
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/91265724
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52135390
has text: Use Anaconda Prompt?

http://stackoverflow.com/a/52130748
has comment: http://stackoverflow.com/comment/91212256
score: 5
type: AcceptedAnswer
has body: requests.get gives a 'Response' object rather than a dict. Only the latter has an items method for iteration. You can use the json library to retrieve a regular Python dictionary: import json import requests names = requests.get("http://some.api") d = json.loads(names.text) Then note you have a dictionary with one key where the value is a list of dictionaries. So you need to access d['mynames'] to retrieve in-scope dictionaries via a list comprehension. filtered_names = [el for el in d['mynames'] if 'Pitbull' in el['name']] # [{'id': 93, 'name': 'Pitbull'}]
accepted answer of: http://stackoverflow.com/q/52130720
answers question: http://stackoverflow.com/q/52130720
type: Answer
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/91212190
has comment: http://stackoverflow.com/comment/91211991

http://stackoverflow.com/a/60209517
has body: Debian 10. crontab RUN pyautogui script to GNOME Screen import os os.environ['DISPLAY'] = ':0' os.environ['XAUTHORITY']='/run/user/1000/gdm/Xauthority' import pyautogui print(pyautogui.position())
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52244164
has comment: http://stackoverflow.com/comment/122077807
type: Answer
upvote count: 1

http://stackoverflow.com/comment/91413734
type: AnswerComment
comment on: http://stackoverflow.com/a/52219628
score: 0
type: Comment
has text: I use ModelForm

http://stackoverflow.com/q/52221286
has title: What to slice rows after fifth row
has body: Hey want to slice rows to alternate rows(every second row), starting at fifth row, but I want to have first five rows unsliced. I tried with df1 = df.iloc[5::2, :] but it deletes first five rows as well. Do you guys have an simple command that could work like that or I need to make two different excels and then combine them together. Thank you!
has comment: http://stackoverflow.com/comment/91391067
downvote count: 0
has answer: http://stackoverflow.com/a/52221562
has answer: http://stackoverflow.com/a/52221408
accepted answer: http://stackoverflow.com/a/52221408
type: AnsweredQuestion
score: 1
tagged with: dataframe
type: Question
upvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/52221388
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/52221388
tagged with: python

http://stackoverflow.com/a/52240109
score: 0
answers question: http://stackoverflow.com/q/52239956
type: Answer
has body: Here is an example: list_1 = ['x1 y1','x1 y2','x1 y3','x1 y4','x2 b1','x2 b2','x2 b3','x2 b4'] x1 = [] x2 = [] dict_1 = {} for i in list_1: if 'x1' in i: j = i.split() x1.append(j[1]) if 'x2' in i: j = i.split() x2.append(j[1]) dict_1 = {'x1': x1, 'x2': x2} print(dict_1) Output: {'x1': ['y1', 'y2', 'y3', 'y4'], 'x2': ['b1', 'b2', 'b3', 'b4']} We create empty lists for everything that belongs to x1 and x2. We also create and empty dict that we will add values to later. WE then run a for loop that states that if a value has x1 within it, we will split the value and index one will be appended to x1. If 'x2' is in the value then index one will be appended to x2. We then create add values to the dictionary with x1 or x2 being the keys, and the list that corresponds with either x1 or x2 being the value. The output is what you are seeking. Also of note, are you using numpy? Or are you are Java developer? In Python what you are looking for as output is technically a "nested list" with a dictionary being the main data structure. Not an array. In java, this would be an array within a map. I was just curious because you sound like a Java developer which I find interesting because which language you primarily write in can impact verbiage I guess.

http://stackoverflow.com/comment/116094890
type: Comment
comment on: http://stackoverflow.com/a/52127513
type: AnswerComment
score: 0
has text: I was getting same error as above, because my port was blank ''.

http://stackoverflow.com/q/52136168
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52136821
has answer: http://stackoverflow.com/a/52136821
has body: I'm trying to find a way to quantify how often I'm distracted. However, flawed the following technique is, it is at least better than nothing. I've decided I'm going to try to count the keystrokes and mouse clicks in my computer. I can listen to my mac keyboard when I run the following python code provided I do so from Mac Terminal and use sudo: import keyboard def count_key_strokes(): while True: b = keyboard.read_key() print (b) However, the keyboard module is not written for mouse clicks on a Mac, so I have to use a different module, which is the following: from pynput import mouse def on_click(x, y, button, pressed): if not pressed: return False def count_mouse(): d = 0 while True: with mouse.Listener( on_click=on_click, ) as listener: listener.join() d += 1 print (d) In order to run the two programs simultaneously I have to thread them together like so: import threading ''code here threading.Thread(target=count_mouse).start() threading.Thread(target=count_key_strokes).start() However when I run that code from Terminal using: sudo python3 count_keystrokes.py I get the following error message and do not understand why: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keyboard/__init__.py", line 292, in listen _os_keyboard.listen(self.direct_callback) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keyboard/_darwinkeyboard.py", line 431, in listen KeyEventListener(callback).run() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keyboard/_darwinkeyboard.py", line 366, in run loopsource = Quartz.CFMachPortCreateRunLoopSource(None, self.tap, 0) File "/Library/Fram…
accepted answer: http://stackoverflow.com/a/52228934
answer count: 2
score: 2
has comment: http://stackoverflow.com/comment/91223029
downvote count: 0
has comment: http://stackoverflow.com/comment/91222123
favorite count: 0
has comment: http://stackoverflow.com/comment/91222245
tagged with: python
has comment: http://stackoverflow.com/comment/91222655
tagged with: macos
upvote count: 2
has answer: http://stackoverflow.com/a/52228934
type: Question
has title: Listening to keyboard on Mac using Python and encountering AttributeError: CFMachPortCreateRunLoopSource

http://stackoverflow.com/q/52145048
tagged with: pycharm
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91273897
has title: Pycharm pytest environmental variable in configuration tab is getting reset always
has comment: http://stackoverflow.com/comment/91271847
type: Question
tagged with: pytest
score: 0
tagged with: ide
has body: For pytest module in Pycharm IDE, to print attributes or execute methods interactively in Debugger console, I learnt that I have to set "-s" for Additional Arguments under Edit Configurations tab. However, I was not able to default this "-s" flag to be applicable for all the test cases. I had to set "-s" flag for each test case individually whenever I run. Later I learnt that I could use JB_DISABLE_BUFFERING=-s Environmental variable. However this Environmental variable is getting reset/cleared after a restart. Is there any way wherein I could preserve this setting forever?
has comment: http://stackoverflow.com/comment/91281379
tagged with: python
tagged with: python-3.x

http://stackoverflow.com/a/52262956
downvote count: 0
answers question: http://stackoverflow.com/q/52262916
accepted answer of: http://stackoverflow.com/q/52262916
has comment: http://stackoverflow.com/comment/91479011
type: AcceptedAnswer
score: 4
has comment: http://stackoverflow.com/comment/91474157
type: Answer
upvote count: 4
has body: http.client is the python 3 standard library (batteries included) way to make rest calls Requests is a popular third party library (http://docs.python-requests.org/en/master/) that is commonly used to make calls. You'll need to install it in order to use it (http://docs.python-requests.org/en/master/user/install/)

http://stackoverflow.com/q/52171982
has body: With PEP 563, from __future__ import annotations changes type annotations so that they are evaluated lazily, which provides a bunch of benefits like forward references. However, this seems to play badly with other features, like dataclasses. For example, I have some code that inspects the type parameters of a class's __init__ method. (The real use case is to provide a default serializer for the class, but that is not important here.) from dataclasses import dataclass from typing import get_type_hints class Foo: pass @dataclass class Bar: foo: Foo print(get_type_hints(Bar.__init__)) In Python 3.6 and 3.7, this does what is expected; it prints {'foo': <class '__main__.Foo'>, 'return': <class 'NoneType'>}. However, if in Python 3.7, I add from __future__ import annotations, then this fails with an error: NameError: name 'Foo' is not defined I think I understand why this is happening. The __init__ method is defined in dataclasses which does not have the Foo object in its environment, and the Foo annotation is being passed to dataclass and attached to __init__ as the string "Foo" rather than as the original object Foo, but get_type_hints for the new annotations only does a name lookup in the module where __init__ is defined not where the annotation is defined. I feel like I must be doing something wrong. I am surprised that these two new features play so poorly together. Is there a proper way to inspect the type hints of of an __init__ method so that it works on dataclasses like it does on normal classes?
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/55937472
tagged with: python-typing
has title: New annotations break inspection of dataclasses
tagged with: python-dataclasses
favorite count: 0
upvote count: 8
has answer: http://stackoverflow.com/a/52969340
has comment: http://stackoverflow.com/comment/91295139
tagged with: python
score: 8
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91295329
type: Question
accepted answer: http://stackoverflow.com/a/52969340

http://stackoverflow.com/q/52149451
type: UnansweredQuestion
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52149605
has body: I have a command in python: os.system('echo {{"value": {0:0.0f}}} | /usr/bin/cmd -parameters'.format(value)) the thing is that I receive value instead of "value". I would like to have "value" in shell. I've tried with triple double quotes, with slashes and json.dumps. Nothing helped, still value instead of "value". Could you help me?
score: 1
has comment: http://stackoverflow.com/comment/91249067
answer count: 2
has comment: http://stackoverflow.com/comment/91249310
favorite count: 0
has answer: http://stackoverflow.com/a/52149642
has comment: http://stackoverflow.com/comment/91248976
tagged with: python
has title: Python double quotes in os.system
has comment: http://stackoverflow.com/comment/91248975
upvote count: 2

http://stackoverflow.com/a/52154033
has body: You can use ravel: x = np.array([[1, 3, 5],[2, 4, 6]]) res = x.ravel('F') # or x.T.ravel() # array([1, 2, 3, 4, 5, 6])
type: Answer
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52153991
answers question: http://stackoverflow.com/q/52153991
type: AcceptedAnswer
score: 4

http://stackoverflow.com/q/52180440
has body: So, if I want a numpy array [0,1,2,3,4,5,6] (or any other vector with, say 7 elements) which has the dimension (7,1) and not (7,), is there anyway to do that when I create it, instead of writing t=np.expand_dims(np.array(range(7)),axis=1) ?
has comment: http://stackoverflow.com/comment/91310793
has comment: http://stackoverflow.com/comment/91311076
linked to: http://stackoverflow.com/q/5954603
type: UnansweredQuestion
has title: Initialize numpy array in two dimensions
duplicate of: http://stackoverflow.com/q/5954603
has answer: http://stackoverflow.com/a/52181457
type: Question
tagged with: dimension
has comment: http://stackoverflow.com/comment/91318461
has comment: http://stackoverflow.com/comment/91317991
has comment: http://stackoverflow.com/comment/91311140
tagged with: numpy
answer count: 2
tagged with: arrays
has comment: http://stackoverflow.com/comment/91311698
score: 0
has answer: http://stackoverflow.com/a/52181246
tagged with: python

http://stackoverflow.com/comment/91221034
type: Comment
comment on: http://stackoverflow.com/a/52128968
has text: Hi sers, I tried this but still could not pull the second phone number onwards. However your code solved teh problem of why am i getting the Try: and Except: outputs. I have added in the website in case i am missing out some info that i did not provide! http://www.timesbusinessdirectory.com/category/1000/sme-1000-ranked-companies-2017?classid=sme1000&mid=1913'
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91326664
has text: As on picture: https://imgur.com/a/eMsmIB3 All messages posted by one bot.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52169896

http://stackoverflow.com/q/52248562
has comment: http://stackoverflow.com/comment/91464006
score: 0
has body: I'm following the new tutorial from https://wagtail.io/blog/wagtail-heroku-2017/ But I have trouble with collectstatic and the white noise package remote: Compressing source files... done. remote: Building source: remote: remote: -----&gt; Python app detected remote: -----&gt; Installing requirements with pip remote: remote: -----&gt; $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 10, in &lt;module&gt; remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, in collect remote: for path, storage in finder.list(self.ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 125, in list remote: for path in utils.get_files(storage, ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 28, in get_files remote: directories, files = storage.listdir(location) remote: File "/app/.heroku/python/lib/python3.6/…
has comment: http://stackoverflow.com/comment/91460280
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91477719
answer count: 0
has comment: http://stackoverflow.com/comment/91445301
has title: Wagtail - Heroku - collectstatic and WhiteNoise during deploying
type: Question
tagged with: heroku
tagged with: wagtail
has comment: http://stackoverflow.com/comment/91461614

http://stackoverflow.com/comment/91434986
comment on: http://stackoverflow.com/q/52243121
has text: where do you initialize root = tkinter.Tk()? Also the last line in main should be root.mainloop()... as I see it a is not an object of tkinter.Tk()
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52185973
tagged with: python
has comment: http://stackoverflow.com/comment/91322764
has comment: http://stackoverflow.com/comment/91322584
score: 2
has comment: http://stackoverflow.com/comment/91322348
downvote count: 0
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91322407
has answer: http://stackoverflow.com/a/52186477
has body: I'm looking for an easy way to implement a 2D Convolution of 2 n-dim arrays without any padding in python. I found the function scipy.ndimage.convolve(input, weights, output=None, mode='constant', cval=0.0, origin=0) which seems to do exactly what i want, but just a little bit to much. The function provides several options for padding in the border region, but as far as i know, NO option WITHOUT any padding, which makes me really wondering. Of course it would be possible to just cut of the borders, but this seems a very unattractive solution to me and since i keep an eye on the performance of my program, it wouldn't prevent the unnecessary computations edit: i'm sorry, but i confused correlation and convolution. What I actually meant was CORRELATION.
upvote count: 2
has comment: http://stackoverflow.com/comment/91322879
has title: python convolution without padding
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: convolution
has comment: http://stackoverflow.com/comment/91323232

http://stackoverflow.com/comment/93043405
comment on: http://stackoverflow.com/q/52222515
score: 0
has text: @SubhashDesai Welcome to Stackoverflow, in future you should include the code as well
type: Comment
type: QuestionComment

amazon-web-services
tags question: http://stackoverflow.com/q/52248614
tags question: http://stackoverflow.com/q/52141780
tags question: http://stackoverflow.com/q/52180758
tags question: http://stackoverflow.com/q/52123401
tags question: http://stackoverflow.com/q/52178872
tags question: http://stackoverflow.com/q/52168279
tags question: http://stackoverflow.com/q/52252580
tags question: http://stackoverflow.com/q/52218089
tags question: http://stackoverflow.com/q/52223496
tags question: http://stackoverflow.com/q/52146908
tags question: http://stackoverflow.com/q/52196780
tags question: http://stackoverflow.com/q/52268328
type: Tag
tags question: http://stackoverflow.com/q/52228704
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/52178711
tags question: http://stackoverflow.com/q/52218533
tags question: http://stackoverflow.com/q/52166293
tags question: http://stackoverflow.com/q/52161964
tags question: http://stackoverflow.com/q/52129442
tags question: http://stackoverflow.com/q/52130281
tags question: http://stackoverflow.com/q/52133692
tags question: http://stackoverflow.com/q/52139535
tags question: http://stackoverflow.com/q/52146685
tags question: http://stackoverflow.com/q/52119306
tags question: http://stackoverflow.com/q/52189623
tags question: http://stackoverflow.com/q/52253605
tags question: http://stackoverflow.com/q/52171712
tags question: http://stackoverflow.com/q/52121334
tags question: http://stackoverflow.com/q/52226062
tags question: http://stackoverflow.com/q/52205712
tags question: http://stackoverflow.com/q/52122242

http://stackoverflow.com/comment/91429581
comment on: http://stackoverflow.com/q/52240398
score: 0
has text: Or use `pdb; pdb.set_trace()` to enter the debugger (similar to gdb).
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52268818
type: Answer
has body: you can group the dataframe by date and cummulative sumo of column will workk df.index = pd.to_datetime(df.index) df.groupby(df.index.date)['volume'].cumsum()
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52268779
upvote count: 2

http://stackoverflow.com/q/52245908
has title: Scrapy running consecutively not concurrently
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has body: I have a spider that takes a list of addresses and requests information from a single page sending an address and some session information as a scrapy.FormRequest. However, the scraper seems to be running them consecutively. I can tell this because if you search 10 addresses it takes 17 seconds and if you search 20 addresses it takes double the time at about 32 seconds. Since the biggest delay is just waiting for the response, and there's no complex parsing going on, if it was running concurrently, it should just take a little longer correct? I've tried making sure concurrent requests was set high enough in the settings.py. I have added dont_filter = true to the form request. But still can't seem to get it to work. It should also be noted that the scraper is working in the sense that it does pull the information requested. settings.py CONCURRENT_REQUESTS_PER_DOMAIN = 20 CONCURRENT_REQUESTS_PER_IP = 20 CONCURRENT_REQUESTS = 20 main.py class WaterSpider(scrapy.Spider): name = "water" def __init__(self,stats): dispatcher.connect(self.spider_closed, signals.spider_closed) self.stats = stats @classmethod def from_crawler(cls, crawler): return cls(crawler.stats) def start_requests(self): #Pull saved session ID Info with open('items.json') as f: sessioninfo = json.load(f) sessioninfo = sessioninfo[0] url = 'http://cityservices.baltimorecity.gov/water/' #Take the cookies from what was scraped above and add them to the new cookies to be passed. cookies = { 'popup':'seen', 'ASP.NET_SessionId': sessioninfo['sessioncookie'] } #Same with the different view states. post_params = { '__VIEWSTATE': sessioninfo['VIEWSTATE'], '__VIEWSTATEGENERATOR': sessioninfo['VIEWSTATEGENERATOR'], '__EVENTVALIDATION': sessioninfo['EVENTVALIDATION'], 'ctl00$ctl00$rootMasterContent$LocalContentPlaceHolder$btnGetInfoServiceAddress': 'Get Info' } #Run through all the addresses in our csv to start scraping. with open('Addresses.csv', 'r') as csvfile: addresses = csv.reader(csvfile) for x,row in enumerat…
tagged with: web-scraping
tagged with: scrapy
type: Question
downvote count: 0

http://stackoverflow.com/q/52248819
upvote count: 1
tagged with: python
has title: Nuitka error when compiling PyQt5 script "implicit module sip" error
tagged with: nuitka
has answer: http://stackoverflow.com/a/52249202
tagged with: pyqt5
has body: I'm trying to compile a Python script using Nuitka: nuitka --recurse-all main.py which then returns the error: Nuitka:WARNING:C:\Users\Tearzz\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\__init__.py:99: Cannot find 'cryptography' in package 'requests' as absolute import (tried cryptography). Nuitka:WARNING:C:\Users\Tearzz\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\compat.py:41: Cannot find 'urlparse' in package 'requests' as absolute import (tried urlparse). Nuitka:WARNING:C:\Users\Tearzz\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\compat.py:42: Cannot find 'urllib2' in package 'requests' as absolute import (tried urllib2). Nuitka:WARNING:C:\Users\Tearzz\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\compat.py:43: Cannot find 'cookielib' in package 'requests' as absolute import (tried cookielib). Nuitka:WARNING:C:\Users\Tearzz\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\compat.py:44: Cannot find 'Cookie' in package 'requests' as absolute import (tried Cookie). Nuitka:WARNING:C:\Users\Tearzz\AppData\Local\Programs\Python\Python36\lib\site-packages\urllib3\packages\ordered_dict.py:11: Cannot find '_abcoll' in package 'urllib3.packages' as absolute import (tried _abcoll). Nuitka:WARNING:C:\Users\Tearzz\AppData\Local\Programs\Python\Python36\lib\site-packages\urllib3\packages\ssl_match_hostname\__init__.py:13: Cannot find 'backports.ssl_match_hostname' in package 'urllib3.packages.ssl_match_hostname' as absolute import (tried backports.ssl_match_hostname). Nuitka:WARNING:C:\Users\Tearzz\AppData\Local\Programs\Python\Python36\lib\site-packages\backports:1: Cannot find '_frozen_importlib_external' in package 'backports' as absolute import (tried _frozen_importlib_external). Nuitka:WARNING:C:\Users\Tearzz\AppData\Local\Programs\Python\Python36\lib\site-packages\urllib3\contrib\socks.py:27: Cannot find 'socks' in package 'urllib3.contrib' as absolute import (tried sock…
accepted answer: http://stackoverflow.com/a/52249202
answer count: 2
tagged with: pyqt
type: AnsweredQuestion
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/52264135
favorite count: 0
has answer: http://stackoverflow.com/a/52264135
tagged with: python-3.x
type: Question

http://stackoverflow.com/comment/91428001
score: 0
has text: i just tried this on my phone and it looks like it will work, you will need some more logic... best of luck import time t = time.localtime() if t.tm_hour >= 22: print("its late") else: print("its not that late")
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52239441

http://stackoverflow.com/comment/91374361
has text: [BeautifulSoup - combine consecutive tags](https://stackoverflow.com/questions/50026264/beautifulsoup-combine-consecutive-tags) looks like exactly what you want; in what way is that insufficient?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52211795

http://stackoverflow.com/a/71830392
has comment: http://stackoverflow.com/comment/130061605
answers question: http://stackoverflow.com/q/52197918
type: Answer
upvote count: 0
downvote count: 1
has body: import numpy as np import cv2 img = cv2.imread('in1.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) (_, thresh) = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU) thresh = ~thresh points = np.column_stack(np.where(thresh.transpose() &gt; 0)) hull1 = cv2.convexHull(points) result1 = cv2.polylines(img.copy(), [hull1], True, (0,0,255), 2) cv2.imshow('result1', result1) points2 = np.fliplr(np.transpose(np.nonzero(thresh))) approx = cv2.convexHull(points2) result2 = cv2.polylines(img.copy(), [approx], True, (255,255,0), 2) cv2.imshow('result2', result2) (contours, _) = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) points3 = [pt[0] for ctr in contours for pt in ctr] points3 = np.array(points3).reshape((-1,1,2)).astype(np.int32) hull3 = cv2.convexHull(points3) result3 = cv2.drawContours(img.copy(), [hull3], -1, (0,255,0), 1, cv2.LINE_AA) cv2.imshow('result3', result3) points4 = list(set(zip(*np.where(img &gt;= 128)[1::-1]))) points4 = np.array(points4).reshape((-1,1,2)).astype(np.int32) hull4 = cv2.convexHull(points4) result4 = cv2.drawContours(img.copy(), [hull4], -1, (0,255,255), 1, cv2.LINE_AA) cv2.imshow('result4', result4) result = np.hstack([result1, result2, result3, result4]) cv2.imwrite('result.jpg', result)
score: -1

http://stackoverflow.com/q/52247001
has comment: http://stackoverflow.com/comment/91442927
tagged with: stereo-3d
has comment: http://stackoverflow.com/comment/91444289
favorite count: 0
upvote count: 2
has body: I have recently bought a stereo camera through Amazon and I want to use it for depth mapping. The problem is that the output that I get from the camera is in the form of a single video with the output of both the cameras. What I want is two seprate outputs from the single usb port if it is possible.I can use cropping but I dont want to use that because i am trying to reduce the processing time and I want the outputs sepratley. The obove image was generated from the following code import numpy as np import cv2 cam = cv2. VideoCapture(1) cam.set(cv2.CAP_PROP_FPS, 120) cam.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 720) while(1): s,orignal = cam.read() cv2.imshow('original',orignal) if cv2.waitKey(1) &amp; 0xFF == ord('w'): break cam.release() cv2.destroyAllWindows() I have also tried other techniques such as: import numpy as np import cv2 left = cv2.VideoCapture(1) right = cv2.VideoCapture(2) left.set(cv2.CAP_PROP_FRAME_WIDTH, 720) left.set(cv2.CAP_PROP_FRAME_HEIGHT, 720) right.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) right.set(cv2.CAP_PROP_FRAME_HEIGHT, 720) left.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*"MJPG")) right.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*"MJPG")) # Grab both frames first, then retrieve to minimize latency between cameras while(True): _, leftFrame = left.retrieve() leftWidth, leftHeight = leftFrame.shape[:2] _, rightFrame = right.retrieve() rightWidth, rightHeight = rightFrame.shape[:2] # TODO: Calibrate the cameras and correct the images cv2.imshow('left', leftFrame) cv2.imshow('right', rightFrame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break left.release() right.release() cv2.destroyAllWindows() but they are not recognising the 3rd camera any help would be nice. My openCV version is 3.4 P.S If anyone can present a soloution in c++ it would also work for me
accepted answer: http://stackoverflow.com/a/52248579
tagged with: python
has comment: http://stackoverflow.com/comment/91444508
tagged with: c++
tagged with: opencv
type: AnsweredQuestion
score: 1
has title: Video capture using Opencv through single port multi-head (stereo) usb camera giving single output
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91443291
answer count: 1
has answer: http://stackoverflow.com/a/52248579

http://stackoverflow.com/a/52135634
answers question: http://stackoverflow.com/q/52135580
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52135580
has body: You can subtract two datetime objects. The result is a datetime.timedelta object: started = datetime.datetime.now() str = "20 12 01 01 2019" time = datetime.datetime.strptime(str, "%M %H %d %m %Y") diff = time - started print(str(diff)) print(diff.total_seconds()) This is the output: 121 days, 0:52:12.768755 10457532.768755 Based on your comment: datetime.datetime.now() + datetime.timedelta(minutes=60) creates a datetime.datetime object shifting now by one hour. This is a simpler approach: time.time() measures seconds (as float) since 1.1.1970. So if you want to do some work for 0.1 second you can write: import time started = time.time() while time.time() &lt; started + 0.1: print("do some work") To parse user input to extract the required seconds using datetime.datetime.strptime only works if your user follows the specified format. Else you might better implement your own parser for this.
has comment: http://stackoverflow.com/comment/91221422
type: Answer
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/91202140
has text: Using a `while` loop for this task looks perfectly reasonable to me. So why do you want to use a `for` loop?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52125671

http://stackoverflow.com/comment/91369665
type: Comment
has text: This may prevent OP's `code.mainloop()` from executing
score: 1
comment on: http://stackoverflow.com/a/52210095
type: AnswerComment

http://stackoverflow.com/comment/91569948
comment on: http://stackoverflow.com/a/52310422
score: 0
type: AnswerComment
has text: Thank you for answering. It does not solve the problem as the sizes of the batches will be different while training and predicting. So, the size of the internal state of the RNN will be serialized with a given size, then a size mismatch will happen when reloading. That is why I try to filter out the this 'H' variable when reloading the checkpoint. It would initialized with the zero_state based on the input batch size, and not overwritten by the checkpoint loading.
type: Comment

http://stackoverflow.com/q/52160912
tagged with: django
has answer: http://stackoverflow.com/a/52161167
tagged with: python
accepted answer: http://stackoverflow.com/a/52161167
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/91272066
type: Question
has title: Filtering object values in django
score: -1
answer count: 1
downvote count: 1
favorite count: 0
has body: I have below code in my signals.py : student.detailinfo_set.all().filter(inf="204X1001") student and detailinfo are two models in models.py and they have many-to-many relation in between. When I print student.detailinfo_set.all().filter(inf="204X1001") to a file from signals.py, I get below output: &lt;DetailInfo: 700101 - Jack Marcher/2018-09-19/Trans X101 / 204X1001 / Pro/Y2&gt; &lt;DetailInfo: 700101 - Jack Marcher/2018-09-21/Trans X1 / 204X22 / Pro/Y2&gt; &lt;DetailInfo: 700101 - Jack Marcher/2018-09-11/Trans X102 / 204X1001 / Pro/Y2&gt; &lt;DetailInfo: 700101 - Jack Marcher/2018-09-10/Trans X1 / 204X22 / Pro/Y2&gt; I just want to filter 4th columns of each row which are "204X1001", so that it will print just 2 lines to the file. Solved by Daniil Mashkin's answer below: student.detailinfo_set.all().filter(inf="204X1001") usage was wrong in my code. The correct usage is student.detailinfo_set.filter(inf="204X1001")

http://stackoverflow.com/comment/91364726
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52207661
type: Comment
has text: I wish I could accept both answers, the other came 5 seconds earlier!

http://stackoverflow.com/q/52132970
has title: pandas: How to plot the pie diagram for the movie counts versus genre of IMDB movies in pandas?
type: Question
score: 5
upvote count: 5
has answer: http://stackoverflow.com/a/52133062
answer count: 2
tagged with: pandas
has body: I have the following dataset: import pandas as pd import numpy as np %matplotlib inline df = pd.DataFrame({'movie' : ['A', 'B','C','D'], 'genres': ['Science Fiction|Romance|Family', 'Action|Romance', 'Family|Drama','Mystery|Science Fiction|Drama']}, index=range(4)) df My attempt # Parse unique genre from all the movies gen = [] for g in df['genres']: gg = g.split('|') gen = gen + gg gen = list(set(gen)) print(gen) df['genres'].value_counts().plot(kind='pie') I got this image: But I would like to pie chart for each separate genres. How we get the genres for number count of movies for each unique genres?
accepted answer: http://stackoverflow.com/a/52133062
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/52133059
has answer: http://stackoverflow.com/a/52133059
tagged with: imdb
tagged with: python
tagged with: plot
type: AnsweredQuestion
tagged with: matplotlib

deep-learning
tags question: http://stackoverflow.com/q/52115690
tags question: http://stackoverflow.com/q/52264469
tags question: http://stackoverflow.com/q/52213776
tags question: http://stackoverflow.com/q/52201643
tags question: http://stackoverflow.com/q/52155642
tags question: http://stackoverflow.com/q/52138920
tags question: http://stackoverflow.com/q/52250821
tags question: http://stackoverflow.com/q/52252442
tags question: http://stackoverflow.com/q/52178818
tags question: http://stackoverflow.com/q/52170404
tags question: http://stackoverflow.com/q/52121536
tags question: http://stackoverflow.com/q/52172859
tags question: http://stackoverflow.com/q/52199485
tags question: http://stackoverflow.com/q/52136663
tags question: http://stackoverflow.com/q/52158598
tags question: http://stackoverflow.com/q/52241539
tags question: http://stackoverflow.com/q/52204265
tags question: http://stackoverflow.com/q/52236885
tags question: http://stackoverflow.com/q/52172956
tags question: http://stackoverflow.com/q/52134926
tags question: http://stackoverflow.com/q/52197741
tags question: http://stackoverflow.com/q/52241680
tags question: http://stackoverflow.com/q/52180502
tags question: http://stackoverflow.com/q/52231830
tags question: http://stackoverflow.com/q/52217422
tags question: http://stackoverflow.com/q/52184053
tags question: http://stackoverflow.com/q/52201594
tags question: http://stackoverflow.com/q/52251674
tags question: http://stackoverflow.com/q/52187913
tags question: http://stackoverflow.com/q/52260617
tags question: http://stackoverflow.com/q/52267314
tags question: http://stackoverflow.com/q/52264891
tags question: http://stackoverflow.com/q/52122730
tags question: http://stackoverflow.com/q/52159838
tags question: http://stackoverflow.com/q/52130170
tags question: http://stackoverflow.com/q/52261909
tags question: http://stackoverflow.com/q/52147934
tags question: http://stackoverflow.com/q/52205479
tags question: http://stackoverflow.com/q/52224797
tags question: http://stackoverflow.com/q/52237965
tags question: http://stackoverflow.com/q/52130755
tags question: http://stackoverflow.com/q/52148029
tags question: http://stackoverflow.com/q/52166308
tags question: http://stackoverflow.com/q/52231108
type: Tag
tags question: http://stackoverflow.com/q/52188435
tags question: http://stackoverflow.com/q/52178578
tags question: http://stackoverflow.com/q/52233578
tags question: http://stackoverflow.com/q/52242669
tags question: http://stackoverflow.com/q/52159239
tags question: http://stackoverflow.com/q/52176998
tags question: http://stackoverflow.com/q/52201565
tag name: deep-learning
tags question: http://stackoverflow.com/q/52157213
tags question: http://stackoverflow.com/q/52223816
tags question: http://stackoverflow.com/q/52256408
tags question: http://stackoverflow.com/q/52221103
tags question: http://stackoverflow.com/q/52169024

http://stackoverflow.com/comment/91411693
type: AnswerComment
score: 0
type: Comment
has text: Might want to also point out that I am very new to Python. I would go ahead and throw some error handling in there to catch valueEror and typeError. If not you will find people entering strings into you int inputs and breaking your code.
comment on: http://stackoverflow.com/a/52231074

http://stackoverflow.com/a/52196913
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52162720
type: AcceptedAnswer
downvote count: 0
has body: I finally understand the descriptor and property concept through Simeon Franklin's excellent presentation, the following contents can be seen as a summary on his lecture notes. Thanks to him! To understand properties, you first need to understand descriptors, because a property is implemented by a descriptor and python's decorator syntactic sugar. Don't worry, it's not that difficult. What is a descriptor: a descriptor is any object that implements at least one of methods named __get__(), __set__(), and __delete__(). Descriptor can be divided into two categories: A data descriptor implements both __get__() and __set__(). A non-data descriptor implements only __get__(). According to python's HowTo: a descriptor is an object attribute with “binding behavior”, one whose attribute access has been overridden by methods in the descriptor protocol. Then what is the descriptor protocol? Basically speaking, it's just says that when Python interpreter comes across an attribute access like obj.attr，it will search in some order to resolve this .attr , and if this attr is a descriptor attribute, then this descriptor will take some precedence in this specific order and this attribute access will be translated into a method call on this descriptor according to the descriptor protocol, possibly shadowing a namesake instance attribute or class attribute. More concretely, if attr is a data descriptor, then obj.attr will be translated into the calling result of this descriptor's __get__ method; if attr is not a data descriptor and is an instance attribute, this instance attribute will be matched; if attr is not in above, and it is a non-data descriptor, we get the calling result of this non-data descriptor's __get__ method. Full rules on attribute resolution can be found here . Now let's talk about property. If you have looked at Python' descriptor HowTo, you can find a pure Python version implementation of property: class Property(object): "Emulate PyProperty_Type() in Objects/descro…
answers question: http://stackoverflow.com/q/52162720

http://stackoverflow.com/a/52249813
score: 0
has comment: http://stackoverflow.com/comment/91447784
type: Answer
answers question: http://stackoverflow.com/q/52249755
accepted answer of: http://stackoverflow.com/q/52249755
type: AcceptedAnswer
has body: There's nothing wrong with the logic in your code. Since the error is an IndentationError, it must be because you're using inconsistent indentation on that if line. Make sure that the indentation on each line is consistent (using same number of spaces/tabs). Probably there is a space at the beginning of that line that is causing the error.

http://stackoverflow.com/q/52242957
tagged with: browser
upvote count: 1
answer count: 1
has body: I'm often using selenium and I would like to know from browser.Firefox() to browser.close(), how much data i used to load everything. Is this something selenium can measure?
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
downvote count: 0
tagged with: selenium
has answer: http://stackoverflow.com/a/52243042
type: Question
has title: In python, selenium. Is there a way to see the amount of data taken to load a site?
score: 1

http://stackoverflow.com/comment/91347196
type: QuestionComment
has text: The error message says Python 3.6 or higher is required whereas Python 3.5 is available on your machine. Try installing Python 3.6 and then install Bleak-Detector or you can try installing older version of Bleak-Detector/MitProxy that works with Python 3.5.
comment on: http://stackoverflow.com/q/52198283
score: 0
type: Comment

http://stackoverflow.com/a/52133607
score: 1
upvote count: 1
downvote count: 0
type: Answer
has body: Short and simple: df.groupby(['contact_id', 'campaign_type']).size().unstack('type', fill_value=0) Edit: neither short nor simple, see other answer.
answers question: http://stackoverflow.com/q/52133577

http://stackoverflow.com/q/52155194
has answer: http://stackoverflow.com/a/52155391
has comment: http://stackoverflow.com/comment/91260689
type: Question
has comment: http://stackoverflow.com/comment/91260858
has comment: http://stackoverflow.com/comment/91260649
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52155503
has answer: http://stackoverflow.com/a/52155592
has comment: http://stackoverflow.com/comment/91260600
has body: I want to create a function that plots a 2-dimensional system of differential equations, but if I call the function with a parameter like 2*x + 3*y I'll obviously run into an exception because I have not defined x and y at the time of execution. In code, I want to do something like this: import numpy as np import matplotlib.pyplot as plt def streamplot(xdot, ydot, xxrange, yyrange): """Displays the stream plot of a two-dimensional system of equations.""" x, y = np.meshgrid(np.arange(0,xxrange,1),np.arange(0,yyrange,1) plt.streamplot(x, y, xdot, ydot) plt.show() but evidently xdot and ydot will depend on x and y which are not assigned yet. I think it should be possible to catch the exception Python will create when the function is executed and create these variables at that time, but there should be a simpler way of doing this, right?
has title: Is it possible to work with a variable before its creation?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91260779
has comment: http://stackoverflow.com/comment/91260832

http://stackoverflow.com/q/52113219
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52163366
tagged with: python
has title: How do I open several webpages on the same machine, each with their own proxy?
upvote count: 0
has comment: http://stackoverflow.com/comment/91177213
has comment: http://stackoverflow.com/comment/91177233
downvote count: 2
type: Question
has body: I don't really know where to start with this. I need help figuring out how to do this as lightweight as possible. I could rent a server but I would prefer a solution where I don't have to. I am experienced with Python and Javscript. Can these be used? Thanks a lot.
score: -2
tagged with: javascript
tagged with: proxy
linked to: http://stackoverflow.com/q/8287628
answer count: 1
tagged with: web

perceptron
tags question: http://stackoverflow.com/q/52236640
type: Tag
tag name: perceptron

http://stackoverflow.com/a/52131688
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/52120838
score: 2
answers question: http://stackoverflow.com/q/52120838
has body: Imports: import pandas as pd from bokeh.models import ColumnDataSource, HoverTool from bokeh.plotting import figure, show, output_notebook output_notebook() Here's the data as you present it: days = ['2018/1/1', '2018/1/2', '2018/1/3', '2018/1/4', '2018/1/5'] data_a = [10, 34, 23, 14, 58] data_b = [20, 13, 45, 98, 65] data_c = [20, 23, 43, 76, 57] Create DataFrame: df_plot = pd.DataFrame({'A': data_a, 'B': data_b, 'C': data_c}, index=days) A B C 2018/1/1 10 20 20 2018/1/2 34 13 23 2018/1/3 23 45 43 2018/1/4 14 98 76 2018/1/5 58 65 57 However, the index is not a proper datetime format, so create a dates column with the proper format: df_plot['dates'] = pd.to_datetime(df_plot.index, format='%Y/%m/%d') A B C dates 2018/1/1 10 20 20 2018-01-01 2018/1/2 34 13 23 2018-01-02 2018/1/3 23 45 43 2018-01-03 2018/1/4 14 98 76 2018-01-04 2018/1/5 58 65 57 2018-01-05 Now for the plotting: source = ColumnDataSource(df_plot) p = figure(x_axis_type="datetime") p.line('dates', 'A', source=source, color='red') p.line('dates', 'B', source=source, color='blue') p.line('dates', 'C', source=source, color='green') p.add_tools(HoverTool(tooltips=[("A", "@A"), ("B", "@B"), ("C", "@C")])) show(p) This is just a png, the actual output will have hoover tools.

http://stackoverflow.com/a/52157531
upvote count: 1
has comment: http://stackoverflow.com/comment/91266549
answers question: http://stackoverflow.com/q/52157380
has body: The first one is a list comprehension to make it faster take out the brackets, example: %timeit sum(i for i in range(1000000) if i % 3 == 0 or i % 5 == 0) Output: 10 loops, best of 3: 47.5 ms per loop But the second one can be made faster too, without using list outside: x=range(0,1000000,3) z=range(0,1000000,5) y=range(0,1000000,15) %timeit sum(x)+sum(z)-sum(y) Output: 1 loop, best of 3: 287 ms per loop But same thing you will still be thinking why is it still faster? Because you're still iterating trough the range in the second example The other one is just summing generators To make it faster do: print(1000000//3 + 1000000//5 - 1000000//15) %timeit 1000000//3 + 1000000//5 - 1000000//15 Time taken: 10000000 loops, best of 3: 31.3 ns per loop
score: 1
has comment: http://stackoverflow.com/comment/91267937
has comment: http://stackoverflow.com/comment/91302469
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52157380
type: Answer

http://stackoverflow.com/comment/91335567
score: 0
comment on: http://stackoverflow.com/q/52192830
type: Comment
type: QuestionComment
has text: @Aran-Fey Yes, that's what i need

http://stackoverflow.com/a/52226526
downvote count: 0
has body: As mentioned in this answer you can use python-dateutil for this: &gt;&gt;&gt; from dateutil import parser &gt;&gt;&gt; datetime_obj = parser.parse("Sun Aug 19 16:24:31 PDT 2018") datetime.datetime(2018, 8, 19, 16, 24, 31) Standard datetime module behaves very strangely with parsing timezones, as I see reading this answer in question related to similar problem.
type: Answer
answers question: http://stackoverflow.com/q/52225765
upvote count: 1
score: 1

http://stackoverflow.com/comment/91258624
type: QuestionComment
comment on: http://stackoverflow.com/q/52153912
type: Comment
has text: Hello, the code works as you say, I get right results, but in the future I would like to add event like keystroke, which do not stop pinging, but returns to the initial setup menu (list of questions in the beggining of script) to add or remove some ips. I was advised to do the following, please see next message.
score: 0

http://stackoverflow.com/a/52165170
has comment: http://stackoverflow.com/comment/91289078
upvote count: 2
has body: I would probably be optimistic and just try the request. If it fails, then re-authenticate and then retry the request: def getdata(self, page, hed, data, ...): ... responsedata = requests.get(url, data=data, headers=hed, verify=False) if responsedata.status_code == 401: hed['Authorization'] = 'Bearer ' + my_lib.kAuth(kauth_data).json()['access_token'] responsedata = requests.get(url, data=data, headers=hed, verify=False) return ... Or, as Klaus D. suggests, check current time and refresh the token if expires_in has been reached.
has comment: http://stackoverflow.com/comment/91289031
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91346384
answers question: http://stackoverflow.com/q/52164956
has comment: http://stackoverflow.com/comment/91280168
has comment: http://stackoverflow.com/comment/91290005
downvote count: 0

http://stackoverflow.com/q/52198434
has body: I get this error and I don't understand why. List index out of range, but the item exists. 1 [u'http://(ip1):(port1)', u'http://(ip2):(port2)'] Exception in thread Thread-11: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 763, in run self.__target(*self.__args, **self.__kwargs) File "(path).py", line 57, in match_fetcher self.fetch_match(match) File "(path).py", line 65, in fetch_match response = self.http_get(url) File "(path).py", line 75, in http_get proxy = self.proxies.get_proxy() File "(path).py", line 51, in get_proxy proxy = self.proxies[self.index] IndexError: list index out of range The code: def get_proxy(self): if self.index &gt;= len(self.proxies): self.index = 0 print self.index, self.proxies proxy = self.proxies[self.index] self.index += 1 return proxy I'm confused. What's the problem here? EDIT: You are using threads, is some other one manipulating the same data? – Thierry Lathuille Output of cat log | grep (proxy1) 0 [u'(proxy1):(port1)', u'(proxy2):(port2)'] 1 [u'(proxy1):(port1)', u'(proxy2):(port2)'] 0 [u'(proxy1):(port1)', u'(proxy2):(port2)'] 1 [u'(proxy1):(port1)', u'(proxy2):(port2)'] 0 [u'(proxy1):(port1)', u'(proxy2):(port2)'] 1 [u'(proxy1):(port1)', u'(proxy2):(port2)'] 0 [u'(proxy1):(port1)', u'(proxy2):(port2)'] 1 [u'(proxy1):(port1)', u'(proxy2):(port2)'] 0 [u'(proxy1):(port1)', u'(proxy2):(port2)'] 1 [u'(proxy1):(port1)', u'(proxy2):(port2)'] 0 [u'(proxy1):(port1)', u'(proxy2):(port2)'] 1 [u'(proxy1):(port1)', u'(proxy2):(port2)'] 0 [u'(proxy1):(port1)', u'(proxy2):(port2)'] 1 [u'(proxy1):(port1)', u'(proxy2):(port2)'] 0 [u'(proxy1):(port1)', u'(proxy2):(port2)'] 1 [u'(proxy1):(port1)', u'(proxy2):(port2)'] 0 [u'(proxy1):(port1)', u'(proxy2):(port2)'] (...)
has answer: http://stackoverflow.com/a/52198892
has comment: http://stackoverflow.com/comment/91346609
has comment: http://stackoverflow.com/comment/91346676
has comment: http://stackoverflow.com/comment/91346512
type: Question
answer count: 1
score: 0
accepted answer: http://stackoverflow.com/a/52198892
has title: List index out of range, but the item exists
has comment: http://stackoverflow.com/comment/91346782
has comment: http://stackoverflow.com/comment/91346088
has comment: http://stackoverflow.com/comment/91346222
has comment: http://stackoverflow.com/comment/91346218
has comment: http://stackoverflow.com/comment/91346683
tagged with: python
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/q/52236655
favorite count: 0
type: Question
score: 9
tagged with: openstreetmap
answer count: 2
tagged with: overpass-api
has answer: http://stackoverflow.com/a/58193809
has title: How to get a {{geocodeArea: xxx }} query to work in python using overpy?
upvote count: 9
has body: I want to find all pubs in a specific area using the Overpass API and selecting the area with geocodeArea. Testing the following query on overpass-turbo.eu gives me the desired result: {{geocodeArea:berlin}}-&gt;.searchArea; ( node["amenity"="pub"](area.searchArea); way["amenity"="pub"](area.searchArea); relation["amenity"="pub"](area.searchArea); ); out body; &gt;; out skel qt; But when I implement that query in python using overpy... import overpy api = overpy.Overpass() result = api.query(""" {{geocodeArea:berlin}}-&gt;.searchArea; ( node["amenity"="pub"](area.searchArea); way["amenity"="pub"](area.searchArea); relation["amenity"="pub"](area.searchArea); ); out body; &gt;; out skel qt; """) print("Amenities in nodes: %d" % len(result.nodes)) print("Amenities in ways: %d" % len(result.ways)) ... I get the following error: Traceback (most recent call last): File "testOP.py", line 15, in &lt;module&gt; """) File "/usr/local/lib/python2.7/dist-packages/overpy/__init__.py", line 119, in query msgs=msgs overpy.exception.OverpassBadRequest: Error: line 2: parse error: Unknown type "{" Error: line 2: parse error: An empty query is not allowed Error: line 2: parse error: ';' expected - '{' found. I guess that the problem has to do with the double curly braces, but so far escaping them and other variations didn't help. Possible solution with Nominatim Thanks to @scai I know now, that with {{geocodeArea:xxx}} overpass turbo only makes a geocode request. I decided to implement that in my program by myself using geopy and Nominatim: from geopy.geocoders import Nominatim import overpy city_name = "berlin" # Geocoding request via Nominatim geolocator = Nominatim(user_agent="city_compare") geo_results = geolocator.geocode(city_name, exactly_one=False, limit=3) # Searching for relation in result set for r in geo_results: print(r.address, r.raw.get("osm_type")) if r.raw.get("osm_type") == "relation": city = r break # Calculating area id area_id = int(city.raw.get("osm_id")) + 3600…
possible better answer: http://stackoverflow.com/a/58193809
accepted answer: http://stackoverflow.com/a/52254540
tagged with: python
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/52254540

http://stackoverflow.com/q/52164820
has answer: http://stackoverflow.com/a/52166148
type: Question
has title: How to use xpath attribute in odoo 10?
has body: i want to learn Odoo xml but a don't understand a lot of things specially on xpath, for example : 1 what is attribute, how it's work, and what mean the value 1 inside the attribute tag and if do you have guys some resources to learn more that's great finally thanks a lot
answer count: 2
tagged with: odoo-10
downvote count: 0
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
has answer: http://stackoverflow.com/a/52198309
tagged with: python
accepted answer: http://stackoverflow.com/a/52198309
type: AnsweredQuestion
score: 3
tagged with: odoo
upvote count: 3
possible better answer: http://stackoverflow.com/a/52166148

http://stackoverflow.com/q/52124240
type: AnsweredQuestion
type: Question
score: 5
accepted answer: http://stackoverflow.com/a/52124277
upvote count: 5
tagged with: matplotlib
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52124327
downvote count: 0
has answer: http://stackoverflow.com/a/52124327
favorite count: 0
has body: I was trying to plot a bar diagram with first 10 bars green and last 10 bars red colors. Here is my code: import pandas as pd import numpy as np df = pd.DataFrame({'c0':np.arange(20)}) my_colors = ['g','g','g','g','g', 'g','g','g','g','g', 'r','r','r','r','r', 'r','r','r','r','r'] df.plot(kind='bar', color=my_colors) How can the problem be solved? pd.__version__ '0.23.4'
has answer: http://stackoverflow.com/a/52124277
tagged with: python
has title: Pandas plot bar with different colors not working as expected

http://stackoverflow.com/comment/91365368
score: 0
type: AnswerComment
has text: Reading through the threading docs actually cleared it up for me quite a bit, I think i was overthinking my problem. I rewrote using threading and it's much simpler. thanks
comment on: http://stackoverflow.com/a/52206628
type: Comment

http://stackoverflow.com/comment/91211494
has text: Doens't Work. Also spits out similar error when i try to run a python script
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52127541

http://stackoverflow.com/comment/91228401
has text: @user6910411 - Because the data is evenly distributed across 10 categories . Thought it would perform better. No ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52139266
score: 0

http://stackoverflow.com/comment/91334401
type: QuestionComment
has text: @JesperJuhl: Presumably they're trying to take advantage of `PyMemberDef`'s ability to generate accessors for simple values for them, rather than having to write custom functions for use with the somewhat more complicated/powerful `PyGetSetDef` approach to accessors. CPython is mostly C++-blind, so it can't use member functions directly, meaning they'd have to write wrappers to call the member function.
score: 1
comment on: http://stackoverflow.com/q/52191948
type: Comment

http://stackoverflow.com/comment/91318526
type: Comment
has text: `np.sum(np.isnan(train_df['station']))`
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52184338

curl
tags question: http://stackoverflow.com/q/52174367
tag name: curl
type: Tag
tags question: http://stackoverflow.com/q/52133268

http://stackoverflow.com/comment/91400217
has text: @JonClements Thats is also not working
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52225301
score: 0

http://stackoverflow.com/comment/135698547
comment on: http://stackoverflow.com/a/52568571
score: 0
type: Comment
type: AnswerComment
has text: are these tasks that are stuck in the STARTED state being picked up by your worker at all?

http://stackoverflow.com/q/52175217
tagged with: python
tagged with: logging
has body: I'm having a bit of an issue here. I have set up a scratch py file just to test out my logging. Neither the consoleHandler nor the fileHandler are getting the right output (any output). Can anyone see if they can eyeball any issues? Here is my log config file [loggers] keys=root [handlers] keys=fileHandler, consoleHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=fileHandler, consoleHandler formatter=simpleFormatter [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout, ) [handler_fileHandler] class=FileHandler level=DEBUG formatter=simpleFormatter args=(os.path.join(os.getcwd(), 'logging.log'), 'w') [formatter_simpleFormatter] format=%(asctime)s - %(levelname)s - %(message)s datefmt="%Y-%m-%d %H:%M:%S" Here is the scratch python file, import logging from logging import config LOGGER_NAME = 'Work' logger = logging.getLogger(LOGGER_NAME) logging.config.fileConfig('C:\\Users\\cschuma1\\PycharmProjects\\workstuff\\config\\logging.conf') addition = 'add' + 'ition' logger.debug('print addition %s', addition) I have looked closely at other's configs on stackoverflow and I believe that I have all of the necessary levels set, and formatter/handler objects, etc. for my task. Does anyone know what I am missing?
type: Question
has title: Filehandler and consolehandler aren't working properly with logging config
score: 0
answer count: 1
tagged with: config
has answer: http://stackoverflow.com/a/52194791
type: UnansweredQuestion

http://stackoverflow.com/a/52252886
score: 1
answers question: http://stackoverflow.com/q/52252528
has comment: http://stackoverflow.com/comment/91453281
has comment: http://stackoverflow.com/comment/91453434
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91453230
has body: I think need: df['Entry_Date'] = pd.to_datetime(df['Entry_Date']) df1 = (df.sort_values('Entry_Date') .drop_duplicates(['id1','id2']) .rename(columns={'Entry_Date':'Next_Date'})) df1['Next_Date'] = df1['Next_Date'].shift(-1) print (df1) id1 id2 Next_Date 0 5344265358 55111095504 2018-07-14 3 5344265358 55111095502 2018-08-13 2 5344265358 55111095501 2018-08-13 4 5441440119 55111366675 2018-08-20 5 5441440119 55111366676 2018-09-21 6 5441440119 55111366677 NaT df = df.merge(df1, on=['id1','id2'], how='left') print (df) id1 id2 Entry_Date Next_Date 0 5344265358 55111095504 2018-07-13 2018-07-14 1 5344265358 55111095504 2018-07-13 2018-07-14 2 5344265358 55111095501 2018-08-13 2018-08-13 3 5344265358 55111095502 2018-07-14 2018-08-13 4 5441440119 55111366675 2018-08-13 2018-08-20 5 5441440119 55111366676 2018-08-20 2018-09-21 6 5441440119 55111366677 2018-09-21 NaT 7 5441440119 55111366677 2018-09-21 NaT
downvote count: 0

http://stackoverflow.com/q/52257101
score: 1
upvote count: 1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91461375
downvote count: 0
has answer: http://stackoverflow.com/a/52261252
tagged with: python-asyncio
favorite count: 0
accepted answer: http://stackoverflow.com/a/52261252
possible better answer: http://stackoverflow.com/a/52257243
has answer: http://stackoverflow.com/a/52257243
has body: I encountered a small annoyance with this code: try: return await asyncio.wait_for(tcp_command(cmd), timeout=timeout) except (OSError, asyncio.TimeoutError) as err: print(f"Network problem: {err}") When the timeout occurs, it prints just "Network problem: ". It is caused by an empty value attached to the raised asyncio.TimeoutError: # inside wait_for(): raise futures.TimeoutError() It is easy to hadle the TimeoutError separately, but I find the original construct quite idiomatic and now a core library breaks it. Is there a good reason for it? Is my assumption - that printing an exception should give us a clue what went wrong - correct?
tagged with: python
type: AnsweredQuestion
has title: Why asyncio raises TimeoutError without any message?

http://stackoverflow.com/q/52155722
upvote count: 11
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: qmediaplayer
has comment: http://stackoverflow.com/comment/91262952
has comment: http://stackoverflow.com/comment/91567043
has comment: http://stackoverflow.com/comment/91267991
has comment: http://stackoverflow.com/comment/91545101
tagged with: pyqt5
has body: I am trying to use QMediaPlayer to create a.. media player. I want to have an ability to rewind videos on press of a button. But setting a negative playbackRate via QMediaPlayer.setPlaybackRate doesn't seem to put video on rewind. It just keeps playing forward. I don't want to change the position of the video, I want the video to play at negative speed. Through some logic of mine, setting playbackRate to a negative value would make the video play in reverse. But that just doesn't happen. If you can't understand me clearly, here is a video of what the playback should look like. Here is some barebones code to reproduce the problem: import sys from PyQt5.QtCore import Qt, QUrl, QEvent from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer from PyQt5.QtMultimediaWidgets import QVideoWidget from PyQt5.QtWidgets import QMainWindow, QApplication class VideoWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) videoWidget = QVideoWidget() self.setCentralWidget(videoWidget) self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.mediaPlayer.setVideoOutput(videoWidget) self.mediaPlayer.setMedia( QMediaContent(QUrl.fromLocalFile(r"&lt;some video file&gt;.mp4")) ) self.mediaPlayer.play() app.installEventFilter(self) def eventFilter(self, source, event): if event.type() == QEvent.KeyPress: key = event.key() if key == Qt.Key_A: self.mediaPlayer.setPlaybackRate(1.0) elif key == Qt.Key_Y: self.mediaPlayer.setPlaybackRate(-1.0) # This doesn't work! :( return super().eventFilter(source, event) def closeEvent(self, event): self.mediaPlayer.setMedia(QMediaContent()) if __name__ == '__main__': app = QApplication(sys.argv) player = VideoWindow() player.resize(640, 480) player.show() exitCode = app.exec_() sys.exit(exitCode) I tried searching for a solution, but I got nothing more than what documentation says (emphasis mine): Values less than zero can be set and indicate the media will rewind at the multiplier of the standard pace. However, I am …
type: Question
has comment: http://stackoverflow.com/comment/91264557
has comment: http://stackoverflow.com/comment/91288531
answer count: 1
has comment: http://stackoverflow.com/comment/91566985
score: 11
has comment: http://stackoverflow.com/comment/91545440
has title: QMediaPlayer negative playbackRate doesn't rewind video
has answer: http://stackoverflow.com/a/52264919
downvote count: 0
has comment: http://stackoverflow.com/comment/91549090

http://stackoverflow.com/a/52150515
answers question: http://stackoverflow.com/q/52149914
downvote count: 0
score: 1
has body: Your wayspoints are instance-variables - they do not belong to the class itself but to the instance. In Bot.start(..) you are assigning a new Mouse_Part() instance with empty waypoints to your bots self.mouse_part variable. Fix: class Bot: def __init__(self): self.mouse_part = None def start(self, mouseParts): # this creates a new Mouse_Part() instance that is empty # self.mouse_part = Mouse_Part() - replace with given one self.mouse_part = mouseParts if len(self.mouse_part.waypoints) &gt; 0: for x in self.mouse_part.waypoints: pyautogui.moveTo(x, duration=0.25) else: print('there are no waypoints') keyboard_part = Keyboard_Part() with keyboard.Listener(on_press=keyboard_part.on_press) as listener: listener.join() when done recording waypoints: b = Bot() # provide the instance of Keyboard_part.mouse_part that was filled # before to your bot: b.start(keyboard_part.mouse_part)
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52149914

http://stackoverflow.com/comment/91277197
comment on: http://stackoverflow.com/q/52163784
score: 0
type: Comment
type: QuestionComment
has text: i m sorry but i don't get the issue: what 'when i run another example' means for you? modify the input? what is you expected output?

http://stackoverflow.com/q/52257649
has title: Python Dash navigation and dashboard from bootstrap template not working
tagged with: python
has comment: http://stackoverflow.com/comment/91463208
tagged with: plotly-dash
score: 2
has comment: http://stackoverflow.com/comment/91542371
has comment: http://stackoverflow.com/comment/91463330
downvote count: 0
type: UnansweredQuestion
has body: Since there are hardly any templates available yet for Python Dash, I'm construction my own template for dashboarding/navigation, using resources available like bootstrap and standard jquery. I converted this template to Python Dash, but for some reason, both toggling and some css do not work as in the live demo. I assume I'm doing something wrong with the data-* and arial-* parameters, but for completeness, I supplied all code, except the css, which can be found in the demo source code. What is the reason my template does not work as expected like the live demo? Especially, why does toggling not work and why is markup different? app.py: import dash import dash_html_components as html external_stylesheets = [ { 'href': 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css', 'rel': 'stylesheet', 'integrity': 'sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4', 'crossorigin': 'anonymous' } ] external_scripts = [ { 'src': 'https://use.fontawesome.com/releases/v5.0.13/js/solid.js', 'integrity': 'sha384-tzzSw1/Vo+0N5UhStP3bvwWPq+uvzCMfrN1fEFe+xBmv1C/AtVX5K0uZtmcHitFZ', 'crossorigin': 'anonymous' }, { 'src': 'https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js', 'integrity': 'sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY', 'crossorigin': 'anonymous' }, { 'src': 'https://code.jquery.com/jquery-3.3.1.slim.min.js', 'integrity': 'sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo', 'crossorigin': 'anonymous' }, { 'src': 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js', 'integrity': 'sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ', 'crossorigin': 'anonymous' }, { 'src': 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js', 'integrity': 'sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm', 'crossorigin': 'anonymous' } ] app = dash.Dash( __name__, external_scripts=external_scripts, externa…
tagged with: bootstrap-4
has answer: http://stackoverflow.com/a/54149450
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/99132984
has answer: http://stackoverflow.com/a/52302839
answer count: 2

http://stackoverflow.com/q/52147934
has comment: http://stackoverflow.com/comment/91246169
tagged with: scaling
type: Question
tagged with: neural-network
score: 0
tagged with: deep-learning
has body: I have trained a DNN model in TensorFlow. When I was training my model I did it in batches. After each created batch I was scaling the batch the following way: batch_x_scale = preprocessing.scale(batch_x) However, I did not know that the scale function is having an attribute axis, used to compute the means and standard deviations along. If 0, independently standardize each feature, otherwise (if 1) standardize each sample. By default is set to 0. But where I am using my pre-trained models the input data is a single input, and since is not in batches after scaling my single input in all the value are set to zeros. My questions are: Is there a way to use this model for a single data input (not a batch input)? If I set the scale axis to 1 and try to train a new model, the new model accuracy is very bad. Is there a recommended method for scaling the data? P.S. A single row of my data looks like this: [0, 3, 0, 1, 0, 0, 23, 75, 1073741824, 6, 2, 4, 1, 1310, 72351744, 528594, 203737, 324857, 135362, 10432, 0, 0.457309, 0.664461, 93.38, 0.0, 2.56, 4.08, 0.0, 0.0, 0.0, 0.0, 0.0, 9699728.0, 5707772.0, 37.05, 35.98, 149.79, 43916.95, 1.0, 0.0, 0.0, 0.0, 4, 3800000000, 4, 17179869184, 1600000000, 4194300.0, 0.0, 0.0, 97.72, 0.0, 1.27, 1.01, 0.0, 0.0, 0.0, 0.0, 0.0, 60612218.0, 5239774.0, 7.955, 42.21, 51530.9, 37659.84, 26.0, 0.0, 0.0, 0.0, 4, 3400000000, 8, 68719476736, 2133000000, 8388604.0, 0.0, 0.0, 0.0, 1588.224, 96988, 90740.5, 569992, 613586, 21595180.5, 8454395.0, 277.57924252922504, 0.0, 0.0, 93170.763733, 215854.80707699998]
has comment: http://stackoverflow.com/comment/91246193
tagged with: python
has comment: http://stackoverflow.com/comment/91246385
answer count: 0
type: UnansweredQuestion
has title: Batch scaling for Deep Neural Network
tagged with: tensorflow

http://stackoverflow.com/q/52167816
has comment: http://stackoverflow.com/comment/91286046
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91308110
type: Question
has title: Avoid repeated load of file in function
accepted answer: http://stackoverflow.com/a/52168280
tagged with: function
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91285622
possible better answer: http://stackoverflow.com/a/52168281
has answer: http://stackoverflow.com/a/52168281
tagged with: python-3.x
tagged with: fasta
has answer: http://stackoverflow.com/a/52168280
tagged with: python
has body: I am trying to write a file with functions to take a fasta file and (i) give an overview of the file, (ii) draw a histogram for length distribution of sequences. I successfully wrote the following code that works: from Bio import SeqIO from prettytable import PrettyTable import pylab import numpy as np import sys %matplotlib inline def fasta_outlook(fasta_file): '''Summarize the fasta file with #ofseq, length(min,max). Takes filename as string''' =&gt; sizes = [len(rec) for rec in SeqIO.parse(fasta_file,"fasta")] table = PrettyTable(['Parameter', 'Stats']) table.add_row(['No. of Sequences', len(sizes)]) table.add_row(['Shortest seq.length', min(sizes)]) table.add_row(['Longest Seq.length', max(sizes)]) print(table) def fasta_burst(fasta_file): '''Reports the length of each fasta sequence in the file. Takes filename as string''' my_file = open("Seq_length.tab","w") =&gt; for rec in SeqIO.parse(fasta_file,"fasta"): my_file.write(rec.id+'\t'+str(len(rec))+'\n') print("Length report written in Seq_length.tab") def fasta_lendist(fasta_file): '''plot the distribution of sequence length as histogram. Takes filename as string''' =&gt; sizes = [len(rec) for rec in SeqIO.parse(fasta_file,"fasta")] count,bins,_ = pylab.hist(sizes, bins=100, log=True, histtype='step',color='red') pylab.title("%i seq with len: %i to %i bp (range)\nBin Max: %i seq around %i bp"%(len(sizes),min(sizes),max(sizes),count.max(),bins[np.argmax(count)])) pylab.xlabel("Sequence length (bp)") pylab.ylabel("Log Count") pylab.savefig("Sequence_length_distribution_plot.png") print("Plot saved as Sequence_length_distribution_plot.png") fasta = 'filename.fa' fasta_outlook(fasta) fasta_lendist(fasta) The problem here is, in all the functions I load the file (=>) repeatedly. Is it possible to load file only once globally and use the object in subsequent functions? Does the arg to a function take an object instead of filename(string)?

http://stackoverflow.com/q/52112560
answer count: 1
favorite count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/91175948
has body: I use PIL in order to convert imagse to monochrome and afterwards to a list of lists, but I am not sure how to do so with rgb images. Can someone give me a direction how to convert images to a multi-dimensional list and backwards an python?
tagged with: python
has answer: http://stackoverflow.com/a/52113846
type: AnsweredQuestion
score: 7
accepted answer: http://stackoverflow.com/a/52113846
tagged with: image-processing
downvote count: 1
type: Question
tagged with: python-imaging-library
has title: Convert a image (png and jpg) to a multi-dimensional list and backwards in python

http://stackoverflow.com/a/52182190
answers question: http://stackoverflow.com/q/52181628
score: 0
type: Answer
has body: Use Signals, from django.db.models.signals import post_save from django.contrib.auth.models import User import Record def send_data(sender, instance, created, **kwargs): record = Record() record.employee_ID = instance.username record.first_name = instance.first_name .... post_save.connect(receiver = send_data, sender= User)

http://stackoverflow.com/comment/91303810
type: Comment
type: QuestionComment
has text: There are two `else` branches in this code. Which are you referring to?
comment on: http://stackoverflow.com/q/52176457
score: 0

http://stackoverflow.com/comment/91484106
type: Comment
score: 0
has text: Why not `["2b", ["cd"]]`
comment on: http://stackoverflow.com/q/52268130
type: QuestionComment

http://stackoverflow.com/q/52143854
tagged with: apply
possible better answer: http://stackoverflow.com/a/52144008
upvote count: 4
has comment: http://stackoverflow.com/comment/91237505
accepted answer: http://stackoverflow.com/a/52143874
has answer: http://stackoverflow.com/a/52143950
has body: I'm trying to build a dataframe in python that is filled with 1s and 0s, depending on the number in one column: Date Hour 2005-01-01 1 2005-01-01 2 2005-01-01 3 2005-01-01 4 I want to make new columns based on the number in "Hour", and fill each column with a 1 if that row is equal to the value in "Hour", or 0 if not. Date Hour HE1 HE2 HE3 HE4 2005-01-01 1 1 0 0 0 2005-01-01 2 0 1 0 0 2005-01-01 3 0 0 1 0 2005-01-01 4 0 0 0 1 I can do it with this code, but it takes a long time: for x in range(1,5): _HE = 'HE' + str(x) for i in load.index: load.at[i, _HE] = 1 if load.at[i,'Hour']==x else 0 I feel like this is a great application (no pun intended) for .apply(), but I can't get it to work right. How would you speed this up?
has comment: http://stackoverflow.com/comment/91237552
tagged with: pandas
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/38938318
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/52143874
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/52144008
has title: apply vs nested for loops
answer count: 3

http://stackoverflow.com/a/52193107
downvote count: 0
score: 6
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/52192855
has body: You could use itertools.product function: from itertools import product list3 = [a+str(b) for a, b in product(list1, list2)]

http://stackoverflow.com/comment/91466460
type: AnswerComment
comment on: http://stackoverflow.com/a/52252813
score: 0
type: Comment
has text: Thanks. It works, but it is a bit slow on my computer.

http://stackoverflow.com/a/52122915
has comment: http://stackoverflow.com/comment/91328574
has body: If l contains your list, I think something like: [i.split('-')[0] for i in l] should provide a good start.
accepted answer of: http://stackoverflow.com/q/52122876
answers question: http://stackoverflow.com/q/52122876
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/60523551
answers question: http://stackoverflow.com/q/52265620
type: Answer
has body: You can try something like this: from .ui_file import * That is what I wrote for my project: from .devices_steps import *
score: 0

http://stackoverflow.com/q/52194717
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91339524
has answer: http://stackoverflow.com/a/52194845
has comment: http://stackoverflow.com/comment/91339111
upvote count: 5
tagged with: arrays
score: 4
has comment: http://stackoverflow.com/comment/91339113
has comment: http://stackoverflow.com/comment/91367929
has comment: http://stackoverflow.com/comment/91339137
linked to: http://stackoverflow.com/q/11295609
has answer: http://stackoverflow.com/a/52198266
has body: I have a list (let's call it all_my_arrays) that contains about 48,000 1D arrays. I'd like to know how many duplicate arrays are in this list, if any. However, I'd like to exclude empty arrays (because I have multiple empty arrays within the list and don't want those factored into my duplicate count). I tried this code below, but it is taking too long: import numpy as np uniques=[] for arr in all_my_arrays: if not np.array_equal(np.array([]), arr): if not any(np.array_equal(arr, unique_arr) for unique_arr in uniques): uniques.append(arr) print(len(uniques)) #number of non-duplicates Is there a much quicker way to accomplish this?
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52194875
has title: Quick way to check for duplicate arrays within list
has comment: http://stackoverflow.com/comment/91339602
type: UnansweredQuestion
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/52195178
has comment: http://stackoverflow.com/comment/91368443
downvote count: 1

http://stackoverflow.com/comment/91307934
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/179441/discussion-between-sven-festersen-and-yuguang).
comment on: http://stackoverflow.com/q/52161656
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91183799
comment on: http://stackoverflow.com/a/52115473
type: AnswerComment
has text: @addicted - There was wrong `sum`, ids necessary after `,'amount'].sum()`
score: 0
type: Comment

http://stackoverflow.com/comment/91412287
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52231296
has text: hi what you mean by ## all profiling code , followed by ## remaining code? For example I have 4 classes running with several methods inside. Where do i put the profiler? tks
score: 0

http://stackoverflow.com/comment/91468327
has text: it is not really clear to me what you are trying to accomplish. can you rephrase the actual issue?
comment on: http://stackoverflow.com/q/52241131
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91224040
comment on: http://stackoverflow.com/q/52137205
score: 0
has text: The first file would get closed, as that's handled by the context manager when the block exits, whether there's an exception or not. The second one: not necessarily.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52182255
has answer: http://stackoverflow.com/a/52183421
type: AnsweredQuestion
tagged with: python-3.x
has body: I am trying to add the weights and biases to tensorboard according to the layers. The following way I tried: tf.reset_default_graph() X = tf.placeholder(tf.float32, [None, n_steps, n_inputs]) y = tf.placeholder(tf.float32, [None,n_outputs]) layers = [tf.contrib.rnn.LSTMCell(num_units=n_neurons, activation=tf.nn.leaky_relu, use_peepholes = True) for layer in range(n_layers)] # for i, layer in enumerate(layers): # tf.summary.histogram('layer{0}'.format(i), tf.convert_to_tensor(layer)) multi_layer_cell = tf.contrib.rnn.MultiRNNCell(layers) for index,one_lstm_cell in enumerate(multi_layer_cell): one_kernel, one_bias = one_lstm_cell.variables # I think TensorBoard handles summaries with the same name fine. tf.summary.histogram("Kernel", one_kernel) tf.summary.histogram("Bias", one_bias) rnn_outputs, states = tf.nn.dynamic_rnn(multi_layer_cell, X, dtype=tf.float32) stacked_rnn_outputs = tf.reshape(rnn_outputs, [-1, n_neurons]) stacked_outputs = tf.layers.dense(stacked_rnn_outputs, n_outputs) outputs = tf.reshape(stacked_outputs, [-1, n_steps, n_outputs]) outputs = outputs[:,n_steps-1,:] # keep only last output of sequence But I got the following error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-43-761df6e116a7&gt; in &lt;module&gt;() 44 45 multi_layer_cell = tf.contrib.rnn.MultiRNNCell(layers) ---&gt; 46 for index,one_lstm_cell in enumerate(multi_layer_cell): 47 one_kernel, one_bias = one_lstm_cell.variables 48 # I think TensorBoard handles summaries with the same name fine. TypeError: 'MultiRNNCell' object is not iterable I would like to know what I have missed so that I can add the variables for visualization in the tensorboard. Kindly, help me.
upvote count: 1
tagged with: tensorflow
has title: 'MultiRNNCell' object is not iterable Python Tensorflow
type: Question
linked to: http://stackoverflow.com/q/42315202
score: 1
accepted answer: http://stackoverflow.com/a/52183421
linked to: http://stackoverflow.com/q/52185422
has comment: http://stackoverflow.com/comment/91316401
downvote count: 0
answer count: 1
favorite count: 0
tagged with: tensorboard
tagged with: python

http://stackoverflow.com/comment/91337711
type: QuestionComment
has text: Your Dockerfile is incomplete. Where's the `FROM` line?
score: 1
comment on: http://stackoverflow.com/q/52193937
type: Comment

http://stackoverflow.com/comment/91338323
has text: Might need help on that one also, it seems that it's a format issue. Trying to do it this way `\"name\": \""descr()"\"` but it says invalid syntax.
comment on: http://stackoverflow.com/a/52193827
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/63807355
answers question: http://stackoverflow.com/q/52208100
score: 0
type: Answer
has body: So, Amazon doesn't allow web scraping on their websites. They may change the HTML content for web scraping programs. For me, the HTML just said: "Forbidden". If you want to get data from Amazon, you will probably need to use their API

http://stackoverflow.com/q/52236996
answer count: 1
has answer: http://stackoverflow.com/a/52237068
tagged with: matplotlib
linked to: http://stackoverflow.com/q/6541123
accepted answer: http://stackoverflow.com/a/52237068
has comment: http://stackoverflow.com/comment/91422657
has body: I have this plot made in pandas: I want to have more space between the titles of the plots and the axis of the following ones, so that they dont overlap. I have tried the solutions of the question Improve subplot size/spacing with many subplots in matplotlib but none of them makes nothing to my plot.
linked to: http://stackoverflow.com/q/2418125
duplicate of: http://stackoverflow.com/q/6541123
has comment: http://stackoverflow.com/comment/91422579
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91422567
downvote count: 0
tagged with: histogram
score: 1
favorite count: 0
type: Question
tagged with: python
has title: How to avoid overlapping between plot titles and axis titles in histogram subplots in pandas?
tagged with: overlap
has comment: http://stackoverflow.com/comment/91422628
upvote count: 1

http://stackoverflow.com/q/52249821
upvote count: 1
downvote count: 0
favorite count: 0
answer count: 1
has title: pymongo insert_one not writing but returning objectid
has answer: http://stackoverflow.com/a/76843032
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91451678
has body: Running CentOS7, python 3.6.6, mongo 4.0.2, r/w access to database unrestricted, no users have been setup. I'm trying to scrape reddit comments and add them to a database, the code is as follows -- from pymongo import MongoClient client = MongoClient() db = client.reddit_comments posts = db.posts post_data = { 'postid': submission.id, 'created': submission.created, 'title': submission.title } print(post_data) result = db.reddit_comments.insert_one(post_data) print('One post: {0}'.format(result.inserted_id)) The printed output, my post data and result, is as follows -- {'postid': '7p1x7e', 'created': 1515722415.0, 'title': 'comment stuff'} One post: 5b95bf479dc6d638808ab230 {'postid': '7d5klp', 'created': 1515512050.0, 'title': 'comment stuff'} One post: 5b95bf479dc6d638808ab231 {'postid': '7sds10', 'created': 1516345119.0, 'title': 'comment stuff'} One post: 5b95bf479dc6d638808ab232 Copying the post_data and manually inserting it into my db works, but this script doesn't seem to insert it. Am I missing something here?
score: 1
tagged with: pymongo
type: Question
tagged with: mongodb

http://stackoverflow.com/comment/91299496
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52173736
type: Comment
has text: And `master` should derive from `tk`, not `tk.Frame`.

http://stackoverflow.com/a/52225079
downvote count: 0
has body: Found out how to sort it(kind of) and thought I'd reply here. I have to run a webserver to accept the data so this is what I have. In the POST function the web.data is the response which says if stream is live/not etc import web urls = ('/.*', 'hooks') app = web.application(urls, globals()) class hooks: def POST(self): data = web.data() print("") print('DATA RECEIVED:') print(data) print("") return 'OK' def GET(self): try: data = web.input() data = data['hub.challenge'] print("Hub challenge: ", data) return data except KeyError: return web.BadRequest if __name__ == '__main__': app.run()
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52188112
accepted answer of: http://stackoverflow.com/q/52188112
type: AcceptedAnswer

http://stackoverflow.com/q/52202909
score: 0
has comment: http://stackoverflow.com/comment/91354846
has body: How can we allocate max CPU usage to a python code at the time of run? I have a script that takes 1hr to run on my local machine(16Gb RAM quad-core) , but takes 4hrs on a remote AWS machine with 32GB RAM and 8cores.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91363329
tagged with: python
has title: How can we allocate max CPU usage to a python code at the time of run?
has comment: http://stackoverflow.com/comment/91361586
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/91355147

http://stackoverflow.com/q/52196242
tagged with: dictionary
has answer: http://stackoverflow.com/a/52196319
tagged with: list
has body: Wondering if there is a "best practice" approach to updating items in a list of dicts. Let's say I have the following and I'd like to update key1 for each dict in the list data = [ {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}, {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}, {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'} ] I know I can make the update in a for loop with range or enumerate like for i, d in enumerate(data): data[i]['key1'] = 'value4' I could also use a list comprehension data = [{'key1': 'value4', 'key2': d['key2'], 'key3': d['key3']} for d in data] However, I feel this approach may become error-prone to code if there are many key/value pairs in the dicts Is there some other way that I have overlooked? PS I note that the loop is significantly faster than the comprehension. Does this play into things? In [12]: %timeit [{'key1': 'value4', 'key2': d['key2'], 'key3': d['key3']} for d in data] The slowest run took 8.41 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 1.25 µs per loop In [14]: %timeit for i, d in enumerate(data): data[i]['key1'] = 'value4' The slowest run took 5.20 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 541 ns per loop
has title: Best practice for updating list of dicts in Python
has comment: http://stackoverflow.com/comment/91342570
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91341959
answer count: 1
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/q/52131343
upvote count: 2
tagged with: sockets
tagged with: python
tagged with: putty
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52136283
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/91214819
has comment: http://stackoverflow.com/comment/91214807
tagged with: title
score: 0
answer count: 1
has title: Python change socket window title
has answer: http://stackoverflow.com/a/52136283
favorite count: 0
has body: When I connect to the server using PuTTY, the window says "DBA-LT2017 - PuTTY" How can I change the title of the window of PuTTY? (not the console application) This is the code I have so far import socket import threading from thread import start_new_thread connect = "" conport = 8080 def clientThread(conn): while True: message = conn.recv(512) if message.lower().startswith("quit"): conn.close() if not message: break def startClient(): host = connect port = conport sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((host, port)) sock.listen(1) print("[+] Server Started") while True: conn, addr = sock.accept() start_new_thread(clientThread, (conn,)) sock.close() client = threading.Thread(target=startClient) client.start() I saw a script programmed in C, that uses TCP and can change the session title without telnet either void *titleWriter(void *sock) { int thefd = (int)sock; char string[2048]; while(1) { memset(string, 0, 2048); sprintf(string, "%c]0;Test", '\033', '\007'); if(send(thefd, string, strlen(string), MSG_NOSIGNAL) == -1) return; sleep(2); } }

docker-api
tag name: docker-api
tags question: http://stackoverflow.com/q/52180512
type: Tag

http://stackoverflow.com/q/52159748
has title: Python How to Decompress a dictionary
has comment: http://stackoverflow.com/comment/91269626
has comment: http://stackoverflow.com/comment/91269169
has answer: http://stackoverflow.com/a/52160059
type: Question
has comment: http://stackoverflow.com/comment/91269268
has answer: http://stackoverflow.com/a/52160035
has comment: http://stackoverflow.com/comment/91269631
downvote count: 5
has answer: http://stackoverflow.com/a/52161472
answer count: 3
has body: I have a dictionary with: inds = [0, 3, 7, 3, 3, 5, 1] vals = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0] d = {'inds': inds, 'vals': vals} print(d) will get me: {'inds': [0, 3, 7, 3, 3, 5, 1], 'vals': [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]} As you can see, inds(keys) are not ordered, there are dupes, and there are missing ones: range is 0 to 7 but there are only 0,1,3,5,7 distinct integers. I want to write a function that takes the dictionary (d) and decompresses this into a full vector like shown below. For any repeated indices (3 in this case), I'd like to sum the corresponding values, and for the missing indices, want 0.0. # ind: 0 1 2 3* 4 5 6 7 x == [1.0, 7.0, 0.0, 11.0, 0.0, 6.0, 0.0, 3.0] Trying to write a function that returns me a final list... something like this: def decompressor (d, n=None): final_list=[] for i in final_list: final_list.append() return(final_list) # final_list.index: 0 1 2 3* 4 5 6 7 # final_list = [1.0, 7.0, 0.0, 11.0, 0.0, 6.0, 0.0, 3.0]
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/91269850
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91269590
has comment: http://stackoverflow.com/comment/91269469

dng
tags question: http://stackoverflow.com/q/52259981
type: Tag
tag name: dng

http://stackoverflow.com/comment/91477243
has text: @EPo I don't think that is necessary. With same probability distribution, values of the column can be different. It is possible for two columns having different set of values but portraying same probability distribution. Don't you think this is true? sorry if I am not able to understand your comment.
comment on: http://stackoverflow.com/q/52264187
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91494968
has text: You can use a self-signed certificate for the server - the documentation has a cookbook for that. You need no certificate on the client side. It is really simple if compression is all you want.
type: QuestionComment
comment on: http://stackoverflow.com/q/52249871
score: 0
type: Comment

http://stackoverflow.com/a/52174465
has comment: http://stackoverflow.com/comment/91299991
has comment: http://stackoverflow.com/comment/91300866
has comment: http://stackoverflow.com/comment/91302800
type: Answer
has comment: http://stackoverflow.com/comment/91303287
score: 1
has comment: http://stackoverflow.com/comment/91300383
has body: In Python you can pass a function as a parameter to another function. Your istrue could be passed in this manner. def myfilter(seq, func): for x in seq: if func(x): yield x print(list(myfilter([0,1,2,3], istrue))) Realize that this is a toy example and a non-trivial use case would be more useful but more complicated. As pointed out in the comments, there's no need to write your own istrue function because Python already has one: bool.
has comment: http://stackoverflow.com/comment/91299893
has comment: http://stackoverflow.com/comment/91299919
has comment: http://stackoverflow.com/comment/91300566
upvote count: 2
answers question: http://stackoverflow.com/q/52174366
has comment: http://stackoverflow.com/comment/91301653
downvote count: 1

http://stackoverflow.com/comment/92024861
type: AnswerComment
score: 0
has text: @Martin Thanks for pointing that out! I have modified my answer to support variable setting as well
type: Comment
comment on: http://stackoverflow.com/a/52514830

http://stackoverflow.com/comment/91225763
type: Comment
comment on: http://stackoverflow.com/a/52138023
score: 0
type: AnswerComment
has text: Thanks for your answer. However, is there anyway to create a loop that separates each row and store them in that manner? as a[0], a[1],...., a[i] since I have +600 record

http://stackoverflow.com/a/52129659
score: 1
has body: From what I gather, the draw functions of networkx do not make any effort drawing self loops. The thing that make me say that is: if you change your script to import networkx as nx import matplotlib.pyplot as plt G=nx.Graph() graph = {("A","A"): 3, ("A","B"): 4, ("A","C"): 1} #graph = {("A","B"): 4, ("A","C"): 1} for edge in graph: G.add_edge(edge[0], edge[1]) graph_pos=nx.circular_layout(G) nx.draw_networkx_edge_labels(G, graph_pos, edge_labels = graph) nx.draw_networkx_nodes(G,graph_pos, alpha=0.1) nx.draw_networkx_edges(G,graph_pos) #nx.draw_networkx_labels(G, graph_pos) plt.show() you will notice that the edge label is shown. In Networkx it seems that the edges are just lines between vertex. A line between the same point is well… nothing… So I think you will have no luck with networkx. However using pygraphviz is your best bet as suggested in Matplotlib and Networkx - drawing a self loop node From my knowledge graphviz (warning it comes only in 32 bits) (and it's python wrapper pygraphviz which needs graphviz) is still a very good graph visualizer. After installation you can use the to_agraph function of networkx.drawing.nx_agraph. Good luck.
upvote count: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52128561

http://stackoverflow.com/q/52175987
tagged with: image-uploading
has comment: http://stackoverflow.com/comment/91302768
has comment: http://stackoverflow.com/comment/91520505
type: Question
has comment: http://stackoverflow.com/comment/91302913
has answer: http://stackoverflow.com/a/52176961
has comment: http://stackoverflow.com/comment/91521275
has comment: http://stackoverflow.com/comment/91521239
has comment: http://stackoverflow.com/comment/91520530
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/52286702
answer count: 2
type: UnansweredQuestion
has body: I'm trying to upload an image via ajax. The image uploads well, but it is delivered inside a "None" folder, between the MEDIA_ROOT value and upload_to parameter of ImageField. My current settings are as follows: MEDIA_ROOT = (os.path.join(BASE_DIR, 'static', 'media')) Inside my app's models.py: image = models.ImageField(blank=True, null=True, upload_to=get_image_path) and def get_image_path(instance, filename): return os.path.join(connection.tenant.schema_name, 'img', 'devices', filename) When I upload the image, it goes to static/media/None/(tenant.schema_name)/img/devices, instead of static/media/(tenant.schema_name)/img/devices (In the picture, tenant.schema_name is "ars") The form is as follows: class DeviceForm(ModelForm): class Meta: model = Device fields = ['name', 'model', 'serial', 'location', 'note', 'image', 'page', 'address'] And the saving snippet: if request.method == 'POST': post_data = request.POST.dict() form = DeviceForm(post_data, request.FILES) if not form.is_valid(): return JsonResponse({"message": "Form is invalid"}, status=400) obj = form.save() return JsonResponse(obj.to_dict(), safe=False) Is there a configuration that I'm missing? Any help would be appreciated EDIT: Here's the whole settings.py: import os from django.utils.translation import ugettext_lazy # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = (key) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True if DEBUG: ALLOWED_HOSTS = ['*'] # Allow any host during debug mode else: ALLOWED_HOSTS = [] # Application definition SHARED_APPS = [ 'tenant_schemas', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions'…
tagged with: django
tagged with: django-1.11
tagged with: python
has comment: http://stackoverflow.com/comment/91303182
has title: Image upload goes to "None" folder in django
has comment: http://stackoverflow.com/comment/91302935

http://stackoverflow.com/comment/91248394
type: Comment
type: QuestionComment
score: 0
has text: See the duplicate on how to define methods that can take a variable number of arguments.
comment on: http://stackoverflow.com/q/52149297

http://stackoverflow.com/q/52262965
has comment: http://stackoverflow.com/comment/91476210
tagged with: python
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/91480396
score: 1
has body: I have a python app.pyo and i have this error: File "RdpConnect.pyo", line 1 SyntaxError: Non-UTF-8 code starting with '\xbd' in file RdpConnect.pyo on line 2, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for detail s In normal application this error is really simple to fix, how i can fix ecodec error in .pyo file ? Attention: i don't have source code of application
type: Question
has comment: http://stackoverflow.com/comment/91475474
downvote count: 0
has title: SyntaxError: Non-UTF-8 code starting with '\xbd' in file .pyo
has comment: http://stackoverflow.com/comment/91476908
has comment: http://stackoverflow.com/comment/91476854

http://stackoverflow.com/q/52249355
tagged with: self-organizing-maps
upvote count: 5
has title: Why is this Python script running faster in the CPU than in the GPU?
has answer: http://stackoverflow.com/a/52271494
score: 5
has comment: http://stackoverflow.com/comment/91447263
has comment: http://stackoverflow.com/comment/91447328
has body: I'm using Python's library somoclu to train a self-organising map using Python. The library allows users to perform the training either on the CPU (Intel Core i7-8700) or on the GPU (GeForce GTX 1080 Ti). I noticed that the CPU was running the script faster than the GPU did, so I ran a sweep varying the number of datapoints and the size of the map, to see if at some point the GPU outperformed the CPU. This was the script: import numpy as np import somoclu import time m = 3 # Number of dimensions points = [5000, 30000, 80000, 150000, 300000] # Number of datapoints iterMax = 200 # Max number of iterations mapSize = [4, 32, 64, 128] # Dimensions of SOM np.random.seed(0) #%% SOM for n in points: for size in mapSize: y = np.random.rand(n,m) # Input data # With CPU t = time.clock() # Start time som = somoclu.Somoclu(size, size, compactsupport = False, kerneltype = 0) som.train(y.astype(np.float32), epochs = iterMax) elapsedTime = time.clock() - t # With GPU t = time.clock() # Start time som = somoclu.Somoclu(size, size, compactsupport = False, kerneltype = 1) som.train(y.astype(np.float32), epochs = iterMax) elapsedTime = time.clock() - t I saved the times in a CSV, and this is what I got: CPU GPU 2.7632589999999997 5.935387999999999 60.340638 82.796062 228.292085 305.75625900000006 861.3243 1141.331934 11.692982999999913 24.568256999999903 330.17140100000006 443.82112400000005 1354.677431 1749.3110039999992 5559.308704 6990.034151000002 29.3726179999976 47.36881999999969 913.3250950000001 1163.5942189999987 3703.653313999999 4615.292857 14868.418703000003 18635.051464000004 37.40133600000263 68.64375999999902 1699.020611 2141.047305 6925.692426000009 8645.564134 27887.844171999997 illegal memory access was encountered As you can see, the CPU outperforms the GPU in every single case (on top of it, the GPU version crashed when running the script with 150000 datapoints and a 64x64 map). How is this possible? What is the advantage on using the GPU to train the SOM then? EDIT…
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91447369
has comment: http://stackoverflow.com/comment/91446937
has comment: http://stackoverflow.com/comment/91490161
favorite count: 0
has comment: http://stackoverflow.com/comment/91447227
tagged with: gpu
type: UnansweredQuestion
tagged with: python
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/91446905
has comment: http://stackoverflow.com/comment/91447349
has comment: http://stackoverflow.com/comment/91447345
type: Question
has comment: http://stackoverflow.com/comment/91447243

http://stackoverflow.com/a/52257239
answers question: http://stackoverflow.com/q/52221123
type: Answer
downvote count: 0
has body: There are a few issues I'll point out, but the question is missing a few details so hopefully I can address them all in one shot: Your syntax here is wrong: @patch checkout.pay.NewFraudCheck. It should be @patch('checkout.pay.NewFraudCheck') There is a missing class somewhere that has the function pay(self) on it. That class lives inside a module somewhere which is important to properly mock NewFraudCheck. I'll refer to that missing module as other. NewFraudCheck needs to be patched at the point where it's looked up. That means, in the mystery module other where there's a class that has pay(self) defined in it, there's presumably an import of from pay import NewFraudCheck. That is where NewFraudCheck is looked up, so your patch will need to look like this: @patch('checkout.other.NewFraudCheck). More info here: http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch You need to assign/use the return value of your patch, not access verify_transaction directly off of the mock. For instance, it should read like this: mock_fraud_check.return_value.verify_transaction.return_value = (1, 1231231). Notice the inclusion of return_value. The final test I came up with looked like this and passed: @mock.patch('checkout.other.NewFraudCheck') def test_pay(self, mock_fraud_check): # This is the class that lives in mystery module, 'checkout.other' and calls pay() other_class = SomeOtherClass() mock_fraud_check.return_value.verify_transaction.return_value = (1, 1231231) other_class.pay() mock_fraud_check.return_value.verify_transaction.assert_called()
score: 5
upvote count: 5

http://stackoverflow.com/comment/91215162
comment on: http://stackoverflow.com/q/52132072
has text: Each of your raw_inputs has an extra close parenthesis
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/91241582
type: QuestionComment
has text: What i mean to ask is when list is created it has no values and we cant add values using the index. But when directories are created we can add values to it using keys .we dont need append method.why is this so
score: 0
comment on: http://stackoverflow.com/q/52145853
type: Comment

http://stackoverflow.com/comment/91412260
type: QuestionComment
comment on: http://stackoverflow.com/q/52230875
has text: @MichaelButscher ok will try that thank you
score: 0
type: Comment

http://stackoverflow.com/a/52139160
has body: Your problem here is that prior to Python 3.7 dictionaries did not have an insertion order so you could not "order" them. As you can see here: Official Python Docs on Dictionaries. If you provide more insight on whats the purpose of this we might try to solve it in other way.
type: Answer
downvote count: 1
score: 2
upvote count: 3
answers question: http://stackoverflow.com/q/52139110

http://stackoverflow.com/q/52213804
tagged with: dataframe
has body: I have the following two dataframes (samples). I'd like to know which companies had their sales changed between the two dataframes. For example, AAPL is different in the second dataframe. Sales 52W High 52W Low Root A 4.81B -0.1072 0.1082 AA 12.81B -0.3124 0.0709 AABA 266.05M -0.2038 0.0437 AAL 43.52B -0.3285 0.1131 AAN 3.61B -0.0208 0.4716 AAOI 321.80M -0.5196 0.5195 AAP 9.42B -0.0153 1.1190 AAPL 255.27B -0.0101 0.5210 AAXN 385.40M -0.1005 2.3432 ABB 35.52B -0.1870 0.0987 Sales 52W High 52W Low Root A 4.81B -0.1019 0.1149 AA 12.81B -0.3527 0.0082 AABA 266.05M -0.2212 0.0208 AAL 43.52B -0.3487 0.0797 AAN 3.61B -0.0196 0.4733 AAOI 321.80M -0.5478 0.4303 AAP 9.42B -0.0216 1.1218 AAPL 243.89B -0.0286 0.4957 AAXN 385.40M -0.0806 2.4171 ABB 35.52B -0.1838 0.1030
upvote count: 1
answer count: 1
favorite count: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/48647534
tagged with: python
has comment: http://stackoverflow.com/comment/91377090
downvote count: 0
has title: Compare two dataframes with same index using one column
type: Question
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52213867
accepted answer: http://stackoverflow.com/a/52213867

http://stackoverflow.com/a/52205502
answers question: http://stackoverflow.com/q/52205034
score: 0
accepted answer of: http://stackoverflow.com/q/52205034
has body: Prior to Python3.5: generators This solution also works for more recent Python versions, although async def, new in Python3.5, seems more fit for your usecase. See next section. The values yielded by a generator are obtained by iterating or using next. The value returned at the end is stored in the value attribute of the StopIteration exception that indicates the end of the generator. Fortunately, it is not too hard to recover. def hardWork(): output = [] for i in range(10): # hard work yield 'Doing ' + str(i) output.append(i ** 2) return output def generator(): # do some calculations work = hardWork() while True: try: print(next(work)) except StopIteration as e: result = e.value break yield result Example foo = generator() print(next(foo)) Output Doing 0 Doing 1 Doing 2 Doing 3 Doing 4 Doing 5 Doing 6 Doing 7 Doing 8 Doing 9 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] Python3.5+: async def If you are running Python3.5+, what you are attempting seems perfectly fit for an event loop using awaitable functions. import asyncio async def hardWork(): output = [] for i in range(10): # do hard work print('Doing ', i) output.append(i**2) # Break point to allow the event loop to do other stuff on the side await asyncio.sleep(0) return output async def main(): result = await asyncio.wait_for(hardWork(), timeout=None) print(result) loop = asyncio.get_event_loop() loop.run_until_complete(main()) Output Doing 0 Doing 1 Doing 2 Doing 3 Doing 4 Doing 5 Doing 6 Doing 7 Doing 8 Doing 9 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
type: Answer
type: AcceptedAnswer

http://stackoverflow.com/q/52222385
has answer: http://stackoverflow.com/a/52222825
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91393664
favorite count: 0
tagged with: postgresql
has body: I'm trying to collect output of a postgres query in ods-file using following code. I have created a function read_table that reads the postgres table successfully. def read_table() import psycopg2 as ps import sys con =None try: con=ps.connect("host, dbname, user,pwd....") cur=con.cursor() cur.execute("Select * from table_name") rows=cur.fetchall() for(row in rows): print(row) cur.close() except (Exception, ps.DatabaseError) as error: print(error) finally: if con is not None: con.close() from collections import OrderedDict from pyexcel_ods import save_data data=OrderedDict() raw_data=read_table() raw_data.update({'DATA':raw_data}) save_data("/home/myfile.ods", raw_data) The table is printed on python shell but it is not written to .ods-file. It gives following error: raw_data.update({'DATA':raw_data}) AttributeError: 'NoneType' object has no attribute How do I save &amp; extract the table in ods-file? All the packages &amp; modules are installed, but still I get this error. I'm a newbie in python, so please guide me. I'm using Postgres database on Ubuntu, using Idle3.
tagged with: python
has title: Unable to extract data from postgres table to .ods file, using python
type: AnsweredQuestion
upvote count: 1
type: Question
score: 1
accepted answer: http://stackoverflow.com/a/52222825
tagged with: ubuntu
tagged with: ods

http://stackoverflow.com/q/52148295
answer count: 2
has title: Making sure the user's input is not a string in Python 3
has comment: http://stackoverflow.com/comment/91246451
favorite count: 0
possible better answer: http://stackoverflow.com/a/52148399
tagged with: python
has answer: http://stackoverflow.com/a/52148399
has answer: http://stackoverflow.com/a/52148345
duplicate of: http://stackoverflow.com/q/23294658
type: AnsweredQuestion
downvote count: 2
upvote count: 1
type: Question
has body: I try to make a function that at first will check if the input is not a string. But if the user inputs a float, it gets False. I need it to accept both Int and Float, bot not a string. def squat(): value = input("What is your RM1?") if value.isnumeric(): rm1 = float(value) print("Your RM1 is: ", rm1) print(type(value)) else: print("Error") squat()
accepted answer: http://stackoverflow.com/a/52148345
score: -1
linked to: http://stackoverflow.com/q/5424716
has comment: http://stackoverflow.com/comment/91246311

http://stackoverflow.com/q/52249551
score: 0
has body: I am writing python code implementing dfs but i cant get it work correctly. Here is a stupid example using dfs to see if word could be formed by lst: def dfs(word, gen): print(gen) if len(gen) &lt;= len(word): if gen == word: return True lst = ["a","b"] for i in lst: dfs(word, gen+i) return False print(dfs("ba","")) Here my lst is ["a", "b"] and it could obviously form "ba". However it returns False. I get the output of the word it formed each time by the print(gen): a aa aaa aab ab aba abb b ba bb bba bbb and I could see ba in the result, so shouldn't the program stop recursion and returns True once it meets ba? What's wrong with my code?
type: Question
has comment: http://stackoverflow.com/comment/91447260
has comment: http://stackoverflow.com/comment/91447395
has title: How to correct this python dfs search?
tagged with: algorithm
has answer: http://stackoverflow.com/a/52249646
possible better answer: http://stackoverflow.com/a/52249644
has answer: http://stackoverflow.com/a/52249644
accepted answer: http://stackoverflow.com/a/52249641
answer count: 3
tagged with: python
tagged with: depth-first-search
has answer: http://stackoverflow.com/a/52249641
type: AnsweredQuestion

http://stackoverflow.com/comment/91478162
comment on: http://stackoverflow.com/q/52265021
score: 0
has text: @K-Log im not sure, should i use database time, or python system time.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91366923
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52208627
has text: did you try `"x = file.read(8).split()"` then use `x[0]` and `x[1]` in place of `x` and `y`?
score: 0

pyqt4
tags question: http://stackoverflow.com/q/52230953
type: Tag
tags question: http://stackoverflow.com/q/52213377
tags question: http://stackoverflow.com/q/52142950
tags question: http://stackoverflow.com/q/52225952
tags question: http://stackoverflow.com/q/52171529
tag name: pyqt4

http://stackoverflow.com/comment/91301999
comment on: http://stackoverflow.com/a/52175584
score: 0
type: AnswerComment
type: Comment
has text: but those pixel values don't meet the requirements

http://stackoverflow.com/comment/91184225
has text: Now that is weird, I am running python 3.7 btw. After re-installing pandas, I still have the same bad behaviour :(
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52115873

http://stackoverflow.com/comment/91331969
comment on: http://stackoverflow.com/q/52190524
score: 0
type: Comment
type: QuestionComment
has text: I needed to discuss to be able to properly answer but I hope you got some ideas I think ... you can use pop() or slice the list [1:] like I showed you in chat room... and use while loop instead..

http://stackoverflow.com/comment/91372620
comment on: http://stackoverflow.com/q/52211220
type: QuestionComment
has text: It just makes an image. You can do anything you want with the resulting image, including displaying it in a GUI.
type: Comment
score: 1

http://stackoverflow.com/q/52190047
tagged with: cmd2
score: 0
has comment: http://stackoverflow.com/comment/91330663
type: UnansweredQuestion
tagged with: python
answer count: 0
has body: Here is a simple script using the Python cmd2 library. import cmd2 class App(cmd2.Cmd): result = 0 # Long computation def do_add3(self, arg): r = 3 + int(arg) print(r) self.result = r # Scripting def do_test(self, arg): self.do_add3("4") self.do_add3("2") self.do_add3("1") print(self.result) if __name__ == '__main__': app = App() app.cmdloop() Gist link The result of a do_add3 function is saved (returned) into self.result. Later that do_add3 was called internally with self.do_add3("4"). Is there a better way to return results from a do_ function, such that I can code like in the following? self.do_add("4") + self.do_add("3") + self.do_add("2") P.S. For example, I can't use return inside do_ function to return value. Is there a better way?
has comment: http://stackoverflow.com/comment/91329891
type: Question
has title: Capture do function results inside cmd2
has comment: http://stackoverflow.com/comment/91330035

http://stackoverflow.com/q/52264156
favorite count: 0
has answer: http://stackoverflow.com/a/52264692
has title: Trying to run JavaScript from Python
tagged with: python
tagged with: python-3.x
upvote count: 0
has body: I am trying to run the below script from Python. import execjs var request = require('request'); var apiHostName='https:/url.com'; emailAddress = 'my.email@company.com' apiKey = 'api_key' function callback(error, response, body) { if (!error && response.statusCode == 200) { console.log("Identity with email address " + emailAddress + " found:"); var b= JSON.parse(body); console.log("id="+b.identityId+",api key="+b.apiKey+",type="+b.type); } else{ if (response.statusCode == 401) { console.log ("Couldn't recognize api key="+apiKey); } else if (response.statusCode == 403) { console.log ("Operation forbidden for api key="+apiKey); } else if (response.statusCode == 404) { console.log ("Email address " +emailAddress + " not found"); } } } I did this: pip install py-mini-racer pip install PyExecJS I would think this is pretty close, based on the research that I did, but I don't know for sure. All I'm getting now is this error: 'SyntaxError: invalid syntax' The error occurs on this line: 'var request = require('request');' Obviously, I am using my actual email and api key. I am running Python 3.x.
type: UnansweredQuestion
score: -4
has comment: http://stackoverflow.com/comment/91476462
type: Question
has comment: http://stackoverflow.com/comment/91476244
has comment: http://stackoverflow.com/comment/91477219
downvote count: 4
has comment: http://stackoverflow.com/comment/91476365
answer count: 1
tagged with: javascript

http://stackoverflow.com/comment/91202674
comment on: http://stackoverflow.com/q/52125543
type: QuestionComment
type: Comment
has text: `pip show tensorflow-gpu` , `pip list | grep tensorflow-gpu` , `python -c 'import tensorflow as tf; print(tf.test.gpu_device_name())'`
score: 3

http://stackoverflow.com/a/52172779
has comment: http://stackoverflow.com/comment/91296443
answers question: http://stackoverflow.com/q/52172738
downvote count: 0
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52172738
has comment: http://stackoverflow.com/comment/91297031
has comment: http://stackoverflow.com/comment/91296389
has body: You can zip your lists together to iterate over both for list1_elm, list2_elm in zip(List1, List2): pass # Remove pass when you add your print statement # Do things Here
has comment: http://stackoverflow.com/comment/91296271
type: AcceptedAnswer

http://stackoverflow.com/comment/91336246
comment on: http://stackoverflow.com/q/52187362
score: 0
has text: Thanks guys. I am thinking of using it on a central server which has python installed and then using a batch file or pysimpleGUI.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52183433
has body: i've done the Tutorial from sentdex. But when I excecute the programm, loss is always 0.0. Epoch 0 completed out of 10 loss: 0.0 Epoch 1 completed out of 10 loss: 0.0 Epoch 2 completed out of 10 loss: 0.0 Epoch 3 completed out of 10 loss: 0.0 Epoch 4 completed out of 10 loss: 0.0 Epoch 5 completed out of 10 loss: 0.0 Epoch 6 completed out of 10 loss: 0.0 Epoch 7 completed out of 10 loss: 0.0 Epoch 8 completed out of 10 loss: 0.0 Epoch 9 completed out of 10 loss: 0.0 Accuracy: 0.0 I am not able to find any solutions. import numpy as np import tensorflow as tf old_v = tf.logging.get_verbosity() tf.logging.set_verbosity(tf.logging.ERROR) import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) n_nodes_hl1 = 500 n_nodes_hl2 = 500 n_nodes_hl3 = 500 n_classes = 10 batch_size = 100 x = tf.placeholder('float', [None, 784]) y = tf.placeholder('float') def neural_network_model(data): hidden_1_layer = {'weights': tf.Variable(tf.random_normal([784, n_nodes_hl1])), 'biases': tf.Variable(tf.random_normal([n_nodes_hl1]))} hidden_2_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), 'biases': tf.Variable(tf.random_normal([n_nodes_hl2]))} hidden_3_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])), 'biases': tf.Variable(tf.random_normal([n_nodes_hl3]))} output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])), 'biases': tf.Variable(tf.random_normal([n_classes])), } l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']), hidden_1_layer['biases']) l1 = tf.nn.relu(l1) l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['biases']) l2 = tf.nn.relu(l2) l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']), hidden_3_layer['biases']) l3 = tf.nn.relu(l3) output = tf.matmul(l3, output_layer['weights']) + output_layer['biases'] return output def train_neural_network(x): prediction = neu…
tagged with: python
has answer: http://stackoverflow.com/a/52183551
accepted answer: http://stackoverflow.com/a/52183995
has title: Tensorflow Loss is always 0.0
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/52183551
tagged with: tensorflow
type: Question
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/52183995
downvote count: 0
has comment: http://stackoverflow.com/comment/91326642
favorite count: 0

http://stackoverflow.com/a/52969340
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52171982
has body: When reported to the Python mailing list, this was considered a "good catch" by the BDFL. According to the issue, this has been fixed. The pull request for the fix was merged and backported. It works as expected starting in Python 3.7.6 and Python 3.8.1.
has comment: http://stackoverflow.com/comment/102765771
type: Answer
accepted answer of: http://stackoverflow.com/q/52171982
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/98532387
has comment: http://stackoverflow.com/comment/98531111

http://stackoverflow.com/q/52212631
favorite count: 0
has title: How do I add datetime.now().isoformat() to NamedTuple's __init__?
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/91375079
upvote count: 4
has comment: http://stackoverflow.com/comment/91375283
tagged with: namedtuple
score: 3
has body: Of course I have tried: class PdfContentRecord(NamedTuple): filename: str page: int cache: dict data: dict = dict() accessed: str = None def __new__(cls, *args, **kwargs): self = super().__new__(*args, **kwargs) self.accessed = datetime.now().isoformat() return self But I get exactly the same error as How to provide additional initialization for a subclass of namedtuple? I can't tell if attrs can help me (too difficult to comprehend). dataclasses.dataclass probably can help, but it only supports Python 3.7. Or I could write my Class, probably also with __slots__... Edit: Did you read the answer in the question you linked? works with from collection import namedtuple, but not from typing import NamedTuple.
type: Question
has answer: http://stackoverflow.com/a/52212934
answer count: 2
has answer: http://stackoverflow.com/a/52213136
has comment: http://stackoverflow.com/comment/91376263
has comment: http://stackoverflow.com/comment/91375442
has comment: http://stackoverflow.com/comment/91375337
downvote count: 1
has comment: http://stackoverflow.com/comment/91375477
linked to: http://stackoverflow.com/q/3624753

http://stackoverflow.com/comment/91418286
comment on: http://stackoverflow.com/q/52234679
type: Comment
type: QuestionComment
has text: Ah, I think I've misinterpreted your confusion. No, it doesn't normalise on its own, you're right
score: 0

nested
tags question: http://stackoverflow.com/q/52131295
tags question: http://stackoverflow.com/q/52207140
tag name: nested
type: Tag
tags question: http://stackoverflow.com/q/52121560
tags question: http://stackoverflow.com/q/52142882
tags question: http://stackoverflow.com/q/52157879
tags question: http://stackoverflow.com/q/52186918
tags question: http://stackoverflow.com/q/52217032

http://stackoverflow.com/comment/91233304
comment on: http://stackoverflow.com/q/52141350
has text: For future questions/fyi, images are one of the quickest ways to stop the responses.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91217395
score: 0
type: AnswerComment
has text: @DownVoter i think i am down-voted because it's a for loop inefficient
type: Comment
comment on: http://stackoverflow.com/a/52133500

http://stackoverflow.com/comment/91204798
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52127112
has text: well... `vars(C)` works... but where are you looking to get that information? If it's within an instance method, then you can do the same on it's self `_class_`

http://stackoverflow.com/comment/91226104
has text: Thanks Dear, it helped me to get expected result
comment on: http://stackoverflow.com/a/52137432
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91241681
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52140654
has text: I don't think you need to use pandas in this at all but please simplify the question.

http://stackoverflow.com/a/77495749
score: 0
answers question: http://stackoverflow.com/q/52197918
type: Answer
has body: This answer refers to a small mistake in a previous answer. I have not enough reputation to add the comment there. In the selected answer, in the line cont = np.vstack(contours[i] for i in range(length)) there is a type. It should be: cont = np.vstack([contours[i] for i in range(length)]) Otherwise you will get the following error: TypeError: arrays to stack must be passed as a "sequence" type such as list or tuple..

http://stackoverflow.com/q/52195015
tagged with: python
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52201502
tagged with: file-encodings
has title: File encoding on Django deployed server
tagged with: locale
type: UnansweredQuestion
has body: I've deployed my Django application recently to pre-set hosting server (Red Hat) and after short usage came to a UnicodeEncode Error after uploaded images, which are containing Cyrillic symbols (russian, to be specific), but saving CharFields data in russian works just fine. However, the identical code works without a flaw on my personal computers (tested both on Ubuntu and Windows). After file encoding inspection on the server, it turned out, that default system encoding on hosting is ANSI, which is an extension of ASCII At this point, I've contacted tech support and they claimed that it may be Django fault because they use UTF-8 encoding on their servers (How then sys.getfilesystemencoding() showcases, that inherited from OS encoding is ASCII?) My another suspicion were messed locales And it turned out to be true. Anyway, is there any way that it's a Django's fault and it can be fixed with Python/Django hacks or is it completely server's fault? Edit: To be clear, that's not VDS, that's just regular hosting with preset config, so I don't have full control over environment settings, however, I can configure .htaccess file and .fcgi script, so I believe it's Apache server
has answer: http://stackoverflow.com/a/52200546
tagged with: unicode
type: Question
tagged with: django

http://stackoverflow.com/comment/91395031
type: Comment
type: QuestionComment
score: 2
has text: I think you have to put some work into your question, because it is highly unclear what you mean. What is your example code supposed to achieve, because it certainly cannot be executed as it stands
comment on: http://stackoverflow.com/q/52223069

http://stackoverflow.com/q/52138349
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
tagged with: tkinter
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52146311
type: Question
has title: Problem with calling functions with tkinter
score: 1
has body: from tkinter import * from random import * root = Tk() #A function to create the turn for the current player. The current player isnt in this code as it is not important def turn(): window = Tk() dice = Button(window, text="Roll the dice!", bg= "white", command=lambda:diceAction(window)) dice.pack() window.mainloop() #a function to simulate a dice. It kills the function turn. def diceAction(window): result = Tk() y = randint(1, 6) quitButton = Button(result, text="Ok!", bg="white", command=result.destroy) quitButton.pack() window.destroy() result.mainloop() #A function to create the playing field and to start the game def main(): label1 = Button(root, text="hi", bg="black") label1.pack() while 1: turn() print("Hi") turn() main() root.mainloop() My problem is that the code in the while function after the first turn() the code isnt executed until i close the root window(which i dont want because it represents the playing field). You can copy this code and execute it yourself if you want. I have no idea what causes this and havent found anything online. Sorry for the long code but i wrote it so that it is executeable.

http://stackoverflow.com/a/52205983
has comment: http://stackoverflow.com/comment/91361024
has body: import numpy as np alpha = 0.3 beta = 0.8 f = lambda x: (x[0]**2 + 3*x[1]*x[0] + 12) dfx1 = lambda x: (2*x[0] + 3*x[1]) dfx2 = lambda x: (3*x[0]) t = 1 count = 1 x0 = np.array([2,3]) dx0 = np.array([.1, 0.05]) def backtrack(x0, dfx1, dfx2, t, alpha, beta, count): while (f(x0) - (f(x0 - t*np.array([dfx1(x0), dfx2(x0)])) + alpha * t * np.dot(np.array([dfx1(x0), dfx2(x0)]), np.array([dfx1(x0), dfx2(x0)])))) &lt; 0: t *= beta print(""" ######################## ### iteration {} ### ######################## """.format(count)) print("Inequality: ", f(x0) - (f(x0 - t*np.array([dfx1(x0), dfx2(x0)])) + alpha * t * np.dot(np.array([dfx1(x0), dfx2(x0)]), np.array([dfx1(x0), dfx2(x0)])))) count += 1 return t t = backtrack(x0, dfx1, dfx2, t, alpha, beta,count) print("\nfinal step size :", t) Output: ######################## ### iteration 1 ### ######################## Inequality: -143.12 ######################## ### iteration 2 ### ######################## Inequality: -73.22880000000006 ######################## ### iteration 3 ### ######################## Inequality: -32.172032000000044 ######################## ### iteration 4 ### ######################## Inequality: -8.834580480000021 ######################## ### iteration 5 ### ######################## Inequality: 3.7502844927999845 final step size : 0.32768000000000014 [Finished in 0.257s]
type: AcceptedAnswer
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/91361144
upvote count: 4
accepted answer of: http://stackoverflow.com/q/52204231
has comment: http://stackoverflow.com/comment/91365079
has comment: http://stackoverflow.com/comment/91402492
answers question: http://stackoverflow.com/q/52204231
downvote count: 0

http://stackoverflow.com/comment/91215411
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52132371
type: AnswerComment
has text: Sure, it just requires that the vectors of ones is of the same height as `a`, i.e. `np.ones([1, a.shape[0]], dtype=int)`.

http://stackoverflow.com/a/52159769
has body: utilizing json library you can dump your keyboard object: import requests, json bot_token = 'xxxxxxxxxxxxxxxxxxxxxxxx' chat_id = 'xxxxxxxxxxxx' text = "Choose:" reply_markup={"keyboard":[["Yes","No"],["Maybe"],["1","2","3"]],"one_time_keyboard":True} data = {'chat_id': chat_id, 'text': text, 'reply_markup': json.dumps(reply_markup)} url ="https://api.telegram.org/bot" + bot_token + "/sendMessage" r = requests.get(url, data = data) results = r.json() print (results)
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52149507
score: 2
answers question: http://stackoverflow.com/q/52149507
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91414427
type: QuestionComment
comment on: http://stackoverflow.com/q/52231601
has text: Try `pip install --upgrade certifi`.
score: 0
type: Comment

scikit-learn-pipeline
tags question: http://stackoverflow.com/q/52123168
tag name: scikit-learn-pipeline
type: Tag

http://stackoverflow.com/comment/91377464
score: 0
type: Comment
type: QuestionComment
has text: I don't get a warning message. The output just isn't what I expect. I though it would be 0 but it is 86399.
comment on: http://stackoverflow.com/q/52213956

http://stackoverflow.com/q/52118245
score: 35
tagged with: seaborn
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91187560
upvote count: 36
has answer: http://stackoverflow.com/a/52119784
has answer: http://stackoverflow.com/a/57374976
has answer: http://stackoverflow.com/a/61473953
has answer: http://stackoverflow.com/a/65785276
type: Question
has answer: http://stackoverflow.com/a/67705358
has title: Python Seaborn jointplot does not show the correlation coefficient and p-value on the chart
has comment: http://stackoverflow.com/comment/91187476
tagged with: matplotlib
answer count: 6
has answer: http://stackoverflow.com/a/61159579
has comment: http://stackoverflow.com/comment/91190439
has body: I'm trying to plot jointplot with below and from samples I saw it should show the correlation coefficient and p-value on the chart. However it does not show those values on mine. Any advice? thanks. import seaborn as sns sns.set(style="darkgrid", color_codes=True) sns.jointplot('Num of A', ' Ratio B', data = data_df, kind='reg', height=8) plt.show()
downvote count: 1
has comment: http://stackoverflow.com/comment/91187451
favorite count: 0

http://stackoverflow.com/q/52212326
linked to: http://stackoverflow.com/q/25022661
score: 3
upvote count: 3
tagged with: matplotlib
has title: Add blur to patch outline in matplotlib?
type: Question
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52212422
has body: I am plotting a regular patch in matplotlib, defining an area. However, there is uncertainty around the edges of this area. i would like to add 'blur'. By brute-forcing it I did it one way - sliced the shape along the x-direction and constructed segments of sub-patches, each with their custom facealpha. I could do this by slicing in 2D and then adjusting facealpha with a more convoluted algorithm. Any simpler ideas?
has comment: http://stackoverflow.com/comment/91374076
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91379417
has text: You are surprised that `tuple` has a `__getitem__` but object does not? Is that the question?
score: 2
comment on: http://stackoverflow.com/q/52215085
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91225777
has text: Your question is broad. Can you show us what you've tried so far and where precisely you got stuck? You can [edit your question](https://stackoverflow.com/posts/52138064/edit) to do this. Also see [mcve].
comment on: http://stackoverflow.com/q/52138064
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52167337
has answer: http://stackoverflow.com/a/52167424
accepted answer: http://stackoverflow.com/a/52167497
linked to: http://stackoverflow.com/q/715417
upvote count: 4
possible better answer: http://stackoverflow.com/a/52167424
type: AnsweredQuestion
downvote count: 0
duplicate of: http://stackoverflow.com/q/715417
favorite count: 0
type: Question
tagged with: python
has title: What is the most Pythonic way to convert 0 and 1 strings to boolean?
score: 4
answer count: 2
has answer: http://stackoverflow.com/a/52167497
has body: I’m reading a value from a General Purpose IO (GPIO) configured as Input and it returns a string that is either 0 or 1. I see two easy ways to convertiing it to boolean: bool(int(input_value)) or not not int(input_value) Which is most Pythonic? Are there more Pythonic ways then the ones presented above?

http://stackoverflow.com/q/52229621
accepted answer: http://stackoverflow.com/a/52229922
has comment: http://stackoverflow.com/comment/91408972
type: Question
possible better answer: http://stackoverflow.com/a/52229916
has answer: http://stackoverflow.com/a/52229916
tagged with: server
score: 0
answer count: 2
tagged with: client
has answer: http://stackoverflow.com/a/52229922
has title: Python: Close socket after specific time whether the client connected to it or not
tagged with: sockets
tagged with: python
type: AnsweredQuestion
has body: First off, Im a python beginner, so I'm not really experienced. This is the code for my server - client program: import getpass from requests import get import os import thread import socket import sys os.system('cls' if os.name == 'nt' else 'clear') print '\033[91mMCP CONTROLLER\033[0m' print ('--------------------------------------') print ('Welcome back,' + getpass.getuser()) print ('--------------------------------------') ip = get('https://api.ipify.org').text print ('Your current external IP is: ' + ip) print ('--------------------------------------') HOST = 'localhost' PORT = 1979 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created!' try: s.bind((HOST, PORT)) except socket.error as msg: print 'lul' sys.exit() print 'Socket bind complete' s.listen(20) print 'Listening...' while 1: conn, addr = s.accept() print 'Client connected: ' + addr[0] + ':' + str(addr[1]) msg = conn.recv(1024) print (msg) s.close() print ('Please enter command') My problem is: I want the program to stop the socket after 20 seconds and do "print('Please enter command')" whether someone connects to it or not. If I start the program now it just says "Listening..." (if I don't start the client) forever and the only option I have is to close the terminal window. But I want the program to move on after 20 seconds. And I also want it to say some special message if it didn't get any connection after 20 seconds (like print 'no client available') Please pardon my bad english.
has comment: http://stackoverflow.com/comment/91408939

http://stackoverflow.com/q/52266943
tagged with: python
tagged with: tweepy
has comment: http://stackoverflow.com/comment/91481787
score: 0
tagged with: twitter
tagged with: traceback
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91481861
has body: So I am relatively new to Python and don't know a ton about programming in general. I've been trying to just write a stupid meme twitter bot that me and my friends thought of as a joke. But I just wanted to see if I could get it running. And of course I can't. And I'm having trouble understanding how to handle a traceback error based on documentation and forum posts alone. I am running python 3.7 in Pycharm on Windows, if any of this makes any difference. Will update with details as asked/needed. Up until this point I've tried: -Removing other Java interpreter versions. -Uninstalling and reinstalling tweepy using pip. -Maybe some other stuff can't quite remember but these being the main things I tried. Code shown here: import random import tweepy consumer_key = 'Insert Consumer Key' consumer_secret = 'Insert Consumer Secret' access_token = 'Access Token Goes Here' access_token_secret = 'access token secret goes here' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) chance = random.randint(1, 1001) def powder(num=chance / 100): if num == 0.01: api.update_status("*Special 0.01% chance tweet* I have a better monitor so I should be better at tekken.") print("*Special 0.01% chance tweet* I have a better monitor so I should be better at tekken.") elif num &lt;= 27.3: api.update_status("Hmmm. That's a lot of powder.") print("Hmmm. That's a lot of powder.") else: api.update_status("Yes.") print("Yes.") powder() And the error thrown looks like this: C:\Users\colem\AppData\Local\Programs\Python\Python37\python.exe C:/Users/colem/PycharmProjects/Playground/powder.py Traceback (most recent call last): File "C:/Users/colem/PycharmProjects/Playground/powder.py", line 29, in &lt;module&gt; powder() File "C:/Users/colem/PycharmProjects/Playground/powder.py", line 22, in powder api.update_status("Hmmm. That's a lot of powder.") File "C:\Users\colem\AppData\Local\Programs\Python\Python37\lib\site…
has title: Tweepy throwing traceback errors?
type: Question

http://stackoverflow.com/comment/91303025
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52176199
has text: @ShpielMeister With Python's modules this isn't a big trouble because `sqrt` doesn't interfere with `math.sqrt`.
score: 0

http://stackoverflow.com/comment/91285059
comment on: http://stackoverflow.com/q/52167284
has text: I think the point is that you should have been able to find this answer (as graciously posted for you by Martin Stone below) for yourself with the same or less effort than posting this question.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91230401
type: AnswerComment
has text: Timir, that 'works' just had to convert the string to bytes first, see my second answer
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52140207

http://stackoverflow.com/a/52241893
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52241853
type: Answer
accepted answer of: http://stackoverflow.com/q/52241853
has comment: http://stackoverflow.com/comment/91435427
has body: You've got U+2212 MINUS SIGN characters in your file, not the U+002D HYPHEN-MINUS people usually think of as the minus sign character. genfromtxt doesn't handle that character. Replace the minus sign characters with hyphen-minuses before trying to parse the data.

http://stackoverflow.com/q/52186640
has answer: http://stackoverflow.com/a/52187413
upvote count: 1
has title: For some reason it is only displaying one if statement
favorite count: 0
tagged with: tkinter
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52187624
possible better answer: http://stackoverflow.com/a/52187413
type: AnsweredQuestion
score: 1
type: Question
has answer: http://stackoverflow.com/a/52187624
has body: from tkinter import * import random easy = ['A','V','M','P','O','E'] random.shuffle(easy) def raise_frame(frame): frame.tkraise() root = Tk() f1 = Frame(root) f2 = Frame(root) f3 = Frame(root) f4 = Frame(root) for frame in (f1, f2, f3, f4): frame.grid(row=0, column=0, sticky='news') Random = Label(f1, text=easy, bg="#00CDCD", font=("Chewy", 20)) Random.pack(side="top", fill="x", pady=20) Entryfield = Entry(f1, font=("Chewy", 22)) Entryfield.pack(pady=105) Begin = Button(f1, text='Begin', font=("Chewy", 24), bg="#00CDCD", command=lambda: Random.pack_forget() + Begin.pack_forget()) Begin.pack(side="bottom", fill="both") Submit = Button(f1, text="Submit", bg="#00CDCD", font=("Chewy", 24), command=lambda: winlose()) Submit.pack(fill="x", side="bottom") This statement is only showing incorrect either way when I press submit, I have tried other conditions such as if not and else but still displays the same statement the code only displays the label if I use !=. def winlose(): if Entryfield == Random: Win = ("Your answer was correct") tts = Label(f1, text=Win, font=('Chewy', 20), bg="#00CDCD") tts.pack() else: L = ("Your answer is wrong") ttr = Label(f1, text=L, font=('Chewy', 20), bg="#00CDCD") ttr.pack() raise_frame(f1) root.geometry("800x400") root.mainloop()
answer count: 2

http://stackoverflow.com/q/52147687
tagged with: python
has comment: http://stackoverflow.com/comment/91355157
answer count: 0
type: UnansweredQuestion
tagged with: openpyxl
upvote count: 1
downvote count: 1
tagged with: excel
has title: other worksheet format gets ruined using openpyxl
has comment: http://stackoverflow.com/comment/91293034
has comment: http://stackoverflow.com/comment/91255479
has body: I am new to python, I am trying to write a very simple python script that will clean my excel file. The problem is that, when I run the code, the formatting of cells on other sheet(Sheet2) that is not in anyway related to the previous sheet (that the code modifies) gets ruined. i am using a portable version of WinPython 3.4.4. Below, I have this script that clears the contents of Sheet1: from openpyxl import load_workbook, workbook wb = load_workbook('sample.xlsx') sh = wb['Sheet1'] for row in sh['B1:C10']: for cell in row: print(cell.value) cell.value = None wb.save('sample.xlsx') Thank you in advance. EDIT Sorry if my question was confusing. Please see the link for sample files. Thank you. Sample file before and after running the python script Hi Charlie, Thanks for checking on my post. From the attached sample files, you will see that in sample before.xlsx Sheet2 ‘A2’, it has 12:00:00 AM and Sheet4 E, G and H columns have borders. After running the above script, we now have the sample after.xlsx, Sheet 1 and 2 ‘A2 ‘ now has -1 value and Sheet 4 E, G and H Columns do not have borders. I have been trying to play around with this since the day I posted this question but the only thing that I could do is to just format the cells again. But still, my question is, why does this simple code affect the other sheet when it is only intended to modify a specific sheet which is Sheet1.
type: Question
favorite count: 0
score: 0

http://stackoverflow.com/a/52204823
type: Answer
answers question: http://stackoverflow.com/q/52204336
score: 2
has comment: http://stackoverflow.com/comment/91394041
upvote count: 2
has body: I think the following regexes should work fine: mobile = re.findall('mobile([0-9]*)', ex1.replace(" ",""))[0] fax = re.findall('fax([0-9]*)', ex1.replace(" ",""))[0] phone = re.findall('phone([0-9]*)', ex1.replace(" ",""))[0]
downvote count: 0

http://stackoverflow.com/comment/91299923
type: AnswerComment
score: 0
type: Comment
has text: "Could you maybe share your approach to this problem? Would appreciate your inputs" not going to answer on questions where there is bad example data (image).
comment on: http://stackoverflow.com/a/52174301

http://stackoverflow.com/comment/91404593
has text: Yes, so don't do that. It simply isn't (or shouldn't be) the responsibility of `swipe` to detect this kind of thing. If the caller wants a series of 1s, they should be explicit instead of expecting `swipe` to turn `1` into such a series.
type: Comment
comment on: http://stackoverflow.com/q/52227101
type: QuestionComment
score: 0

http://stackoverflow.com/a/52143038
type: AcceptedAnswer
has body: I was trying to think about the more general problem, where you could have any value from 0 to 255 present in each band, or even more than 3 bands... We can encode the positions of 0's and 255's by applying a different bit shift to each column (0 to 3 bits for zeros in columns 0, 1, and/or 2, and 4 to 6 bits for 255's in columns 0, 1 and/or 2): a = (im == 0) &lt;&lt; numpy.array([0,1,2], numpy.uint8) a += (im == 255) &lt;&lt; numpy.array([3,4,5], numpy.uint8) The sum along the last axis then uniquely encodes the classes. The division by 7 is not necessary, it just gives simpler class labels. numpy.add.reduce(a, -1) // 7 From there it is a standard 1:1 map to re-label the classes. I think for larger images, or large numbers of images, this approach may be faster. To see how this works: 0,0,0 = 1&lt;&lt;0 + 1&lt;&lt;1 + 1&lt;&lt;2 + 0&lt;&lt;3 + 0&lt;&lt;4 + 0&lt;&lt;5 = 7, /7 = 1 0,0,255 = 1&lt;&lt;0 + 1&lt;&lt;1 + 0&lt;&lt;2 + 0&lt;&lt;3 + 0&lt;&lt;4 + 1&lt;&lt;5 = 35, /7 = 5 0,255,255 = 1&lt;&lt;0 + 0&lt;&lt;1 + 0&lt;&lt;2 + 0&lt;&lt;3 + 1&lt;&lt;4 + 1&lt;&lt;5 = 49, /7 = 7 255,255,255 = 0&lt;&lt;0 + 0&lt;&lt;1 + 0&lt;&lt;2 + 1&lt;&lt;3 + 1&lt;&lt;4 + 1&lt;&lt;5 = 56, /7 = 8 etc... An equivalent formulation is: a = (im == 0) * numpy.array([1,2,4], numpy.uint8) a += (im == 255) * numpy.array([8,16,32], numpy.uint8) numpy.add.reduce(a, -1) //7
type: Answer
answers question: http://stackoverflow.com/q/52123180
accepted answer of: http://stackoverflow.com/q/52123180
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/a/52154658
has comment: http://stackoverflow.com/comment/91265411
has comment: http://stackoverflow.com/comment/91265497
upvote count: 1
has comment: http://stackoverflow.com/comment/91265866
type: AcceptedAnswer
type: Answer
has body: DF is defined as a list, and [DF] thus is a list of lists, which cannot be concatenated as the error states. If I understand the logic correctly, here's what you should be doing: filenames = [ f'C:/Users/Jangsu/Desktop/Sample data{i}.csv' for i in range(1, 4) ] df = pd.concat( map(pd.read_csv, filenames), axis=1, ignore_index=False )
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52154593
answers question: http://stackoverflow.com/q/52154593

http://stackoverflow.com/a/64222367
score: 8
type: Answer
downvote count: 0
upvote count: 8
has body: Solution based on plt.annotate fig = plt.figure() ax = fig.add_subplot(111) values = [7, 57, 121, 192, 123, 240, 546] labels = ['1950s', '1960s', '1970s', '1980s', '1990s', '2000s', '2010s'] plt.plot(range(len(labels)), values, 'bo') # Plotting data plt.xticks(range(len(labels)), labels) # Redefining x-axis labels for i, v in enumerate(values): ax.annotate(str(v), xy=(i,v), xytext=(-7,7), textcoords='offset points') plt.ylim(-10, 595) Output:
answers question: http://stackoverflow.com/q/52240633

http://stackoverflow.com/comment/91368960
type: Comment
comment on: http://stackoverflow.com/a/52209775
has text: Awesome! Thanks a lot!
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91488830
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52268914
has text: Thanks @Bernhard. But since they are not compulsory, i had to put that, but i understand why that won't work. That will only check the spellings if the order is already correct.
score: 0

http://stackoverflow.com/a/52124739
type: Answer
has body: Since all the recursive calls are made at the end of the function, you can use baruchel's Tail Call Optimization for Python (installed with pip install tco): from tco import with_continuations num = 10240 #Used to remove duplicates of the same prime def simplify (num,prime): if(num % prime == 0): return simplify(num/prime,prime) else: return (num,num) #used to find the prime factors @with_continuations() def pFact(num,a,b, self=None): if a == 1: return elif b == 1: print (a, "is a prime") return self((simplify (num,a))[0],(simplify (num,a))[1],a) elif a % b == 0: return self(num,b,b-1) elif a % b != 0: return self(num,a,b-1) elif b == 0: return (num,num,num-1) pFact(num,num,num-1) This outputs: 5 is a prime 2 is a prime
answers question: http://stackoverflow.com/q/52124536
score: 0

http://stackoverflow.com/q/52119162
upvote count: 2
has body: I have a tensor of shape (16, 4096, 3). I have another tensor of indices of shape (16, 32768, 3). I am trying to collect the values along dim=1. This was initially done in pytorch using gather function as shown below- # a.shape (16L, 4096L, 3L) # idx.shape (16L, 32768L, 3L) b = a.gather(1, idx) # b.shape (16L, 32768L, 3L) Please note that the size of output b is the same as that of idx. However, when I apply gather function of tensorflow, I get a completely different output. The output dimension was found mismatching as shown below- b = tf.gather(a, idx, axis=1) # b.shape (16, 16, 32768, 3, 3) I also tried using tf.gather_nd but got in vain. See below- b = tf.gather_nd(a, idx) # b.shape (16, 32768) Why am I getting different shapes of tensors? I want to get the tensor of the same shape as calculated by pytorch. How to achieve the same result as given by pytorch?
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91361657
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52123787
score: 2
tagged with: pytorch
tagged with: tensorflow
type: Question
has title: Different behavior of gather() function as seen in tensorflow and pytorch

http://stackoverflow.com/comment/91276474
type: Comment
comment on: http://stackoverflow.com/a/52163319
has text: Result is exactly what i want. But, what is row.split. Row is unknown here ? It gives some error. Also i read rows in my text file. Therefore just .split doesnot work. I should use something like that rows.read().strip().split(' '). Can you edit your code according to if i take it in a text file. Thank you.
score: 0
type: AnswerComment

http://stackoverflow.com/a/52242165
has comment: http://stackoverflow.com/comment/91432976
has comment: http://stackoverflow.com/comment/91443749
has body: You can extract the character from the pressed key by using the char attribute of the pynput.keyboard._win32.KeyCode. In other words, in your press function, you would append key.char to the list. Also, I would avoid using list as a variable name as you may end up with unexpected results from list being the name of a built-in type in Python. def press(key): print(_list, 'pressed') if key is not keyboard.Key.space: _list.append(key.char) # &lt;-- Note: key.char elif keyboard.Key.space is key: pass elif keyboard.Key.enter is key: pass
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/123574416
has comment: http://stackoverflow.com/comment/124233067
answers question: http://stackoverflow.com/q/52241868
accepted answer of: http://stackoverflow.com/q/52241868
type: Answer

http://stackoverflow.com/a/52209639
answers question: http://stackoverflow.com/q/52209356
has body: numpy.eye v = df.iloc[:, 1:].values i = np.eye(3, dtype=np.int64) a = v.argmax(1) df.iloc[:, 1:] = i[a] df id level1 level2 level3 0 1 0 1 0 1 2 0 0 1 2 3 0 1 0 3 4 0 0 1 4 5 1 0 0 cumsum and mask df.set_index('id').pipe( lambda d: d.mask(d.cumsum(1) &gt; 1, 0) ).reset_index() id level1 level2 level3 0 1 0 1 0 1 2 0 0 1 2 3 0 1 0 3 4 0 0 1 4 5 1 0 0
score: 2
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/comment/91393329
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52222334
has text: How do you pass data to your server?

http://stackoverflow.com/q/52149075
upvote count: 1
tagged with: shapely
answer count: 1
has title: How can I check if a polygon contains a point?
favorite count: 0
accepted answer: http://stackoverflow.com/a/52149076
tagged with: python
type: AnsweredQuestion
has body: Suppose I have from shapely.geometry import Polygon, Point polygon = Polygon(((0, 0), (0, 1), (1, 1), (0.5, 0.5), (1, 0))) point = Point(0, 1) How can I check if point is inside polygon?
has answer: http://stackoverflow.com/a/52149076
downvote count: 0
score: 1
type: Question

http://stackoverflow.com/comment/91345312
type: QuestionComment
score: 0
has text: Please update the question with the code you use to populate the table with the data that is coming from the API.
comment on: http://stackoverflow.com/q/52197487
type: Comment

http://stackoverflow.com/q/52163770
answer count: 1
score: 1
favorite count: 0
tagged with: storage
has body: I'm having issues downloading files on my google bucket I followed this Google tutorial(using a client library &amp; service account) Here is the python code I use (from google example) : import json from httplib2 import Http from oauth2client.client import SignedJwtAssertionCredentials from apiclient.discovery import build client_email = 'myclientname@myproject.iam.gserviceaccount.com' json_file = 'resources/Google/myproject-anumber.json' ## &lt;---- JSON provided when i created the service account cloud_storage_bucket = 'mybucketname' report_to_download = 'path/to/my/file.zip' private_key = json.loads(open(json_file).read())['private_key'] credentials = SignedJwtAssertionCredentials(client_email, private_key, 'https://www.googleapis.com/auth/devstorage.read_only') storage = build('storage', 'v1', http=credentials.authorize(Http())) report = storage.objects().get(bucket = cloud_storage_bucket, object = report_to_download).execute() I thought i would have then to output 'report' to a file, but no, as described here, report is only a dict object : https://google-api-client-libraries.appspot.com/documentation/storage/v1beta2/python/latest/storage_v1beta2.objectAccessControls.html#get I tried then to use the selfLink attribute or mediaLink, but with no success. Same for 'https://cloud.google.com/storage/docs/json_api/v1/objects/get' which returns the ACL aswell Thank you in advance,
type: UnansweredQuestion
tagged with: python
upvote count: 2
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52169216
has title: Download files from google bucket
tagged with: google-cloud-storage
tagged with: oauth2client
tagged with: api

http://stackoverflow.com/a/52954757
has comment: http://stackoverflow.com/comment/112268894
score: 2
answers question: http://stackoverflow.com/q/52170658
accepted answer of: http://stackoverflow.com/q/52170658
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: I faced the same problem, all the operations on the given post showed the same error, finally got this code to change the port number: from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": import os HOST = os.environ.get('SERVER_HOST', 'localhost') try: PORT = int(os.environ.get('SERVER_PORT', '5555')) except ValueError: PORT = 5555 app.run(HOST, PORT) my port number was previously set to 5000 by default now I changed it to 5555, u can change it to any port number
type: Answer
has comment: http://stackoverflow.com/comment/114419863

http://stackoverflow.com/comment/91228353
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52138966
type: Comment
has text: @9291Sam, you also can have your program parse the file and insert data there. It's impossible to edit the file like you're trying here because Python files are _text_, not objects or anything like that.

http://stackoverflow.com/q/52158448
type: AnsweredQuestion
has title: Can't Import Keras from Tensorflow library in Python
score: -1
has comment: http://stackoverflow.com/comment/91280454
tagged with: tensorflow
linked to: http://stackoverflow.com/q/47262955
has comment: http://stackoverflow.com/comment/91280208
type: Question
tagged with: python-import
downvote count: 2
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/52158956
accepted answer: http://stackoverflow.com/a/52158956
has comment: http://stackoverflow.com/comment/91269123
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/52165475
has comment: http://stackoverflow.com/comment/91266996
has body: I've been trying to import keras from tensorflow using the following statement: import tensorflow as tf from tensorflow import keras Tensorflow has been updated, it should work as far as I know but I still get the following message: from tensorflow import keras ImportError: cannot import name 'keras' from 'tensorflow'(/Users/gabork/PycharmProjects/Tester/venv/lib/python3.7/site-packages/tensorflow/__init__.py) SOLUTION: I was using Python 3.7 which seems like recent TensorFlow versions do not support and on the other hand, older versions of TensorFlow do not support Keras. For now I’ll either downgrade Python or just import keras.
has comment: http://stackoverflow.com/comment/91267756
possible better answer: http://stackoverflow.com/a/52165475
tagged with: pycharm
tagged with: python

discord.py
tags question: http://stackoverflow.com/q/52121740
tags question: http://stackoverflow.com/q/52257398
tags question: http://stackoverflow.com/q/52156924
tags question: http://stackoverflow.com/q/52215002
tags question: http://stackoverflow.com/q/52153246
tags question: http://stackoverflow.com/q/52155265
tags question: http://stackoverflow.com/q/52190862
tags question: http://stackoverflow.com/q/52236001
tags question: http://stackoverflow.com/q/52257249
tags question: http://stackoverflow.com/q/52191882
tags question: http://stackoverflow.com/q/52154168
tags question: http://stackoverflow.com/q/52139809
tags question: http://stackoverflow.com/q/52173801
tags question: http://stackoverflow.com/q/52266886
tags question: http://stackoverflow.com/q/52177907
tags question: http://stackoverflow.com/q/52247301
tags question: http://stackoverflow.com/q/52156410
tags question: http://stackoverflow.com/q/52210855
tags question: http://stackoverflow.com/q/52176124
tags question: http://stackoverflow.com/q/52131921
tags question: http://stackoverflow.com/q/52169896
tags question: http://stackoverflow.com/q/52249107
tags question: http://stackoverflow.com/q/52246205
tags question: http://stackoverflow.com/q/52223722
tags question: http://stackoverflow.com/q/52206819
tags question: http://stackoverflow.com/q/52129545
tags question: http://stackoverflow.com/q/52206940
tags question: http://stackoverflow.com/q/52241075
tags question: http://stackoverflow.com/q/52139457
type: Tag
tags question: http://stackoverflow.com/q/52188112
tags question: http://stackoverflow.com/q/52241051
tags question: http://stackoverflow.com/q/52173676
tags question: http://stackoverflow.com/q/52125432
tags question: http://stackoverflow.com/q/52252695
tags question: http://stackoverflow.com/q/52142539
tags question: http://stackoverflow.com/q/52232177
tags question: http://stackoverflow.com/q/52193942
tag name: discord.py
tags question: http://stackoverflow.com/q/52132913
tags question: http://stackoverflow.com/q/52154647
tags question: http://stackoverflow.com/q/52194212
tags question: http://stackoverflow.com/q/52215217
tags question: http://stackoverflow.com/q/52225311

http://stackoverflow.com/q/52184338
upvote count: 1
accepted answer: http://stackoverflow.com/a/52184469
favorite count: 0
has answer: http://stackoverflow.com/a/52184469
tagged with: python
has answer: http://stackoverflow.com/a/52184633
has body: There are a lot of stations in csv file, I don't know how to use loop to count the number of nan of every station. There is I got so far, count one by one. Can someone help me please, thank you in advance. station1= train_df[train_df['station'] == 28079004] station1 = station1'date', 'O_3' count_nan = len(station1) - station1.count() print(count_nan)
has comment: http://stackoverflow.com/comment/91318322
possible better answer: http://stackoverflow.com/a/52184633
has comment: http://stackoverflow.com/comment/91318526
has comment: http://stackoverflow.com/comment/91318683
type: AnsweredQuestion
has title: How to use loop to count the number of nan
downvote count: 0
score: 1
tagged with: loops
type: Question
answer count: 2

http://stackoverflow.com/comment/91403238
type: QuestionComment
comment on: http://stackoverflow.com/q/52226782
has text: Please add information by [edit]ing your question, instead of hiding in comments.
score: 0
type: Comment

http://stackoverflow.com/q/52118908
has comment: http://stackoverflow.com/comment/91189006
tagged with: python
has comment: http://stackoverflow.com/comment/91188904
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91190523
has comment: http://stackoverflow.com/comment/91189395
has answer: http://stackoverflow.com/a/52119248
has comment: http://stackoverflow.com/comment/91188649
type: Question
has comment: http://stackoverflow.com/comment/91191222
tagged with: group-by
has comment: http://stackoverflow.com/comment/91191053
has body: I am trying to sort within multiple levels of a groupby multi-index dataframe based on an aggregated value. For an idea of what I'm talking about: I have a hierarchal data set that is then grouped on multiple levels. I then aggregate and sum a certain measure on them. I then want to rank them within each other. At level 0, values should be ranked in descending based on sum of said measure. Then within level 1, values should be ranked in descending order again based on sum of said measure, level 2 and so on.. After a groupby, how do I sort at every level? I know not providing an example is tough, but if I could be pointed in the right direction that'd be great, thanks EDIT: Original Data: pd.DataFrame(data=[['a','car',6], ['a','bike',7], ['a','car',8], ['b','bike',9], ['b','car',10], ['b','bike',11]], columns=['a', 'b', 'c']) Groupby: df.groupby(['a','b']).agg({'c':'sum'}) Desired Output after resetting index: pd.DataFrame(data=[['b','bike',20], ['b','car',10], ['a','car',14], ['a','bike',7]], columns=['a', 'b', 'c'])
answer count: 1
has comment: http://stackoverflow.com/comment/91190393
has title: Pandas ranking within multiple groupby levels
tagged with: pandas

http://stackoverflow.com/a/59901821
has body: I had the same problem with django and I solved it by clearing the chrome cache
score: 0
answers question: http://stackoverflow.com/q/52225721
type: Answer
has comment: http://stackoverflow.com/comment/105931268

datepicker
tags question: http://stackoverflow.com/q/52249082
tag name: datepicker
type: Tag

http://stackoverflow.com/comment/91193250
has text: @Bazingaa But this is clearly a numpy array, so why show the OP how to flatten without using numpy instead of just calling `flatten` on it?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52120904
score: 0

http://stackoverflow.com/a/52325144
type: Answer
has comment: http://stackoverflow.com/comment/95278891
has body: PyInstaller is a powerful opensource tool for cross-platform deployment/distribution of python project. *Note: Although I have no experience on distributing Jupyter Notebook with PyInstaller, but it seems to be plausible with this guide. Install through pypi: pip install pyinstaller Distribution of code without console can be as simple as: pyinstaller --noconsole script.py Then you can find your .exe(Window) under dist folder of your working directory.
upvote count: 5
score: 5
answers question: http://stackoverflow.com/q/52187362
downvote count: 0

http://stackoverflow.com/a/52128234
answers question: http://stackoverflow.com/q/52113140
upvote count: 2
type: Answer
has body: As many classes in NetworKit, both PLP and PLM include a run() method that executes the algorithm and you need to invoke it before getting the result. Also, there is no need to use the toString() method to get the community structure; you can use the getPartition() method (included in both PLP and PLM, see the documentation) which returns a Partition object that represents the community structure (you can find the documentation of Partition here). See below for a simple example: from networkit import * # In this example I generate a graph with a random community structure. # In your code use your own graph. g = generators.ClusteredRandomGraphGenerator(100, 10, 0.5, 0.01).generate() # Creating an instance of PLP and running the algorithm. # Use community.PLM(g) to run the PLM algorithm. plp = community.PLP(g).run() # Getting the Partition object. plpPartition = plp.getPartition() # Getting the community IDs. plpCommunityIDs = plpPartition.getSubsetIds() # Getting the community ID of each node of the graph g. plpCommunities = plpPartition.getVector() Each community is associated with a unique integer id, and each node is associated to a community id. plpCommunityIDs is a set that contains all the community ids, while plpCommunities is a vector of size n (number of nodes of the graph) that contains the community id of each node (for example, use c = plpCommunities[v] to store in c the community id of node v).
score: 2
downvote count: 0

hive
tags question: http://stackoverflow.com/q/52129192
tags question: http://stackoverflow.com/q/52241312
tags question: http://stackoverflow.com/q/52220307
tags question: http://stackoverflow.com/q/52133285
type: Tag
tag name: hive

python-internals
tags question: http://stackoverflow.com/q/52262686
tag name: python-internals
tags question: http://stackoverflow.com/q/52140641
tags question: http://stackoverflow.com/q/52125009
tags question: http://stackoverflow.com/q/52268262
type: Tag
tags question: http://stackoverflow.com/q/52140811
tags question: http://stackoverflow.com/q/52131289
tags question: http://stackoverflow.com/q/52201848
tags question: http://stackoverflow.com/q/52141149

http://stackoverflow.com/a/52207092
downvote count: 0
answers question: http://stackoverflow.com/q/52207014
type: Answer
upvote count: 3
score: 3
has body: If I understand correctly, Try using shift, then loc to find where 'index' is in column A: df.shift().loc[df.A=='index','A'].tolist() ['a', 'b', 'c']

http://stackoverflow.com/comment/91445113
comment on: http://stackoverflow.com/q/52248391
has text: @WillemVanOnsem I was under the impression that \n in a string leads to a new line being triggered when that string is printed & that the \n in e.g. "exam\nple" is just a string and nothing else.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91187839
score: 0
has text: Are the special characters always at the end?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52118382

http://stackoverflow.com/comment/91217132
type: AnswerComment
type: Comment
score: 2
has text: You should use `super`, otherwise any inheritance will be broken.
comment on: http://stackoverflow.com/a/52133323

http://stackoverflow.com/a/52153124
answers question: http://stackoverflow.com/q/52153037
has comment: http://stackoverflow.com/comment/139796950
upvote count: 35
type: AcceptedAnswer
downvote count: 0
score: 35
has body: Due to the integration of tqdm with pandas you can use progress_map function instead of map function. Note: for this to work you should add tqdm.pandas() line to your code. So try this: from tqdm import tqdm def example(x): x = x + 2 return x tqdm.pandas() # &lt;- added this line if __name__ == '__main__': dframe = pd.DataFrame([{'a':1, 'b': 1}, {'a':2, 'b': 2}, {'a':3, 'b': 3}]) dframe['b'] = dframe['b'].progress_map(example) # &lt;- progress_map here Here is the documentation reference: (after adding tqdm.pandas()) ... you can use progress_apply instead of apply and progress_map instead of map
type: Answer
accepted answer of: http://stackoverflow.com/q/52153037

http://stackoverflow.com/q/52156945
upvote count: 2
score: 0
downvote count: 2
answer count: 1
tagged with: jquery
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Can I add a Flask server to an existing Node web app?
tagged with: http
type: Question
has answer: http://stackoverflow.com/a/52157309
tagged with: javascript
has comment: http://stackoverflow.com/comment/91273248
has body: I've got a web app and some Python scripts I'd like to run on some inputted text. I looked around and it seems like Flask is the best solution for this, but wouldn't this mean I'd have two web servers? So would I be starting the Flask server when the user submits some text, running the Python script, then stopping the Flask server? How would I do this? The app is JS/jQuery. The other solution looks to be rewriting the Python into JavaScript which naturally I'm hesitant to do.
tagged with: flask

http://stackoverflow.com/a/52207270
downvote count: 0
has body: The str representation of a User (including Members) will be their username (not their server-specific nickname), and the discriminator (used to tell people with the same username apart). if str(ctx.message.author) == "foo#3465": ... That said, you should be checking against ids, as it is possible for a person to change their Discord username. ids are strings in the async branch of discord.py and integers in discord.py-rewrite
score: 5
type: Answer
answers question: http://stackoverflow.com/q/52206940
upvote count: 5

http://stackoverflow.com/q/52193545
upvote count: 3
tagged with: image-processing
has body: I know my question might sound a little generic but I read a lot of blogs and questions about this and still can't find a solution that get any close to what I'm trying to do. I have the attached sample IG screenshot. My goal is to get the coordinates of the elements I highlighted in green. Canny edges doesn't seem to do a thing (see also https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_canny/py_canny.html). I read Houg Transform could have helped (https://pysource.com/2018/03/07/lines-detection-with-hough-transform-opencv-3-4-with-python-3-tutorial-21/) but still no luck. All I would need is a way to get those sections and get their coordinates. If somebody could simply point me out to what technique(s) could help me, that would be helpful.
type: Question
has answer: http://stackoverflow.com/a/52193819
has comment: http://stackoverflow.com/comment/91336897
has comment: http://stackoverflow.com/comment/91337344
downvote count: 0
answer count: 3
has title: Python OpenCV - get coordinates of borders of elements inside an image
favorite count: 0
has answer: http://stackoverflow.com/a/66276439
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52193944
tagged with: opencv
score: 3

http://stackoverflow.com/comment/91187779
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52118391
has text: You are `return`ing after the first iteration.
score: 2

http://stackoverflow.com/q/52255582
answer count: 3
type: UnansweredQuestion
has title: python jupyter magic %%writefile returns SyntaxError: invalid syntax
tagged with: python
has body: # [ ] The following program asks the user for a circle radius then display the area and circumference # Modify the program so it only displays the information when executed directly # The program should not display anything if it is imported as a module %%writefile main_script.py def main(): from math import pi def circle_area(r): return pi * (r ** 2) def circle_circumference(r): return 2 * pi * r radius = float(input("Enter radius: ")) print("Area =", circle_area(radius)) print("Circumference =", circle_circumference(radius)) if __name__="__main__": main() ---------- File "&lt;ipython-input-3-70ba6a5d5e98&gt;", line 6 %%writefile main_script.py ^ SyntaxError: invalid syntax How do I fix this?? Its an exercise, but I just dont get how this system command works,can you explain? ignore:for word requirements ignore:for word requirements
tagged with: jupyter
tagged with: jupyter-notebook
linked to: http://stackoverflow.com/q/36520723
upvote count: 3
type: Question
score: 3
has answer: http://stackoverflow.com/a/52256544
has answer: http://stackoverflow.com/a/53547749
has answer: http://stackoverflow.com/a/52335818
tagged with: writefile
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/97319136

http://stackoverflow.com/a/52264091
type: Answer
score: 2
has body: The groupby is adding an index level that is getting in your way. rs = df.groupby('group').value.rolling(2).sum() df.assign(rolling_sum=rs.reset_index(level=0, drop=True)) date group value value_useless rolling_sum 0 2018-01-01 a 1 2 NaN 1 2018-01-01 a 2 2 3.0 2 2018-01-01 b 3 2 NaN 3 2018-01-01 b 4 2 7.0 details rs # Annoying Index Level # | # v # group # a 0 NaN # 1 3.0 # b 2 NaN # 3 7.0 # Name: value, dtype: float64 Alternatively, you can get around the added index by using pd.concat df.assign(rolling_sum=pd.concat(s.rolling(2).sum() for _, s in df.groupby('group').value)) date group value value_useless rolling_sum 0 2018-01-01 a 1 2 NaN 1 2018-01-01 a 2 2 3.0 2 2018-01-01 b 3 2 NaN 3 2018-01-01 b 4 2 7.0
answers question: http://stackoverflow.com/q/52264035
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52264035
upvote count: 2

http://stackoverflow.com/comment/91245755
type: QuestionComment
comment on: http://stackoverflow.com/q/52147901
score: 1
has text: What do you think is being changed here? Both `i` and `a` will be unchanged.
type: Comment

http://stackoverflow.com/comment/91415849
has text: As @Amit Jain pointed out, if you check the website, the first and last two rows do not have any data. So you need to run this `rows=rows[2:-2]` before going over your for loop. Hope it helps
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52217388

http://stackoverflow.com/comment/91200886
type: QuestionComment
type: Comment
score: 0
has text: This may be a bug with autopep8. Have you checked their issue tracker on github? https://github.com/hhatto/autopep8/issues
comment on: http://stackoverflow.com/q/52124940

http://stackoverflow.com/comment/91489378
type: AnswerComment
comment on: http://stackoverflow.com/a/52271046
type: Comment
has text: I added #!/usr/bin/env python #-*- coding: utf-8 -*- at the beginning of the file, still nothing, will check that answer now
score: 0

http://stackoverflow.com/q/52122119
type: UnansweredQuestion
has title: Create Database using Python on Jupyter Notebook
upvote count: 1
downvote count: 1
tagged with: excel
type: Question
tagged with: database
has answer: http://stackoverflow.com/a/52122268
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52122280
tagged with: pandas
has answer: http://stackoverflow.com/a/60449322
favorite count: 0
has comment: http://stackoverflow.com/comment/91195647
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: so i am building a database for a larger program and do not have much experience in this area of coding (mostly embedded system programming). My task is to import a large excel file into python. It is large so i'm assuming I must convert it to a CSV then truncate it by parsing and then partitioning and then import to avoid my computer crashing. Once the file is imported i must be able to extract/search specific information based on the column titles. There are other user interactive aspects that are simply string based so not very difficult. As for the rest, I am getting the picture but would like a more efficient and specific design. Can anyone offer me guidance on this?

http://stackoverflow.com/comment/91442506
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52247213
has text: Its `input()` and `print("abc")` in python3 not `raw_input()` and `print "abc"`
score: 0

http://stackoverflow.com/a/52278155
has comment: http://stackoverflow.com/comment/91518666
has comment: http://stackoverflow.com/comment/91526703
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92981212
answers question: http://stackoverflow.com/q/52248985
type: Answer
accepted answer of: http://stackoverflow.com/q/52248985
has body: In cx_Freeze version 5.1.1, the included modules are in a subdirectory lib of the build directory. The manually added DLLs apparently need to be moved there as well. You can do this with the following modification of your setup.py script: options = { 'build_exe': { 'packages': packages, 'include_files': [ (os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'), os.path.join('lib', 'tk86t.dll')), (os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll'), os.path.join('lib', 'tcl86t.dll')), (os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'sqlite3.dll'), os.path.join('lib', 'sqlite3.dll')) ], }, } I'm actually not sure whether sqlite3.dll also needs to be moved to lib. Your question is interesting in view of the fact that it seems to indicate an import conflict between pandas and tkinter. That's presumably why you get a different error message than reported in this question: Getting "ImportError: DLL load failed: The specified module could not be found" when using cx_Freeze even with tcl86t.dll and tk86t.dll added in EDIT: I manage to freeze and run the OP's example script main.py without errors using Python 3.6.5 on Windows 7 with the following configuration idna 2.7 (installed with pip) numpy 1.14.3+mkl (installed using Gohlke's binaries) pandas 0.23.4 (installed with pip) cx_Freeze 5.1.1 (installed with pip) I use the following setup.py script: import os import sys from cx_Freeze import setup, Executable PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__)) os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6') os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6') base = None if sys.platform == "win32": base = "Win32GUI" executables = [Executable("main.py", base=base)] packages = ["idna", "os", "numpy", "importlib", "pandas"] options = { 'build_exe': { 'packages': packages, 'include_files': [ (os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'), os.path.join('lib', 'tk86t.dll')), (os.path.join(PYTHON_INSTALL_DIR, 'D…
score: 1
upvote count: 1

http://stackoverflow.com/q/52113425
tagged with: variables
has answer: http://stackoverflow.com/a/52113490
has body: Sorry I am new to python and I think I have seen someone, somewhere do something that resembled the following: hiddenLayerinput = { units=64, activation='relu', input_dim=5 } There is a syntax error at the = of units=64, Can I do that? And if yes, do you know whats wrong? Thank you for any help I am using Jupyter notebooks running python 3
tagged with: python
has answer: http://stackoverflow.com/a/52113518
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52113480
has comment: http://stackoverflow.com/comment/91177411
has answer: http://stackoverflow.com/a/52113480
has title: Defining multiple variables inside one
type: Question
accepted answer: http://stackoverflow.com/a/52113490
score: 0
answer count: 3

http://stackoverflow.com/a/52200592
has body: It appears as though the program simply reads the file that is passed into the command line argument. The program functions and reads the file, but you need a line to tell python to print the contents of the file you are reading. Try this: import sys def openfile(filename): f = open(filename, mode='r') contents = f.read() print(contents) f.close() if __name__ == '__main__': openfile(filename=sys.argv[1]) print('script has been executed')
downvote count: 0
answers question: http://stackoverflow.com/q/52200409
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/52267926
answers question: http://stackoverflow.com/q/52267681
has body: The question per se makes not much sense, I think what you want is just a function if you do not want to print the value on assignment: def myvar(): print('nothing') Which you can call to print afterwards with myvar().
has comment: http://stackoverflow.com/comment/91483833
type: Answer
score: 0

http://stackoverflow.com/q/52203027
tagged with: python
tagged with: nosql
type: AnsweredQuestion
tagged with: pymongo
has title: pymongo : How can I get multiple results from filed in mongodb?
has body: I would like to get every 'ecg_raw' in 'data' itmes that founded by 'name' with python3 pymongo. If i know 'name' and 'time_info', How can i get 4 ecg_raw datas which time_info == '2018-09-01 00:00:03' I want to get every ecg_raw data like [[8,2],[1,10],[9,4],[1,9]] I tried db.g.find({"data":{"$elemMatch":{"time_info":"2018-09-01 00:00:03"}}},{"name":1,"data":{"$elemMatch":{"time_info":"2018-09-01 00:00:03"}}}) but it returns only one value like bottom. {'_id': ObjectId('5b90d401219e9c9f72cac8c4'), 'name': 'testDog3', 'data': [{'time_info': '2018-09-01 00:00:03', 'ecg_raw': [8, 2]}]} Please help me. &gt; db.g.find().pretty() { "_id" : ObjectId("5b90d401219e9c9f72cac8c4"), "name" : "testDog3", "data" : [ { "time_info" : "2018-09-01 00:00:03", "ecg_raw" : [ 8, 2 ] }, { "time_info" : "2018-09-01 00:00:03", "ecg_raw" : [ 1, 10 ] }, { "time_info" : "2018-09-01 00:00:03", "ecg_raw" : [ 9, 4 ] }, { "time_info" : "2018-09-01 00:00:03", "ecg_raw" : [ 1, 9 ] }, { "time_info" : "2018-09-01 00:00:04", "ecg_raw" : [ 10, 6 ] }, { "time_info" : "2018-09-01 00:00:04", "ecg_raw" : [ 1, 6 ] } ] }
type: Question
accepted answer: http://stackoverflow.com/a/52203425
score: 0
tagged with: mongodb
answer count: 1
has answer: http://stackoverflow.com/a/52203425

http://stackoverflow.com/q/52141874
has comment: http://stackoverflow.com/comment/91233782
has comment: http://stackoverflow.com/comment/91233666
score: 0
has comment: http://stackoverflow.com/comment/91234564
answer count: 1
has comment: http://stackoverflow.com/comment/91234558
has answer: http://stackoverflow.com/a/52142449
favorite count: 0
has comment: http://stackoverflow.com/comment/91234160
upvote count: 2
linked to: http://stackoverflow.com/q/5679638
downvote count: 2
has comment: http://stackoverflow.com/comment/91233762
tagged with: python
has body: I'm studying algorithms and one of the questions asks me to build an in-house calendar tool which stores data as a tuple of integers. My goal is to write a function that takes a list of multiple meeting time ranges and returns a list of condensed ranges. So far, I've written pseudo-code and some real code. However, I'm trying to append overlapping times (represented as integers) and I'm stuck. Here's what I have so far: # Variable containing list of tuples meeting_times = [(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)] # Sort meetings by start time ordered_list = sorted(meeting_times) # For each number in the variable for m in range(ordered_list): # If number overlaps with another number in variable if m[0:] &gt;= m[:-1]: # Append start time of first number to end time of last number append_meeting_time = else: # Continue on and loop through variable. While it's not complete, I'd like to know if I'm the right path. If not, how can I improve my answer?
has comment: http://stackoverflow.com/comment/91234066
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52142449
type: Question
has title: How can I append overlapping tuples in Python and list them in order?
has comment: http://stackoverflow.com/comment/91233737
tagged with: algorithm
tagged with: data-structures

http://stackoverflow.com/comment/91404018
has text: Agree, but you can related to documentation.
type: Comment
comment on: http://stackoverflow.com/a/52227136
score: 0
type: AnswerComment

http://stackoverflow.com/a/52217234
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91383828
has body: You can get details like, You have to locate number of Row available in the table without Table Header, This is Example as according to your HTML. Example using Python: rows = driver.find_elements_by_xpath("//td[@style='font-weight:bold;']//parent::tr") for row in rows: company=row.find_element_by_xpath('./td[1]').text address = row.find_element_by_xpath('./td[2]').text contact= row.find_element_by_xpath('./td[3]//a').text number= row.find_element_by_xpath('./td[5]').text Example using Java: List<WebElement> findData = driver.findElements("//td[@style='font-weight:bold;']//parent::tr"); for (WebElement webElement : findData) { String getValueofCompany = webElement.findElement(By.xpath("./td[1]")).getText(); String getValueofAddress = webElement.findElement(By.xpath("./td[2]")).getText(); String getValueofContact = webElement.findElement(By.xpath("./td[3]//a")).getText(); String getValueofPhoneNumber = webElement.findElement(By.xpath("./td[5]")).getText(); }
answers question: http://stackoverflow.com/q/52216449
type: Answer
accepted answer of: http://stackoverflow.com/q/52216449
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/91390716
has comment: http://stackoverflow.com/comment/91383731
has comment: http://stackoverflow.com/comment/91390321

http://stackoverflow.com/a/52266546
type: Answer
score: 1
has body: An alternative method is to calculate an array of non-white ItemID values. Then filter your dataframe: non_whites = df.loc[df['ItemType'].ne('White'), 'ItemID'].unique() res = df[~df['ItemID'].isin(non_whites)] print(res) ItemType ItemPrice ItemID 4 White 14 C 5 White 15 C You can also use GroupBy, but it's not absolutely necessary.
upvote count: 1
has comment: http://stackoverflow.com/comment/91482771
downvote count: 0
answers question: http://stackoverflow.com/q/52266424

http://stackoverflow.com/q/52264242
linked to: http://stackoverflow.com/q/47104547
type: UnansweredQuestion
tagged with: python
has title: How to fill between line and function in the matplotlib 3D?
score: -4
has comment: http://stackoverflow.com/comment/91476404
type: Question
tagged with: matplotlib
linked to: http://stackoverflow.com/q/16417496
tagged with: python-2.7
downvote count: 4
has answer: http://stackoverflow.com/a/52278909
upvote count: 0
has body: I have a line and a function and I need to color between they. How can I do it?
answer count: 1
favorite count: 0

http://stackoverflow.com/q/52144670
possible better answer: http://stackoverflow.com/a/69426819
has answer: http://stackoverflow.com/a/52144960
tagged with: scikit-learn
has title: fit method in Sklearn. when using KNeighborsClassifier
has comment: http://stackoverflow.com/comment/91239064
favorite count: 0
has comment: http://stackoverflow.com/comment/91239618
has comment: http://stackoverflow.com/comment/91239152
score: 0
has comment: http://stackoverflow.com/comment/91239617
tagged with: python
has comment: http://stackoverflow.com/comment/91239535
has body: from sklearn.neighbors import KNeighborsClassifier knn_clf =KNeighborsClassifier() knn_clf.fit(x_train[:92000],y_train[:92000]) #1st method call knn_clf.fit(x_train[92000:123000],y_train[92000:123000]) #2nd method call My doubt is when I call fit method like this does the 2nd call trains the model once again from scratch ? or it will add to what it has learned from the previous fit call(1st method call) ? What I am trying to achieve is to do batch wise training as laptop can't handle the data if I use the complete dataset at once! Thanks in Advance :-)
tagged with: knn
accepted answer: http://stackoverflow.com/a/52144960
tagged with: machine-learning
upvote count: 1
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/69426819
type: Question
answer count: 2

http://stackoverflow.com/q/52209389
score: 1
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/52209763
type: Question
has title: Extract multiple Elements from a JSON dict using python
downvote count: 0
answer count: 1
has body: In Python, i have my JSON formated the following way: lists = [ { "id": 1, "data": { "id": "1", "title": "Title1", "list_category": "green", "list_group": ["foo", "bar"], "tag_Number": ["One","Three","Four","Seven"], "tag_ABCD": ["B", "C", "D", "E"] } }, { "id": 2, "data": { "id": "32", "title": "Title32", "list_category": "blue", "list_group": ["foo2", "bar2"], "tag_Number": ["One","Three","Four","Seven"], "tag_ABCD": ["B", "C", "D", "E"] }, ... I want do write different funtions to extract different kind of data from these list. For example, to extract the title and id, I wrote the following funtion: def getTitle(): index_list = [] index_dict = dict() for x in checklists: val = ast.literal_eval(x["data"]) Index = dict(id= x['id'], title = val["title"]) index_dict[x['id']]=Index return index_dict My problem is, when i try to extract other values, for example tag_ABCD, I try to change my function the following way: def getTag(): index_list = [] index_dict = dict() for x in checklists: val = ast.literal_eval(x["data"]) _val = ast.literal_eval(x["val"]) Index = dict(id= x['id'], tag = _val["tag_ABCD"]) index_dict[x['id']]=Index return index_dict But it wont return the correct element. Another Problem (side question..): Why isn't it possible to return my data when i want to add a third element to the dict? def getTitle(): index_list = [] index_dict = dict() for x in checklists: val = ast.literal_eval(x["data"]) Index = dict(id= x['id'], title = val["title"], list_category = val["list_category"]) index_dict[x['id']]=Index return index_dict For every one of my variatoins, I get the same error: KeyError: 'list_category'
favorite count: 0
tagged with: python-2.7
has answer: http://stackoverflow.com/a/52209763
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91369140

http://stackoverflow.com/comment/91383921
type: Comment
type: QuestionComment
has text: Thank you a lot!
score: 0
comment on: http://stackoverflow.com/q/52216637

http://stackoverflow.com/comment/91194934
type: Comment
type: QuestionComment
has text: The problem isn't capitalizing the first letter though, is it? Look at the exepcted output in case 2; it has two capitals in the middle of the word too.
score: 4
comment on: http://stackoverflow.com/q/52121773

http://stackoverflow.com/a/52188209
type: Answer
accepted answer of: http://stackoverflow.com/q/52187510
has body: Setup user_data = { "data": [ {"display_name": "John", "id": "123"}, {"display_name": "Frank", "id": "456"}, {"display_name": "Billy", "id": "789"}]} stream_data = { "data": [ {"id": "333444", "user_id": "456", "title": "Franks Stream"}, {"id": "555666", "user_id": "789", "title": "Billys Stream"}, {"id": "111222", "user_id": "123", "title": "Johns Stream"}]} Solution Using a dictionary comprehension, you can create a new dictionary of user data keyed on the id field, and then use this data to update the stream data. new_user_data = {row.get("id"): row.get('display_name') for row in user_data['data']} &gt;&gt;&gt; new_user_data {'123': 'John', '456': 'Frank', '789': 'Billy'} Now use this dictionary to update the display_name in the data (you may wish to make a copy if you don't want to mutate the original data). for row in stream_data['data']: id_ = row.get('user_id') row['display_name'] = new_user_data[id_] &gt;&gt;&gt; stream_data['data'] [{'display_name': 'Frank', 'id': '333444', 'title': 'Franks Stream', 'user_id': '456'}, {'display_name': 'Billy', 'id': '555666', 'title': 'Billys Stream', 'user_id': '789'}, {'display_name': 'John', 'id': '111222', 'title': 'Johns Stream', 'user_id': '123'}] If you have more than one piece of user data to store as values (i.e. more than just the id as the key and display_name as the value), you could use a namedtuple to hold them. user_data = { "data": [ {"display_name": "John", "id": "123", "description": "boring"}, {"display_name": "Frank", "id": "456", "description": "smart"}, {"display_name": "Billy", "id": "789", "description": "funny"}]} from collections import namedtuple UserData = namedtuple('UserData', ('display_name', 'description')) for row in user_data['data']: id_ = row.pop('id') new_user_data[id_] = UserData(**row) for row in stream_data['data']: id_ = row.get('user_id') row.update(**new_user_data[id_].__dict__) &gt;&gt;&gt; new_user_data {'123': UserData(display_name='John', description='boring'), '456': UserData(…
answers question: http://stackoverflow.com/q/52187510
has comment: http://stackoverflow.com/comment/91328142
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91332572
comment on: http://stackoverflow.com/a/52175814
score: 0
type: AnswerComment
has text: Thanks. It did work! However, another question came up as; why we also don't write self.end_time_of_the_script for: end_time_of_the_script and self.process_time_in_seconds for : process_time_in_seconds. why it does't give any error when we don't.? –
type: Comment

http://stackoverflow.com/q/52136002
has answer: http://stackoverflow.com/a/52136221
has comment: http://stackoverflow.com/comment/91222064
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/52136106
has comment: http://stackoverflow.com/comment/91221864
score: -4
has comment: http://stackoverflow.com/comment/91221809
has comment: http://stackoverflow.com/comment/91222030
type: Question
has title: python fool-proof grade measuring
has comment: http://stackoverflow.com/comment/91221832
has comment: http://stackoverflow.com/comment/91258623
has body: def func(grades): first,*middle,last=grades try: avg=sum(middle)/len(middle) print(avg) except ZeroDivisionError: print("Atleast 3 grades must be inputed") except NameError: print("no letters are allowed in Grades") func([50,60,60,60,70,90]) func([20,a,4,40]) hello i am using this function to calculate the average of the grades in the middle(excluding first and last grade). My question is how can i improve this function to make it "fool proof" i.e (no matter what was the input the code keeps running without crashing). I tried using except: to overcome it but still NameError. *it was stated in the answers that error is caused outside the function,can this error be solved?
has answer: http://stackoverflow.com/a/52136106
answer count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/91222050
has comment: http://stackoverflow.com/comment/91223310
favorite count: 0
has comment: http://stackoverflow.com/comment/91221850
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91221863
downvote count: 5
has comment: http://stackoverflow.com/comment/91221840
has comment: http://stackoverflow.com/comment/91221878
tagged with: python
has answer: http://stackoverflow.com/a/52136064
accepted answer: http://stackoverflow.com/a/52136064

http://stackoverflow.com/comment/91320604
score: 0
type: AnswerComment
has text: hi, zipa,can you explain this part: for k, v in test.items(): value = avg0.get(k.year, (0, 0)) avg0[k.year] = (value[0] + v[0], value[1] + 1.0)
type: Comment
comment on: http://stackoverflow.com/a/52183501

http://stackoverflow.com/comment/91359178
type: Comment
type: QuestionComment
has text: by step size you mean `t` value ?
comment on: http://stackoverflow.com/q/52204231
score: 0

http://stackoverflow.com/q/52156448
type: Question
score: 0
answer count: 1
has body: let's assume the following code-snippet: page = ( E.html( E.head( E.title("This is a sample document") ), E.body( E.h1("Hello!", CLASS("title")), E.p("This is a paragraph with ", B("bold"), " text in it!"), E.p("This is another paragraph, with a ", A("link", href="http://www.python.org"), "."), E.p("Here are some reserved characters: <spam&egg>."), ET.XML(" And finally, here is an embedded XHTML fragment. "), ) ) ) Source: https://lxml.de/api/lxml.builder.ElementMaker-class.html How can I add an attribute to the -tag in the above syntax? Doing something like this: E.body(myattr="something", couldn't solve my problem. So any hints are welcome!
tagged with: lxml
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52157471
linked to: http://stackoverflow.com/q/47219957
tagged with: python
has comment: http://stackoverflow.com/comment/91274726
has title: lxml - ElementMaker: adding attributes
tagged with: http://stackoverflow.com/tag/xml

http://stackoverflow.com/comment/91318799
has text: Yes this is quite smart! :D
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52184469
type: Comment

http://stackoverflow.com/comment/106638075
has text: should notepad be launched and shown on the screen? (I have 3 monitors with win10, not sure if that is causing a constraint)
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52148059
type: AnswerComment

http://stackoverflow.com/comment/91293904
comment on: http://stackoverflow.com/a/52156851
score: 0
type: AnswerComment
type: Comment
has text: @JacobPeck Glad to have helped :)

http://stackoverflow.com/q/52232613
upvote count: 1
has comment: http://stackoverflow.com/comment/91436850
linked to: http://stackoverflow.com/q/45276984
downvote count: 3
type: Question
score: -2
tagged with: pyspark
answer count: 1
favorite count: 0
has body: I have Ubuntu 18.04.I am working with anaconda distribution for using jupyter notebooks and python.I want to install spark and pyspark to work with HDFS. I want to know the proper installation procedure for the same. Thank you
duplicate of: http://stackoverflow.com/q/45276984
tagged with: apache-spark
has title: How to install Spark with anaconda distribution on ubuntu?
has answer: http://stackoverflow.com/a/52239547
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/91235182
comment on: http://stackoverflow.com/q/52142645
has text: Did I get the question right: Half a million inserts per second into SQLite is too slow for you?
score: 1
type: Comment
type: QuestionComment

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/52150172
tags question: http://stackoverflow.com/q/52258924
tags question: http://stackoverflow.com/q/52115896
tags question: http://stackoverflow.com/q/52249755
type: Tag
tags question: http://stackoverflow.com/q/52175718
tags question: http://stackoverflow.com/q/52262056
tags question: http://stackoverflow.com/q/52142443
tags question: http://stackoverflow.com/q/52155331
tags question: http://stackoverflow.com/q/52117759

http://stackoverflow.com/q/52161453
favorite count: 0
possible better answer: http://stackoverflow.com/a/52161583
has answer: http://stackoverflow.com/a/52161583
tagged with: python
has answer: http://stackoverflow.com/a/52162559
answer count: 4
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/52162037
type: Question
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/52162037
tagged with: pandas
has title: Subtracting values from two pivot tables stored in two dataframes
score: 3
has answer: http://stackoverflow.com/a/52162774
downvote count: 0
has body: I have two tables: df1:[1 rows x 23 columns] 1C 1E 1F 1H 1K ... 2M 2P 2S 2U 2W total 1057 334 3609 3762 1393 ... 328 1611 1426 87 118 df2:[1 rows x 137 columns] 1CA 1CB 1CC 1CF 1CJ 1CS ... 2UB 2UJ 2WB 2WC 2WF 2WJ total 11 381 111 20 527 2 ... 47 34 79 2 1 36 I need to subtract the value between two tables. like 1C-1CF, 1E-1EF, 1F-1FF and so on. I.e I need to subtract only the column ends with F in sheet2. Answer: 1C=1C-1CF=1037 How is this possible using Python code? Note: Some of ´df1´ has no ´F´ in ´df2´ df1: ['1C', '1E', '1F', '1H', '1K', '1M', '1N', '1P', '1Q', '1R', '1S', '1U', '1W', '2C', '2E', '2F', '2H', '2K', '2M', '2P', '2S', '2U', '2W'] df2: ['1CA', '1CB', '1CC', '1CF', '1CJ', '1CS', '1CU', '1EA', '1EB', '1EC', '1EF', '1EJ', '1ES', '1FA', '1FB', '1FC', '1FF', '1FJ', '1FS', '1FT', '1FU', '1HA', '1HB', '1HC', '1HF', '1HJ', '1HS', '1HT', '1HU', '1KA', '1KB', '1KC', '1KF', '1KJ', '1KS', '1KU', '1MA', '1MB', '1MC', '1MF', '1MJ', '1MS', '1MU', '1NA', '1NB', '1NC', '1NF', '1NJ', '1PA', '1PB', '1PC', '1PF', '1PJ', '1PS', '1PT', '1PU', '1QA', '1QB', '1QC', '1QF', '1QJ', '1RA', '1RB', '1RC', '1RF', '1RJ', '1SA', '1SB', '1SC', '1SF', '1SJ', '1SS', '1ST', '1SU', '1UA', '1UB', '1UC', '1UF', '1UJ', '1US', '1UU', '1WA', '1WB', '1WC', '1WF', '1WJ', '1WS', '1WU', '2CA', '2CB', '2CC', '2CJ', '2CS', '2EA', '2EB', '2EJ', '2FA', '2FB', '2FC', '2FJ', '2FU', '2HB', '2HC', '2HF', '2HJ', '2HU', '2KA', '2KB', '2KC', '2KF', '2KJ', '2KU', '2MA', '2MB', '2MC', '2MF', '2MJ', '2MS', '2MT', '2PA', '2PB', '2PC', '2PF', '2PJ', '2PU', '2SA', '2SB', '2SC', '2SF', '2SJ', '2UA', '2UB', '2UJ', '2WB', '2WC', '2WF', '2WJ']´

http://stackoverflow.com/comment/91280875
type: QuestionComment
comment on: http://stackoverflow.com/q/52165430
has text: According to the [docs](https://www.statsmodels.org/dev/generated/statsmodels.tsa.arima_model.ARIMAResults.predict.html#statsmodels.tsa.arima_model.ARIMAResults.predict): "end (int, str, or datetime) – Zero-indexed observation number at which to end forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. **However, if the dates index does not have a fixed frequency, end must be an integer index** if you want out of sample prediction." -- you never set a dates parameter in the call to `ARIMA`
score: 0
type: Comment

http://stackoverflow.com/comment/91284444
has text: It meant request is not correct because JSON file has 'name' attribute in it for each entry. Im just not getting JSON file correctly
type: Comment
comment on: http://stackoverflow.com/q/52167187
type: QuestionComment
score: 1

http://stackoverflow.com/comment/91389099
type: QuestionComment
has text: import logging; log = logging.getLogger(__name__)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52219956

http://stackoverflow.com/a/52130323
has comment: http://stackoverflow.com/comment/91210988
type: Answer
answers question: http://stackoverflow.com/q/52130313
score: 0
has body: If you want to break your loop, then simply use break where you want the loop to stop. Edit: Your loop can be like: while n &gt; 0: print('while n value', n) operation = input(''' Please type in the math operation you would like to complete: + for addition - for subtraction * for multiplication / for division ''') number_1 = int(input('Please enter the first number: ')) number_2 = int(input('Please enter the second number: ')) if operation == '+': print('{} + {} = '.format(number_1, number_2)) print(number_1 + number_2) if again(n) == 0:break elif operation == '-': print('{} - {} = '.format(number_1, number_2)) print(number_1 - number_2) if again(n) == 0:break elif operation == '*': print('{} * {} = '.format(number_1, number_2)) print(number_1 * number_2) if again(n) == 0:break elif operation == '/': print('{} / {} = '.format(number_1, number_2)) print(number_1 / number_2) if again(n) == 0:break else: print('You have not typed a valid operator, please run the program again.')

http://stackoverflow.com/q/52156289
has comment: http://stackoverflow.com/comment/91263260
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91263286
tagged with: python
has comment: http://stackoverflow.com/comment/91263845
has comment: http://stackoverflow.com/comment/91263270
has comment: http://stackoverflow.com/comment/91273258
has comment: http://stackoverflow.com/comment/91263035
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/91263342
has comment: http://stackoverflow.com/comment/91273159
has comment: http://stackoverflow.com/comment/91263214
has body: Is there any relatively robust way to check if the currently running script is being automatically invoked as the PYTHONSTARTUP script rather than as a normal Python program? The best method I know of is os.getenv('PYTHONSTARTUP') != __file__, but that relies on PYTHONSTARTUP containing the exact same path as __file__, which I don't think is necessarily the case on all platforms.
type: Question
score: 3
has title: Is there a relatively robust way to detect if the current script is running as PYTHONSTARTUP?
has comment: http://stackoverflow.com/comment/91263460
upvote count: 3
has comment: http://stackoverflow.com/comment/91263228
has comment: http://stackoverflow.com/comment/91262887
has comment: http://stackoverflow.com/comment/91274620
has comment: http://stackoverflow.com/comment/91263308
favorite count: 0

http://stackoverflow.com/comment/91325944
comment on: http://stackoverflow.com/q/52188133
has text: you can't take the `len(None)`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52264041
has comment: http://stackoverflow.com/comment/91475980
type: Question
type: AnsweredQuestion
score: -1
linked to: http://stackoverflow.com/q/976882
has comment: http://stackoverflow.com/comment/91476098
answer count: 2
has title: Is there a way to mix/'shuffle' values in a list in python?
duplicate of: http://stackoverflow.com/q/976882
has body: I am trying to create a Deck of cards type scenario, which I want to 'shuffle' and then pick a 'card'. The cards are in a list as 'S6' (6 of spades), 'CJ' (Jack of Clubs) and I want a card to be picked from index value 0 (top of the deck), and so would like to be able to move around each value in the list randomly. Side question- Would picking a card by using a randomly generated index number produce a similar result? Coding Newboy here!
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52264077
tagged with: python
upvote count: 0
tagged with: list
possible better answer: http://stackoverflow.com/a/52264077
has answer: http://stackoverflow.com/a/52264075
accepted answer: http://stackoverflow.com/a/52264075
tagged with: shuffle

http://stackoverflow.com/comment/91435735
comment on: http://stackoverflow.com/q/52220794
score: 0
type: QuestionComment
type: Comment
has text: My query returns 7 columns. 5 columns type is INT and 2 columns type is TINYINT. Total rows count is 1.480.456

http://stackoverflow.com/comment/91426951
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52237977
has text: @PythonNoob you were probably doing indexed iteration over a dataframe, and that is *extremely* inefficient, because there's a lot of overhead per indexing operation (meant to work on whole dataframes). Even worse, you may have inadvertently mixed the iterative and vectorized methods to produce the worst of both worlds. You can get comparable performance iterating the dataframe if you make sure to loop with `itertuples`. That returns an iterator over the rows of the dataframe as `collections.namedtuple` objects. And you can implement this solution in those terms and keep working with your df.
score: 0

http://stackoverflow.com/q/52152096
duplicate of: http://stackoverflow.com/q/40416072
upvote count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/51520
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/40416072
has comment: http://stackoverflow.com/comment/91254591
answer count: 0
type: UnansweredQuestion
has body: I've been working on a python application that takes input from the user. The input is the path to a text file. Once the user has entered the path to a text file, it will be opened, and the contents displayed in the console. file = input() with open(file, "r") as file: content = file.read() Currently, it will only accept 'literal file paths', for example C:/users/name/documents/filename.txt I would like it to accept relative file paths aswell, for example ./file.txt, which should get a file named file.txt in the current directory, or ../file2.txt which should go up a directory (..) and then get a file called file2.txt. How can I achieve this? I was unable to find any relevant answers.
type: Question
has title: Relative file paths in python
score: 1
has comment: http://stackoverflow.com/comment/91254562

http://stackoverflow.com/comment/91357096
type: Comment
comment on: http://stackoverflow.com/a/52203855
has text: WOW!!! That is more than what I expected. Thank you very much. I will study your code to understand it better. Any chance you could look at my code above and let me know what am i missing. I would really love to see what am I missing and I believe it could be something to do with a built in sprite command.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91248090
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52147916
type: QuestionComment
has text: Is this the whole DAG? Then the call for generic_op might be missing.

http://stackoverflow.com/comment/93913079
score: 1
comment on: http://stackoverflow.com/q/52119997
has text: I'm not entirely sure, but it seems that the answer is "no" to both questions. If you want to mask out some time steps for the metrics computation, the easiest (although hacky) way is to assign a special label to those transactions, then write a custom metric that ignores time steps where y_true has that value.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52125136
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/52125367
answer count: 1
tagged with: python
tagged with: gensim
has title: Training LDA on Wikipedia corpus to tag arbitary article?
has body: I followed the steps in gensim Python https://radimrehurek.com/gensim/wiki.html to train wikipedia on LDA model, now I want to compare arbitary article from cnn.com for example with the trained data, what do I need to do next? Suppose this article is in txt file?
has answer: http://stackoverflow.com/a/52125367
type: AnsweredQuestion
tagged with: nltk

http://stackoverflow.com/comment/91198059
comment on: http://stackoverflow.com/q/52123168
type: Comment
type: QuestionComment
has text: `pipe.get_params()` ?
score: 0

http://stackoverflow.com/comment/91211613
comment on: http://stackoverflow.com/a/52130143
has text: Wow, thanks a ton for the detailed answer. The overhead of calling the kernels is probably going to be much greater than the time it takes for them to execute, so that will be a bottleneck when cycles gets bigger.
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/q/52124261
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/91242352
upvote count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/91287616
has comment: http://stackoverflow.com/comment/91317409
has title: How to make a ROC with sklearn elastic net?
type: Question
has comment: http://stackoverflow.com/comment/91418218
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/91411700
favorite count: 0
score: 0
has body: I have: r = numpy array of 6 features, i.e. shape ~10000 x 6 answer = binary numpy array (1 or 0) that I want to learn to predict, shape ~1000 x 1 I've done: [datatrain, datatest, answertrain, answertest] = cross_validation.train_test_split(r,answer) clf = linear_model.ElasticNet() clf.fit(X=datatrain,y=answertrain) prediction = clf.predict(datatest) How do I get thresholds for a ROC? I don't see an attribute for a decision function or prediction probabilities or anything.
answer count: 0
type: UnansweredQuestion

keras
tags question: http://stackoverflow.com/q/52115503
tags question: http://stackoverflow.com/q/52145802
tags question: http://stackoverflow.com/q/52188435
tags question: http://stackoverflow.com/q/52123816
tags question: http://stackoverflow.com/q/52210472
tags question: http://stackoverflow.com/q/52189093
tags question: http://stackoverflow.com/q/52219925
tags question: http://stackoverflow.com/q/52126539
tags question: http://stackoverflow.com/q/52233812
tags question: http://stackoverflow.com/q/52218258
tags question: http://stackoverflow.com/q/52270853
tags question: http://stackoverflow.com/q/52125924
tags question: http://stackoverflow.com/q/52162609
tags question: http://stackoverflow.com/q/52250100
tags question: http://stackoverflow.com/q/52248705
tags question: http://stackoverflow.com/q/52147847
tags question: http://stackoverflow.com/q/52118314
tags question: http://stackoverflow.com/q/52170404
tags question: http://stackoverflow.com/q/52149009
tags question: http://stackoverflow.com/q/52267297
tags question: http://stackoverflow.com/q/52234213
tags question: http://stackoverflow.com/q/52113872
tags question: http://stackoverflow.com/q/52180645
tags question: http://stackoverflow.com/q/52270177
tags question: http://stackoverflow.com/q/52176998
tags question: http://stackoverflow.com/q/52257825
tags question: http://stackoverflow.com/q/52184142
tags question: http://stackoverflow.com/q/52237657
tags question: http://stackoverflow.com/q/52216747
tags question: http://stackoverflow.com/q/52193464
tags question: http://stackoverflow.com/q/52181121
tags question: http://stackoverflow.com/q/52256408
tags question: http://stackoverflow.com/q/52192148
tags question: http://stackoverflow.com/q/52265795
tags question: http://stackoverflow.com/q/52188991
tags question: http://stackoverflow.com/q/52221103
tags question: http://stackoverflow.com/q/52187453
tags question: http://stackoverflow.com/q/52268879
tags question: http://stackoverflow.com/q/52220242
tags question: http://stackoverflow.com/q/52155331
tags question: http://stackoverflow.com/q/52269603
tags question: http://stackoverflow.com/q/52169024
tags question: http://stackoverflow.com/q/52149644
tags question: http://stackoverflow.com/q/52115690
tags question: http://stackoverflow.com/q/52251597
tags question: http://stackoverflow.com/q/52248424
tags question: http://stackoverflow.com/q/52144245
tags question: http://stackoverflow.com/q/52119997
tags question: http://stackoverflow.com/q/52201744
tags question: http://stackoverflow.com/q/52158448
tags question: http://stackoverflow.com/q/52257509
tags question: http://stackoverflow.com/q/52150412
tags question: http://stackoverflow.com/q/52117648
tags question: http://stackoverflow.com/q/52140607
tags question: http://stackoverflow.com/q/52249488
tags question: http://stackoverflow.com/q/52177629
tags question: http://stackoverflow.com/q/52261597
tags question: http://stackoverflow.com/q/52201643
tags question: http://stackoverflow.com/q/52155642
tags question: http://stackoverflow.com/q/52252442
tags question: http://stackoverflow.com/q/52162004
tags question: http://stackoverflow.com/q/52235235
tags question: http://stackoverflow.com/q/52119988
tags question: http://stackoverflow.com/q/52234586
tags question: http://stackoverflow.com/q/52121536
tags question: http://stackoverflow.com/q/52218137
tags question: http://stackoverflow.com/q/52172859
tags question: http://stackoverflow.com/q/52205315
tags question: http://stackoverflow.com/q/52152054
tags question: http://stackoverflow.com/q/52152341
tags question: http://stackoverflow.com/q/52199485
tags question: http://stackoverflow.com/q/52201644
tags question: http://stackoverflow.com/q/52226691
tags question: http://stackoverflow.com/q/52212704
tags question: http://stackoverflow.com/q/52138290
tags question: http://stackoverflow.com/q/52237609
tags question: http://stackoverflow.com/q/52115366
tags question: http://stackoverflow.com/q/52221899
tags question: http://stackoverflow.com/q/52197351
tags question: http://stackoverflow.com/q/52246288

jupyter-notebook
tags question: http://stackoverflow.com/q/52227150
tags question: http://stackoverflow.com/q/52176813
tags question: http://stackoverflow.com/q/52235476
tags question: http://stackoverflow.com/q/52234432
tags question: http://stackoverflow.com/q/52133347
tags question: http://stackoverflow.com/q/52210690
tags question: http://stackoverflow.com/q/52268613
tags question: http://stackoverflow.com/q/52140966
tags question: http://stackoverflow.com/q/52255582
tags question: http://stackoverflow.com/q/52241986
tags question: http://stackoverflow.com/q/52157057
tags question: http://stackoverflow.com/q/52214776
tags question: http://stackoverflow.com/q/52202855
tags question: http://stackoverflow.com/q/52242964
type: Tag
tags question: http://stackoverflow.com/q/52203981
tags question: http://stackoverflow.com/q/52197459
tags question: http://stackoverflow.com/q/52208325
tags question: http://stackoverflow.com/q/52264782
tags question: http://stackoverflow.com/q/52231714
tags question: http://stackoverflow.com/q/52220398
tags question: http://stackoverflow.com/q/52233578
tags question: http://stackoverflow.com/q/52261597
tags question: http://stackoverflow.com/q/52231642
tags question: http://stackoverflow.com/q/52235013
tags question: http://stackoverflow.com/q/52209224
tags question: http://stackoverflow.com/q/52162213
tags question: http://stackoverflow.com/q/52200373
tags question: http://stackoverflow.com/q/52210212
tags question: http://stackoverflow.com/q/52211219
tags question: http://stackoverflow.com/q/52244474
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/52204739
tags question: http://stackoverflow.com/q/52222461
tags question: http://stackoverflow.com/q/52123009
tags question: http://stackoverflow.com/q/52118110
tags question: http://stackoverflow.com/q/52167754
tags question: http://stackoverflow.com/q/52162671
tags question: http://stackoverflow.com/q/52247021
tags question: http://stackoverflow.com/q/52173227
tags question: http://stackoverflow.com/q/52119454
tags question: http://stackoverflow.com/q/52148843
tags question: http://stackoverflow.com/q/52239111
tags question: http://stackoverflow.com/q/52188625
tags question: http://stackoverflow.com/q/52250730
tags question: http://stackoverflow.com/q/52184570

http://stackoverflow.com/comment/91334549
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52190649
has text: yes, this seems reasonable way.
score: 0

http://stackoverflow.com/comment/118564754
score: 0
type: AnswerComment
has text: @Meet pd.cut(df.Points,bins=[0,20,80,150,np.Inf],labels=['very low','low','medium','High'])
type: Comment
comment on: http://stackoverflow.com/a/52249520

http://stackoverflow.com/comment/91499697
score: 0
has text: probably I should use external DB to store these new passwords and then use it.
comment on: http://stackoverflow.com/a/52262895
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52221761
tagged with: pivot-table
tagged with: python
has answer: http://stackoverflow.com/a/52222058
type: AnsweredQuestion
score: 2
upvote count: 2
has title: selecting a column from pandas pivot table
has body: I have the below pivot table which I created from a dataframe using the following code: table = pd.pivot_table(df, values='count', index=['days'],columns['movements'], aggfunc=np.sum) movements 0 1 2 3 4 5 6 7 days 0 2777 51 2 1 6279 200 7 3 2 5609 110 32 4 3 4109 118 101 8 3 4 3034 129 109 6 2 2 5 2288 131 131 9 2 1 6 1918 139 109 13 1 1 7 1442 109 153 13 10 1 8 1085 76 111 13 7 1 9 845 81 86 8 8 10 646 70 83 1 2 1 1 As you can see from pivot table that it has 8 columns from 0-7 and now I want to plot some specific columns instead of all. I could not manage to select columns. Lets say I want to plot column 0 and column 2 against index. what should I use for y to select column 0 and column 2? plt.plot(x=table.index, y=??) I tried with y = table.value['0', '2'] and y=table['0','2'] but nothing works.
type: Question
accepted answer: http://stackoverflow.com/a/52222058
tagged with: pandas
tagged with: python-3.5
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/91381018
type: Comment
has text: Could you split your corpus and run your function on different threads? (https://stackoverflow.com/questions/2846653/how-to-use-threading-in-python#28463266)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52216053

http://stackoverflow.com/comment/91403930
has text: Thank you for the comment. That's true that train_data_generator() is returning tensors. But how do I convert it in a way so that it returns numpy arrays instead then?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52216747

http://stackoverflow.com/q/52264028
type: Question
score: 5
answer count: 1
has body: I'm attempting to login to a website, click a button, and then scrape some data. The page must be rendered because it's all in JavaScript (and thus unavailable if you were [for example] to View Source in a web browser). Everything works except for when it comes time to send the click. When I try to send the click with the requests_html package, it doesn't appear to do anything, although no errors are thrown. I understand it leans heavily on pyppeteer, so I've been trying to jump between the docs, but the whole async programming thing is pretty confusing to me. import asyncio import requests_html # Login information payload = { 'email': 'example@gmail.com', 'password': 'Password123' } # Start a session with requests_html.HTMLSession() as s: p = s.post('https://www.website.com/login', data=payload) # Send the request now that we're logged in r = s.get('https://www.website.com/data') # Render the JavaScript page so it's accessible r.html.render(keep_page=True, scrolldown=5, sleep=5) async def click(): await r.html.page.click( selector='button.showAll', options={'delay':3, 'clickCount':1}, ) asyncio.get_event_loop().run_until_complete(click()) print(r.html.html) r.html.html contains the rendered HTML from the JS, but not with the button clicked. I've confirmed the button is being clicked, but I suspect the new page is not being 'saved' somehow, and that r.html.html is returning the pre-clicked page. I would rather not use deprecated PhantomJS/Selenium. Scrapy is really heavy duty, and I'd rather not rely on Scrapy + Splash to get this done - I think I'm so close! MechanicalSoup doesn't work with JavaScript.
has comment: http://stackoverflow.com/comment/91476360
has answer: http://stackoverflow.com/a/63467702
tagged with: python
favorite count: 0
has title: Sending a click with requests_html and pyppeteer python
upvote count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91492782
tagged with: web-scraping
downvote count: 0

http://stackoverflow.com/q/52247901
tagged with: django
tagged with: python
tagged with: favicon
has body: I'm completely stumped. I have written a Django application that is being hosted by A2 and is served up through passenger wsgi. It functions in development, but on deployment, it fails with the following error: Failed to load resource: the server responded with a status of 502 (Bad Gateway) /favicon.ico:1 So, I figure that the favicon must not be able to be found by the application. I have an index.html that contains the following in the head: &lt;link rel="shortcut icon" href="{% static 'icons/favicon.ico' %}" type="image/x-icon" /&gt; That doesn't seem to do it. I tried adding it to my app.urls as a view like so: from django.contrib import admin from django.urls import path from django.conf.urls import include, url from django.views.generic.base import RedirectView from django.conf import settings favicon_view = RedirectView.as_view(url='static/favicon.ico', permanent=False) urlpatterns = [ path('admin/', admin.site.urls), path('resume/', include('resume.urls')), path('favicon.ico', favicon_view), ] Works in dev again, not in deployment. I'm not sure if it is a problem with my static folder or what. I understand that there's loads of threads about favicon.ico, but none seem to be much relevant (for Ruby on Rails) or I have already tried the solutions above, which failed. Any ideas on how to get past this favicon.ico 502 error? Here is my relevant settings.py code: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'public') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'tmp') And here is my project tree with the attempted locations of favicon.ico: app - app - __init__.py - settings.py - urls.py - wsgi.py - public - icons/favicon.ico - resume - static - icons/favicon.ico - favicon.ico - templates - templatetags - (python files) - tmp - (empty) - favicon.ico - manage.py - passenger_wsgi.py
answer count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/91443637
tagged with: wsgi
has title: Favicon.ico in Django app cannot be found resulting in 502 Error
upvote count: 1
tagged with: passenger
downvote count: 0
has comment: http://stackoverflow.com/comment/91443678
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/107698374
type: QuestionComment
has text: When I tried out `selenium-wire` for the first time using the [homepage simple example](https://github.com/wkeeling/selenium-wire#simple-example) I also got `KeyError` on `content-type` from line `request.response.headers['Content-Type']`. This is because, for that particular response in the loop, there was no `content-type` header. For the sake of running the *simple example* to completion: replace `request.response.headers['Content-Type']` with `request.response.headers.get('Content-Type')`
comment on: http://stackoverflow.com/q/52263610
score: 0
type: Comment

http://stackoverflow.com/q/52141434
accepted answer: http://stackoverflow.com/a/52235714
answer count: 1
downvote count: 0
favorite count: 0
tagged with: proxy
tagged with: python
has answer: http://stackoverflow.com/a/52235714
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: selenium
type: Question
has body: I am trying to use selenium and python to connect to a site. I then decided to add proxies to the whole process and use them to connect to the site. The proxies are scraped using Proxy Broker (python module). So I can get a lot of proxies scraped. I then save it to a text file and when I need to connect I randomly choose it from the text file. However here is where the problem arises. When connecting to the site the proxies sometimes don't work. Currently this is the code I am using: import asyncio from proxybroker import Broker async def save(proxies, filename): """Save proxies to a file.""" with open(filename, 'w') as f: while True: proxy = await proxies.get() if proxy is None: break proto = 'https' if 'HTTPS' in proxy.types else 'http' row = '%s://%s:%d\n' % (proto, proxy.host, proxy.port) f.write(row) def main(): proxies = asyncio.Queue() broker = Broker(proxies) tasks = asyncio.gather(broker.find(types=['HTTP', 'HTTPS'], limit=5), save(proxies, filename='proxies.txt')) loop = asyncio.get_event_loop() loop.run_until_complete(tasks) if __name__ == '__main__': main() lines = open('proxies.txt').read().splitlines() rproxy =random.choice(lines) PROXY = rproxy This code is the example code from the Proxy Broker example page (https://proxybroker.readthedocs.io/en/latest/examples.html) So what I want to be able to do is 1 of two things: Option 1: Check the proxies right after they are scraped and then save the proxies that work in a text file and call them later Option 2: Check the proxies right before it connects to the site. So it checks if the proxy works and then if it does it uses it. If it doesn't it tries with another one. I don't really have a clue on how to do this. One thing my friend suggested was to use requests and see if the proxy works, but I'm having problems with that because I can't format the proxy list to be used with requests automatically. Any help/tips are much appreciated. Thanks in advance!!!! (Edit) I have already tried posts such as these: Pr…
linked to: http://stackoverflow.com/q/765305
has title: Checking proxies in python/selenium

http://stackoverflow.com/a/52170678
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52170598
answers question: http://stackoverflow.com/q/52170598
has body: In this case, you can just check if the img tag has the class attribute: soup.find_all('img', attrs={'class': True}) Example: In [1570]: [img['alt'] for img in soup.find_all('img', attrs={'class': True})] Out[1570]: ['Japanese League Cup', 'Japanese League Cup', 'Brazilian Division 1'] For completeness, matching any dynamic attribute value, you need to find a common pattern in the naming e.g. in this case it seems all the class names start with character c; so, you can use the CSS selector: img[class^="c"] Example: In [1571]: [img['alt'] for img in soup.select('img[class^="c"]')] Out[1571]: ['Japanese League Cup', 'Japanese League Cup', 'Brazilian Division 1']
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/a/52140708
accepted answer of: http://stackoverflow.com/q/52139535
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
has body: The problem here is a Python programming error, not an issue with your use of AWS. Your globarVars dict does not have a value whose key is 'Endpoint' so Python throws a KeyError when you try to access globalVars['Endpoint']. You need to populate a value. Also, rather than write 100s of lines of code to build AWS infrastructure, you might want to consider using AWS CloudFormation which allows you to write a YAML template to do the same thing. Finally, a preferred way to populate your globalVars dictionary would be: globalVars = { 'REGION_NAME': 'ap-south-1', 'AZ1': 'ap-south-1a', 'AZ2': 'ap-south-1b', # others here }
answers question: http://stackoverflow.com/q/52139535

http://stackoverflow.com/comment/91280711
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52165522
score: 0
has text: (And no, it's not an OAuth2 exchange, that works differently).

http://stackoverflow.com/comment/91367070
comment on: http://stackoverflow.com/q/52208787
type: Comment
type: QuestionComment
has text: I think this question is better suited to https://dba.stackexchange.com/
score: 0

http://stackoverflow.com/q/52152313
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/7706095
has comment: http://stackoverflow.com/comment/91256047
has body: i making a script in python for reading the last 5 minutes of a log file, this is my code so far from datetime import datetime, timedelta now = datetime.now() before = timedelta(minutes=5) now = now.replace(microsecond=0) before = (now-before) now = (now.strftime("%b %d %X")) before = (before.strftime("%b %d %X")) print(before) print(now) with open('user.log','r') as f: for line in f: if before in line: break for line in f: if now in line: break print (line.strip()) the output is Sep 03 11:47:25 Sep 03 11:52:25 which is the print to check if the time is correct, nearly 100 lines in the log that has it but dont bring me nothing, if i take the ifs out then print all the lines which proves the problem is on the if... any ideas? here is a exemple of my log file content: Sep 03 10:18:47 bni..........teagagfaesa..... Sep 03 10:18:48 bni..........teagagfaesa.....2
has title: Reading log file last 5 minutes python 2.6
has comment: http://stackoverflow.com/comment/91256476
has comment: http://stackoverflow.com/comment/91256116
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91256744
score: 0
has comment: http://stackoverflow.com/comment/91256351
answer count: 1
tagged with: shell
has comment: http://stackoverflow.com/comment/91256979
has answer: http://stackoverflow.com/a/52153314
has comment: http://stackoverflow.com/comment/91256171
has comment: http://stackoverflow.com/comment/91255306
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91446905
type: Comment
comment on: http://stackoverflow.com/q/52249355
type: QuestionComment
score: 0
has text: what is the level of parallelism involved in your script?

http://stackoverflow.com/q/52160596
has answer: http://stackoverflow.com/a/52160743
tagged with: apache-spark
score: 2
downvote count: 0
has title: Convert Column value in Dataframe to list
has answer: http://stackoverflow.com/a/52160900
favorite count: 0
has answer: http://stackoverflow.com/a/52160849
tagged with: python
answer count: 4
upvote count: 2
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52160849
tagged with: pyspark
has body: I have the following source file. I have a name called "john" in my file wanted to split to list ['j','o','h','n']. Please find the person file as follows. Source File: id,name,class,start_data,end_date 1,john,xii,20170909,20210909 Code: from pyspark.sql import SparkSession def main(): spark = SparkSession.builder.appName("PersonProcessing").getOrCreate() df = spark.read.csv('person.txt', header=True) nameList = [x['name'] for x in df.rdd.collect()] print(list(nameList)) df.show() if __name__ == '__main__': main() Actual Output: [u'john'] Desired Output: ['j','o','h','n']
possible better answer: http://stackoverflow.com/a/52160743
has answer: http://stackoverflow.com/a/59788050

http://stackoverflow.com/q/52225334
downvote count: 0
tagged with: instagram
possible better answer: http://stackoverflow.com/a/52984722
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52984722
has comment: http://stackoverflow.com/comment/91400697
answer count: 5
tagged with: web-scraping
tagged with: python
has answer: http://stackoverflow.com/a/52225638
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/53670711
has answer: http://stackoverflow.com/a/52225590
accepted answer: http://stackoverflow.com/a/52225638
has answer: http://stackoverflow.com/a/52225513
has title: Webscraping Instagram follower count BeautifulSoup
has comment: http://stackoverflow.com/comment/108423040
type: Question
has body: I'm just starting to learn how to web scrape using BeautifulSoup and want to write a simple program that will get the follower count for a given Instagram page. I currently have the following script (pulled from another Q&amp;A thread): import requests from bs4 import BeautifulSoup user = "espn" url = 'https://www.instagram.com/'+ user r = requests.get(url) soup = BeautifulSoup(r.content) followers = soup.find('meta', {'name': 'description'})['content'] follower_count = followers.split('Followers')[0] print(follower_count) # 10.7m The problem I am running into is I want to get a more precise number, which you can see when you hover the mouse over the follower count on the Instagram page (e.g., 10,770,816). Unfortunately, I have not been able to figure out how to do this with BeautifulSoup. I'd like to do this without the API since I am combining this with code to track other social media platforms. Any tips?
score: 5
upvote count: 5

http://stackoverflow.com/comment/91206355
type: Comment
comment on: http://stackoverflow.com/a/52127982
has text: @AntsOfTheSky i added it to the answer
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91542877
type: AnswerComment
has text: @rocksportrocker eval throws EOL for string literal as informed explanation has all special characters as well as \n
type: Comment
comment on: http://stackoverflow.com/a/52171733
score: 0

http://stackoverflow.com/a/52123068
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: In future, please show the relevant code in your question itself. The problem is in your artshow function, where you have this code; return render_template('artshow.html', title='artshow', submissions='submissions') Here you are sending the literal string "submissions" to the template, and you iterate over it (count how many letters it has). Instead, you should be sending the submissions variable you defined in the previous line: return render_template('artshow.html', title='artshow', submissions=submissions)
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/52122949
answers question: http://stackoverflow.com/q/52122949

http://stackoverflow.com/a/52156138
downvote count: 1
type: Answer
score: 8
upvote count: 9
has comment: http://stackoverflow.com/comment/103862547
answers question: http://stackoverflow.com/q/52134926
accepted answer of: http://stackoverflow.com/q/52134926
has body: As discussed in the question's comments, keras' ReduceLROnPleteau, does appear to work for its default parameters: # keras' ReduceLROnPlateau callback default parameters: from keras.callbacks import ReduceLROnPlateau reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=10, verbose=0, mode='auto', min_delta=0.0001, cooldown=0, min_lr=0) I tried to recreate the error to try and identify which parameter causes it, but I couldn't. Due to this, I believe that the error doesn't appear for all input shapes or models. However, I can say for sure that, with the correct parameters, ReduceLROnPlateau does work with Adam.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/98026310

http://stackoverflow.com/comment/133821625
has text: For me, exceptions handle errors at code side and can't handle API response. Eg: with a bad route, no Exception is raised , just an error message in the response `try: req = requests.post(endpoint, headers=head, data=json.dumps(payload)) print(f'{req.text} - OK') except Exception as e: print(f'{req.text} - KO {e}')`. I this case, not exception. The `TRY`is ok and the`req.text`only shows `bad route`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/70399146

http://stackoverflow.com/q/52179181
tagged with: javascript
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91308679
has answer: http://stackoverflow.com/a/52214816
type: Question
has comment: http://stackoverflow.com/comment/91325578
tagged with: python
has answer: http://stackoverflow.com/a/52179640
has body: I am trying to get html code for web scraping using Python. I chose a website of the real estate agency. Before doing onclick event of the button that change pages I need to get this element itself. However buttons that let us go to the next or previous page (designed with symbols ">" and "&lt;") are not displayed inside the code. Could you please advice something on this issue. Here is my code from selenium import webdriver from bs4 import BeautifulSoup as bs import requests browser = webdriver.Chrome() url = "https://www.centris.ca/en/properties~for-sale?view=Thumbnail" browser.get(url) innerHTML = browser.execute_script("return document.body.innerHTML") print(innerHTML)
has title: Can't get all html code by using execute_script in Python for web scraping
score: 0
answer count: 2
tagged with: selenium
tagged with: web-scraping

http://stackoverflow.com/comment/91468062
has text: before running 700 processes with some code, optimize the code itself...
comment on: http://stackoverflow.com/q/52260212
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/52256672
type: Answer
has comment: http://stackoverflow.com/comment/91569519
score: 0
has body: select is a Python standard module. Maybe you should check that your python binaries are unbroken or just reinstall it. Check that: import select and select.select in Python Interactive Environment. If some errors generated, you'd better reinstall the python binaries.
has comment: http://stackoverflow.com/comment/91575125
answers question: http://stackoverflow.com/q/52256451

http://stackoverflow.com/q/52180582
type: Question
tagged with: 3d
answer count: 1
score: 0
tagged with: rotational-matrices
has comment: http://stackoverflow.com/comment/91315234
accepted answer: http://stackoverflow.com/a/52182302
tagged with: gyroscope
has title: quaternion rotation vs. rotation matrix have a slight difference
tagged with: python
has body: I have a 3D rotation over time represented as a momentary rotation around each of the axis (roll, pitch, yaw). I'm trying to accumulate this rotation over time (about 50k measurements in total). I've tried doing it in 2 different ways. Using rotation matrices, and using quaternions calculation. The rotation matrices implementation seem to give correct results, but I know it is less recommended for accumulating many rotations. The 2 results seem quite similar, but it accumulates a slight difference between the 2 results over time (about 1 degree every 250 measurements). I'm not sure where this difference comes from. Whether it is caused by floating point precision in calculating many matrices multiplications, or by using wrong parameters for the quaternion initialization. This is the code I use: # Last known rotation. As quaternion and as rotation matrix last_rotation_matrix = .... last_quaternion_rotation = ..... # time_diff_seconds is approximately 4/1000 # the momentary rotation speed is around 0-1 radian per second. so [roll,pitch,yaw] are around 0-0.004) roll = rotation_x_speed * time_diff_seconds pitch = rotation_y_speed * time_diff_seconds yaw = rotation_z_speed * time_diff_seconds total_rotation = np.sqrt(roll**2 + pitch**2 + yaw**2) # This function creates a rotation matrix based on the given parameters diff_rotation_matrix = rotation_matrix(roll, pitch, yaw) # THIS IS THE LINE THAT I SUSPECT: diff_quaternion_rotation = Quaternion(axis=[rotation_x_speed, rotation_y_speed, rotation_z_speed], radians=total_rotation) new_rotation_matrix = diff_quaternion_rotation.dot(last_rotation_matrix) new_quaternion_rotation = diff_quaternion_rotation * last_rotation_matrix The line that I suspect is the line initializing the diff_quaternion_rotation variable.
type: AnsweredQuestion
tagged with: quaternions
has answer: http://stackoverflow.com/a/52182302

http://stackoverflow.com/q/52196356
tagged with: python-import
answer count: 1
has comment: http://stackoverflow.com/comment/91343197
has answer: http://stackoverflow.com/a/52197112
has body: I am a beginner having difficulties using Julia's PyCall to interface with the MIT Python music module music21. According to Music21’s website, in order to display a short melody in musical notation one would type this in Python: converter.parse("tinynotation: 3/4 c4 d8 f g16 a g f#").show() Here is what I did to try and execute this code in Julia: I first initialized music21, which seemed to work: @pyimport music21 music21: Certain music21 functions might need these optional packages: matplotlib, scipy; if you run into errors, install them by following the instructions at http://mit.edu/music21/doc/installing/installAdditional.html Then I tried to recreate the above Python example in Julia by typing: converter.parse("tinynotation: 3/4 c4 d8 f g16 a g f#").show() I received this error: ERROR: UndefVarError: converter not defined Stacktrace: [1] eval(::Module, ::Any) at ./boot.jl:235 UPDATE 1 According to rickhg12hs's suggestion, I attempted music21.converter.parse("tinynotation: 3/4 c4 d8 f g16 a g f#").show(). Now I am getting this error message on 'Parse': ERROR: type PyObject has no field parse Stacktrace: 1 eval(::Module, ::Any) at ./boot.jl:235 It seems like an improvement as it is now crashing a little later in the code chain, at 'Parse' instead of 'Converter'. UPDATE 2 - FIXED This issue has to do with dot overloading. Based on this link, I tried modifying my code to look like this: music21.converter[:parse]("tinynotation: 3/4 c4 d8 f g16 a g f#")[:show]() but now I get this error FSPathMakeRef(/Applications/MuseScore 2.app/Contents/MacOS/mscore) failed with error -43. I discovered that the last thing I had to do was to download MuseScore and now the problem is fixed! See @crstnbr's answer for more context on the ugliness of this solution and imminent fixes. Many thanks! Nakul
accepted answer: http://stackoverflow.com/a/52197112
favorite count: 0
has comment: http://stackoverflow.com/comment/91343502
has comment: http://stackoverflow.com/comment/91342674
tagged with: python
has comment: http://stackoverflow.com/comment/91343380
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: music21
has title: Julia PyCall difficulties in running modules of Music21
has comment: http://stackoverflow.com/comment/91343116
tagged with: julia
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/28553722

http://stackoverflow.com/comment/91450894
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52249152
has text: are you sure that´s even possible? did you check out the docs? afaik event search is deprecated.
type: Comment

http://stackoverflow.com/comment/91518389
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52175881
has text: ok, thank you! sir. my question is how to delete the python module from the anacoda which is the python 3.6.5. as you can see, I cannot remove it on anaconda gui, or using conda remove xxx command. do you have any solutions?

http://stackoverflow.com/a/52203170
has body: Assuming the order is by the keys ['2018-01', '2018-02', '2018-03', '2018-04'] you could loop over the keys in that order, like this: d = {'2018-01': ['jack', 'jhon', 'mary', 'mary', 'jack'], '2018-02': ['Oliver', 'Connor', 'mary', 'Liam', 'jack', 'Oliver'], '2018-03': ['Jacob', 'jhon', 'Reece', 'mary', 'jack'], '2018-04': ['George', 'jhon', 'mary', 'Alexander', 'Richard']} result = {} found = set() for i in sorted(d): result[i] = list(set(d[i]).difference(found)) found.update(d[i]) for i in sorted(result): print(i, result[i]) Output 2018-01 ['mary', 'jhon', 'jack'] 2018-02 ['Oliver', 'Liam', 'Connor'] 2018-03 ['Reece', 'Jacob'] 2018-04 ['Alexander', 'Richard', 'George']
answers question: http://stackoverflow.com/q/52202840
upvote count: 1
downvote count: 1
score: 0
type: Answer

http://stackoverflow.com/q/52201782
score: 0
tagged with: bash
has comment: http://stackoverflow.com/comment/91352826
has title: Creating Excel File From Bash Script output with python
answer count: 1
has comment: http://stackoverflow.com/comment/91353967
type: UnansweredQuestion
tagged with: python
has body: I have an output file which created from a bash script. that output file is: xyz|xxx.local|Protocol 2|Root Acces Denied xyz|xxx1.local|Protocol 2|Root Acces Denied I am trying to create Excel file from this which is going to be Column1 Column2 Column3 Column4 xyz xxx.local Protocol 2 Root Acces Denied xyz xxx.local Protocol 2 Root Acces Denied How can I do this with Python?
linked to: http://stackoverflow.com/q/13437727
has answer: http://stackoverflow.com/a/52203175
type: Question

http://stackoverflow.com/comment/91326213
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52188185
has text: Welcome to SO. It would be a good idea to follow name conventios for your classes, wich is `CamelCase`. So instead of `product_list` and `product_list_from_user`, `ProductList` and `ProductListFromUser`. Lower case is for methods.
score: 0

http://stackoverflow.com/a/52188345
answers question: http://stackoverflow.com/q/52188152
has body: The documentation says modules are installed here: So you should be able to copy old modules from your python folder to this folder. I am not sure if it will work for all modules, cos they may be incompatible with your new version. I strongly suggest to create a BACKUP. Another way could be modifying sys.path in your script, so Python will search for modules also in the path provided by you: import sys sys.path.append('path/to/old/libs/folder') If these methods don't work for all your libs, they can at least serve you as a temporary fix until you find a better way to detect and install all old libs with new version.
accepted answer of: http://stackoverflow.com/q/52188152
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/91329755
type: AcceptedAnswer

http://stackoverflow.com/q/52254343
has body: On a windows 7 (64-bits) machine I installed python 2.7. Then installed pyinstaller, pypiwin32, pywin32-ctypes in this order, by running "pip install pyinstaller" etc in command prompt. Each time some files were downloaded and a success message was shown. Then I restarted my computer. After doing above, I ran "pyinstaller" in command prompt (just this, didnt mention the python code file I wrote) to test the installions. I get a detailed error message, whose last line is shown below (the whole error message is I think too cumbersome and unnecessary to be shown here): C:\Python27&gt;pyinstaller ImportError: No module named dis3 Same error came when I ran the command from c:\python27, c:\python27\scripts. Same error also came when I ran the command mentioning my python code file from above directories and also from the directory where my python code file is. The other questions here related to import errors mentioning some modules when running pyinstaller command are about programming errors inside users' codes such as not mentioning a module in import statement because of hidden dependency etc. I think my error is related to installation (because as stated above, even when I dont pass my code file to the command same error comes). Is the problem with installion or with my code? If the problem is with installion, what do I need to install or uninstall, and in which order? If the problem is in my code then what do I have to import?
type: Question
has title: How to solve "ImportError: No module named dis3" when making stand-alone executable file from python script
answer count: 1
accepted answer: http://stackoverflow.com/a/52259455
score: 0
has answer: http://stackoverflow.com/a/52259455
tagged with: pyinstaller
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/91218184
has text: how to i pass your_links to parse_data function?
comment on: http://stackoverflow.com/a/52133902
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91279704
type: QuestionComment
comment on: http://stackoverflow.com/q/52161677
has text: Huh, actually it is right, usually api-version is a variation of YYYY-MM-DD in Azure, this one seems to omit DD. Let me try to craft the POST myself. How did you generate the SAS? Portal/some SDK?
score: 0
type: Comment

http://stackoverflow.com/comment/91180133
has text: As I mentioned, the gray color in the first line is because PyCharm colours gray lines that have no effect in the code. Since Tk is not being recognised as part of that import, nowhere else the line is being used therefore it is highlighted as gray. It is not because it is commented out. @Mike-SMT
comment on: http://stackoverflow.com/a/52114349
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91346655
has text: Can you add the stack trace? It's not very clear from the question where exactly the error is thrown. Stack trace would help us in debugging.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52198637

http://stackoverflow.com/comment/91236144
has text: I've tried doing that with GIMP but the problem is (unexpectedly) that it won't produce the palette IN THE RIGHT ORDER! It jumbles everything around! I would have assumed it would find a free slot and if every element is unique, it'd just fill up "free slots" of the potential palette in order. But no. I'll try IrfanView just in case.
score: 0
comment on: http://stackoverflow.com/q/52142982
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91378824
comment on: http://stackoverflow.com/q/52214712
score: 1
type: QuestionComment
type: Comment
has text: What do you mean by `where arg1 is from the first python call`, the input for second call is come from output of first call?

http://stackoverflow.com/q/52261909
accepted answer: http://stackoverflow.com/a/52264032
tagged with: python
has title: Tensorflow vs PyTorch: convolution doesn't work
type: AnsweredQuestion
upvote count: 0
tagged with: pytorch
tagged with: tensorflow
type: Question
score: -1
tagged with: deep-learning
answer count: 1
downvote count: 1
favorite count: 0
has body: I'm trying to test if Tensorflow convolution output matches PyTorch convolution output with the same weights. Here's my code in which I copy the weights from Tensorflow to Torch, convolve and compare outputs: import tensorflow as tf import numpy as np import math from math import floor, ceil import os import math import datetime from scipy import misc from PIL import Image import model import torch from torch import nn import common import torch.nn.functional as F sess = tf.Session() np.random.seed(1) tf.set_random_seed(1) #parameters kernel_size = 3 input_feat = 4 output_feat = 4 #inputs npo = np.random.random((1,5,5, input_feat)) x = tf.convert_to_tensor(npo, tf.float32) x2 = torch.tensor(np.transpose(npo, [0, 3, 1, 2])).double() #the same weights weights = np.random.random((kernel_size,kernel_size,input_feat,output_feat)) weights_torch = np.transpose(weights, [3, 2, 1, 0]) #convolving with tensorflow w = tf.Variable(weights, name="testconv_W", dtype=tf.float32) res = tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding="VALID") sess.run(tf.global_variables_initializer()) #convolving with torch torchres = F.conv2d(x2, torch.tensor(weights_torch), padding=0, bias=torch.zeros((output_feat)).double()) #comparing the results print(np.mean(np.transpose(sess.run(res), [0, 3, 1, 2])) - torch.mean(torchres).detach().numpy()) It outputs 0.15440369065716908 Why? Why is there such a big difference? Is the Tensorflow conv2d implementation incorrect? Why doesn't it match PyTorch? Am I doing something wrong? On kernel size 1 everything works fine. Please help.
has answer: http://stackoverflow.com/a/52264032

http://stackoverflow.com/q/52212704
has comment: http://stackoverflow.com/comment/91477294
tagged with: keras
has comment: http://stackoverflow.com/comment/91587505
score: 0
tagged with: keras-layer
has comment: http://stackoverflow.com/comment/91382516
has comment: http://stackoverflow.com/comment/91411441
has body: I want to make an auto-encoder in Keras. Before sending the output of the encoder to the decoder, I want to add a noise image having the same size as the encoder, and after that send both to the decoder. I want to know if this is possible or not. When this section of my code is encountered: merge_encoded_w=cv2.merge(encoded,w) I get this error: TypeError: Tensor objects are not iterable when eager execution is not enabled. To iterate over this tensor use tf.map_fn. My entire code is below: from keras.models import Sequential from keras.layers import Input, Dense, Dropout, Activation,UpSampling2D,Conv2D, MaxPooling2D, GaussianNoise from keras.models import Model from keras.optimizers import SGD from keras.datasets import mnist from keras import regularizers from keras import backend as K import numpy as np import matplotlib.pyplot as plt import cv2 from time import time from keras.callbacks import TensorBoard # Embedding phase ##encoder w=np.random.random((1, 28,28)) input_img = Input(shape=(28, 28, 1)) # adapt this if using `channels_first` image data format x = Conv2D(8, (5, 5), activation='relu', padding='same')(input_img) #x = MaxPooling2D((2, 2), padding='same')(x) x = Conv2D(4, (3, 3), activation='relu', padding='same')(x) #x = MaxPooling2D((2, 2), padding='same')(x) x = Conv2D(2, (3, 3), activation='relu', padding='same')(x) encoded = Conv2D(1, (3, 3), activation='relu', padding='same')(x) merge_encoded_w=cv2.merge(encoded,w) # #decoder x = Conv2D(2, (5, 5), activation='relu', padding='same')(merge_encoded_w) #x = UpSampling2D((2, 2))(x) x = Conv2D(4, (3, 3), activation='relu', padding='same')(x) #x = UpSampling2D((2, 2))(x) x = Conv2D(8, (3, 3), activation='relu',padding='same')(x) #x = UpSampling2D((2, 2))(x) decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x) #Extraction phase decodedWithNois=GaussianNoise(0.5)(decoded) x = Conv2D(8, (5, 5), activation='relu', padding='same')(decodedWithNois) #x = MaxPooling2D((2, 2), padding='same')(x) x =…
answer count: 0
type: UnansweredQuestion
has title: change layers during learning in keras
tagged with: python
has comment: http://stackoverflow.com/comment/91603914
has comment: http://stackoverflow.com/comment/91518297
has comment: http://stackoverflow.com/comment/91486066
has comment: http://stackoverflow.com/comment/91556658
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/91382363

http://stackoverflow.com/comment/91313047
score: 1
comment on: http://stackoverflow.com/q/52181417
type: Comment
has text: Btw: welcome to Stackoverflow. The reason you got a downvote is, because there are plenty of questions about generating a random number between x and y, so you should search for your question first, before blindly asking. Please take yourself some time to take [the tour](https://stackoverflow.com/tour) and read [how to ask a good question](https://stackoverflow.com/help/how-to-ask)
type: QuestionComment

http://stackoverflow.com/q/52185422
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52187721
upvote count: 1
tagged with: python
type: AnsweredQuestion
downvote count: 1
tagged with: tensorflow
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52187721
has body: Here is what I have tried: tf.reset_default_graph() X = tf.placeholder(tf.float32, [None, n_steps, n_inputs]) y = tf.placeholder(tf.float32, [None,n_outputs]) layers = [tf.contrib.rnn.LSTMCell(num_units=n_neurons, activation=tf.nn.leaky_relu, use_peepholes = True) for layer in range(n_layers)] multi_layer_cell = tf.contrib.rnn.MultiRNNCell(layers) rnn_outputs, states = tf.nn.dynamic_rnn(multi_layer_cell, X, dtype=tf.float32) tf.summary.histogram("outputs", rnn_outputs) tf.summary.image("RNN",rnn_outputs) I am getting the following error: InvalidArgumentError: Tensor must be 4-D with last dim 1, 3, or 4, not [55413,4,100] [[Node: RNN_1 = ImageSummary[T=DT_FLOAT, bad_color=Tensor&lt;type: uint8 shape: [4] values: 255 0 0...&gt;, max_images=3, _device="/job:localhost/replica:0/task:0/device:CPU:0"](RNN_1/tag, rnn/transpose_1)]] Kindly, help me get the visualization of the rnn inside the LSTM model that I am trying to run. This will help in understanding what LSTM is doing more accurately.
has answer: http://stackoverflow.com/a/52187110
score: 0
tagged with: tensorboard
possible better answer: http://stackoverflow.com/a/52187110
has title: Displaying RNN using tf.summary.image give error in python tensorflow

http://stackoverflow.com/q/52202538
score: 2
answer count: 0
tagged with: matplotlib
type: Question
linked to: http://stackoverflow.com/q/52200823
downvote count: 0
favorite count: 0
has body: I am trying to create a measurement visualization inside kivy using kivy garden matplotlib. The goal is to plot variables from a dictionary with their associated measurements. At the moment the code (see below) consists of 3 parts. After the import section I define constants that I use inside the code. The next part is a dictionary that I use to programmatically plot different variables with different settings (line color, line width, ect.). Beginning after the dictionary I define a method slice array to splice the arrays to reduce memory usage and a class Plots to generate the plots. I also posted a similar question but by using the kivy garden graph. I have two problems with the code. First, it is not possible for me to display the coordinate system without. The ax.spines command does not have any effect. The second problem is, that I actually want to have the possibility to plot an arbitrary number of variables that I want to display in a separate subplot. I want echt figure to have a constant height on the display. This should lead to the possibility to scroll the plots. import time import psutil import matplotlib.pyplot as plt from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.clock import Clock from kivy.uix.scrollview import ScrollView from kivy.uix.widget import Widget from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg # Chart Constants MAX_MEASUREMENT_ARRAY_LENGTH = 500 # to trim measured values values X_BASE_INTERVAL_LENGTH = 10 # time axis is displayed for an interval of 50 seconds BASE_LINE_WIDTH = 0.5 # line width of lines in plots BASE_LINE_COLOR = "white" COLUMNS_OF_PLOTS = 1 # TODO implement more general layout possibilities, at the moment only 1-column chart_variables = { "cpu_usage": { "order_number": 1, "title": "CPU Usage", "color": BASE_LINE_COLOR, "line_width": BASE_LINE_WIDTH, "x_interval_length": X_BASE_INTERVAL_LENGTH, "y_bottom": 0, "y_top": 100, "x_label": "Time in epochs", "y_label": "CPU usage…
tagged with: kivy-language
upvote count: 2
type: UnansweredQuestion
has title: Python Kivy using Matplotlib for plotting real time graphs (size too small)
tagged with: python
tagged with: kivy
tagged with: plot

http://stackoverflow.com/q/52185746
has answer: http://stackoverflow.com/a/52185783
type: Question
score: -2
has body: I have a list of dictionaries like this: [{'a':1,'b':2},{'a':3,'b':4}...] and, is there any jquery chart plugin that supports user defined x keys and y keys? like this: { xAxis: 'a', yAxis: ['b', 'c'...], data: [{'a':1,'b':2},{'a':3,'b':4}...] }
upvote count: 0
tagged with: highcharts
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: jquery chart plugin that support udf keys
downvote count: 2

http://stackoverflow.com/comment/91467025
comment on: http://stackoverflow.com/q/52229780
type: QuestionComment
type: Comment
has text: Yeah, that isn't the issue I have with it. Does my last comment make sense, or can I clarify it in some way? That's an example of the given query providing a false negative.
score: 0

http://stackoverflow.com/comment/91311049
score: 0
comment on: http://stackoverflow.com/q/52180514
type: Comment
type: QuestionComment
has text: Depends on the database you would like to use. But for example, you can run a docker image of your desired DB, if you want to use Postgresql, you can easily follow this manual: https://docs.docker.com/compose/django/#connect-the-database

http://stackoverflow.com/q/52240712
has body: I'm using XML to return the text values for the values below. I'm using the absolute path to map to the location of the text value. I'm fairly confident the path is accurate. However, when I try to return the value I'm not returning value. Do does anyone see errors in the code that might prevent the value from returning the text value? import requests from lxml import html headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'} url = 'https://www.marketwatch.com' response = requests.get(url, headers=headers, verify=False).text parser = html.fromstring(response) r_name = parser.xpath('/html/body/div[2]/div/div[1]/div/div/ul[2]/li[1]/div[3]/div/p/text()') print(r_name)
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
upvote count: 1
tagged with: python-requests
answer count: 1
has answer: http://stackoverflow.com/a/52240821
has title: XML: Return Text Value?
type: AnsweredQuestion
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/52240821
favorite count: 0
type: Question
tagged with: lxml

http://stackoverflow.com/comment/91415002
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52232839
has text: this might help: http://practicalcryptography.com/miscellaneous/machine-learning/guide-mel-frequency-cepstral-coefficients-mfccs/

http://stackoverflow.com/comment/91534945
type: QuestionComment
has text: I'm glad I could help. I also added my comment as an answer.
comment on: http://stackoverflow.com/q/52251993
score: 0
type: Comment

http://stackoverflow.com/a/52234710
type: AcceptedAnswer
downvote count: 0
score: 16
type: Answer
upvote count: 16
accepted answer of: http://stackoverflow.com/q/52229539
answers question: http://stackoverflow.com/q/52229539
has body: As I already said in the comments to the question: The command expects one (or multiple) arguments of type int; but as the error says, it cannot cast the received argument into a int. Try passing numbers; instead of python manage.py update_mb event_id market_id try using this (or something similar) python manage.py update_mb 2 3 4 But I notice an issue with your code: you use parser.add_argument(... nargs='+', ...) for both of your arguments. Consider the example I gave previously: python manage.py update_mb 2 3 4 How is the command supossed to know which are event_id and which are market_id? How does it work for you? One improvement could be to use optional arguments; read more about Djangos custom management commands and the underlying Python argparse module. It could look like this: def add_arguments(self , parser): parser.add_argument('--event', action='append', type=int) parser.add_argument('--market', action='append', type=int) To be used like this: &gt;&gt;&gt; python manage.py update_mb --event 2 --event 3 --market 4

http://stackoverflow.com/comment/91410431
score: 3
has text: Umm, you have to type `from emoji import emojize` in a python script. It's not a bash command...
comment on: http://stackoverflow.com/q/52230411
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52256242
tagged with: python
has comment: http://stackoverflow.com/comment/91459742
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91459791
accepted answer: http://stackoverflow.com/a/52256388
type: Question
has body: I'm stuck with a rather random problem after inheriting someones work. There are currently 2 CSV files being imported into the python programme 1 containing numbers 1 containing patterns and a site code Currently his programme will correctly import both CSV's and check "if pattern in numbers", if so it will print the the number the pattern it matched and then the site code. The problem is actually that he wants to append each match to a list named after the site code which he had also statically created. After much googling it seems like globals() would be the option to get the desired behaviour i.e: x = Range[0] globals()[x].append(DDI) where Range[0] is the site code The issue i seem to be having with this is that all the arrays turn out the same despite the fact that the comparison line is working correctly when printed Full code for context: with open('NumPlan.csv', 'r') as f: mylist = [] AEDUB = ATVIE = ATVZR = BEANT = BEBRS = BEBRU = BEMPL = CHBAS = CHLAS = CHZUR = CHWRO = CZOPA = CZPPA = DEBER = DEBSS = DEBRS = DECOL = DEDUS = DEESS = DEFBA = DEFFM = DEFRA = DEHAM = DEMUN = DENUR = DESTU = DKAAR = DKALB = DKCOP = ESBCN = ESMAD = ESMDD = ESPAL = ESVAL = FIHEL = FRBAG = FRBOR = FRLIL = FRLYN = FRMAR = FRMON = FRPRO = FRRHB = FRTOU = GBABE = GBAZT = GBBEL = GBBIR = GBBRI = GBCOL = GBEDI = GBGPH = GBGSH = GBLBS = GBLEE = GBLIV = GBLHH = GBLON = GBLWR = GBMAN = GBNOR = GBPAR = GBSMC = GBSOU = GBTRA = GBTHE = GBXWH = HUBUD = HUGUB = IEDBL = ITMIL = ITMOD = ITMVP = ITROM = ITTUR = ITMIG = LULGI = LULUX = NLAMS = NLUTR = NLDEN = NLRIK = NLROT = NLSCH = NODRO = PLWRO = PLART = PLWAA = PLWKS = PTLIS = ROBUC = RUMOS = SKBRA = SKZAM = SESTG = SESTO = SESOL = TRIST = [] with open('Ranges.csv', 'r') as R: currentDDI = [] ranges = [] for line in f: li = line.split(",") for each in li: if "\\" in each: currentDDI.append(each.strip()) for line2 in R: Range = line2.split(",") for DDI in currentDDI: if Range[1].strip() in DDI.strip(): x = Range[0] globals()[x].append(DDI) print…
has comment: http://stackoverflow.com/comment/91463322
has answer: http://stackoverflow.com/a/52256388
has title: Appending to List after Matching
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91459913

http://stackoverflow.com/comment/91289260
has text: Because I can't really tell what is the root cause of my problem. Maybe the Telnet part is buggy and maybey the thread management is buggy. If I could have focus my problem a bit more I w would have done that.
comment on: http://stackoverflow.com/q/52164003
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91406207
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/52228241
has text: You open a file for reading and then immediately for writing. Opening a file for writing immediately truncates it and destroys its content. That is why nothing is read from the files - and nothing is written, too. You should either read everything from the file and only then open it for writing, or open two different files, copy the content, and then rename the new file.
type: Comment

http://stackoverflow.com/q/52142154
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52142169
has comment: http://stackoverflow.com/comment/91234182
has title: I'm not able to understand how Python3 map function for list is working?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52142169
tagged with: python-3.x
has body: I am trying to understand the map function on Python3. I wrote the below code: for ch in map(list,["66","67","68"]): print (ch) And I'm getting the below Output: ['6', '6'] ['6', '7'] ['6', '8'] Can anyone explain this in detail?
type: Question
tagged with: map-function
tagged with: python
possible better answer: http://stackoverflow.com/a/52142172
has answer: http://stackoverflow.com/a/52142172
tagged with: list

http://stackoverflow.com/q/52193873
has body: Here is the code that i am using to load workbook: import openpyxl from sys import argv genreUri = argv[1] genre = openpyxl.load_workbook(genreUri) Above code throw this error. Traceback (most recent call last): File "/Users/Chaudhary/projects/genre/backend/utils/openpyxl/cell.py", line 26, in &lt;module&gt; genre = openpyxl.load_workbook(genreUri) File "/usr/local/lib/python2.7/site-packages/openpyxl/reader/excel.py", line 251, in load_workbook ws_parser.parse() File "/usr/local/lib/python2.7/site-packages/openpyxl/reader/worksheet.py", line 130, in parse dispatcher[tag_name](element) File "/usr/local/lib/python2.7/site-packages/openpyxl/reader/worksheet.py", line 304, in parse_sheet_protection self.ws.protection = SheetProtection.from_tree(element) File "/usr/local/lib/python2.7/site-packages/openpyxl/descriptors/serialisable.py", line 100, in from_tree return cls(**attrib) TypeError: __init__() got an unexpected keyword argument 'undefined'
answer count: 0
score: 0
type: UnansweredQuestion
tagged with: openpyxl
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/91444997
tagged with: python
has title: Not able to load workbook using openpyxl
has comment: http://stackoverflow.com/comment/91398698
has comment: http://stackoverflow.com/comment/91451170

http://stackoverflow.com/comment/91238189
comment on: http://stackoverflow.com/a/52136129
type: Comment
score: 1
has text: Sounds plausible; the vectorization in the non-Numba approach probably becomes more effective as size increases. If you want to see exactly where the approaches differ, and you're not already using it, I'll recommend `line_profiler` (and [here's a good guide](https://github.com/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/01.07-Timing-and-Profiling.ipynb)); it's light-weight compared to many other profilers and easy to get started with.
type: AnswerComment

http://stackoverflow.com/q/52212827
downvote count: 0
accepted answer: http://stackoverflow.com/a/57262392
has answer: http://stackoverflow.com/a/52231117
possible better answer: http://stackoverflow.com/a/52231117
favorite count: 0
tagged with: dask
upvote count: 2
has body: I am new to dask and am trying to figure out how to reshape a dask array that I've obtained from a single column of a dask dataframe and am running into errors. Wondering if anyone might know of the fix (without having to force a compute)? Thanks! Example: import pandas as pd import numpy as np from dask import dataframe as dd, array as da df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]}) ddf = dd.from_pandas(df, npartitions=2) # This does not work - error ValueError: cannot convert float NaN to integer ddf['x'].values.reshape([-1,1]) # this works, but requires a compute ddf['x'].values.compute().reshape([-1,1]) # this works, if the dask array is created directly from a np array ar = np.array([1, 2, 3]) dar = da.from_array(ar, chunks=2) dar.reshape([-1,1])
tagged with: python
type: AnsweredQuestion
score: 2
type: Question
has title: Reshape a dask array (obtained from a dask dataframe column)
has answer: http://stackoverflow.com/a/57262392
answer count: 2

http://stackoverflow.com/a/63593839
has comment: http://stackoverflow.com/comment/117428297
upvote count: 7
answers question: http://stackoverflow.com/q/52232177
has comment: http://stackoverflow.com/comment/117425349
score: 7
has comment: http://stackoverflow.com/comment/121452169
downvote count: 0
type: Answer
has body: I fixed this by replacing all calls to asyncio.run with the asyncio_run below. It solved both of these errors for me: RuntimeError: Timeout context manager should be used inside a task RuntimeError: This event loop is already running pip install nest-asyncio import asyncio import nest_asyncio def asyncio_run(future, as_task=True): &quot;&quot;&quot; A better implementation of `asyncio.run`. :param future: A future or task or call of an async method. :param as_task: Forces the future to be scheduled as task (needed for e.g. aiohttp). &quot;&quot;&quot; try: loop = asyncio.get_running_loop() except RuntimeError: # no event loop running: loop = asyncio.new_event_loop() return loop.run_until_complete(_to_task(future, as_task, loop)) else: nest_asyncio.apply(loop) return asyncio.run(_to_task(future, as_task, loop)) def _to_task(future, as_task, loop): if not as_task or isinstance(future, asyncio.Task): return future return loop.create_task(future) A secondary goal was to be able to think of asyncio.run as promise.resolve from the JS world, or Task.Wait from the .NET world.
has comment: http://stackoverflow.com/comment/117428313

http://stackoverflow.com/comment/91360698
type: Comment
comment on: http://stackoverflow.com/q/52195887
score: 0
type: QuestionComment
has text: @ReblochonMasque I'm sorry. Please see the edit. These should be dictionary values which are dictionaries, not sets.

http://stackoverflow.com/comment/91425041
type: AnswerComment
type: Comment
has text: @Saurabh, try df = df.reset_index() before.
comment on: http://stackoverflow.com/a/52237970
score: 0

http://stackoverflow.com/comment/91237267
type: AnswerComment
comment on: http://stackoverflow.com/a/52143732
has text: A character class is convenient when you are really looking for single-character strings, but it appears from comments that the OP is actually looking for longer strings.
score: 0
type: Comment

http://stackoverflow.com/comment/91259016
type: Comment
type: AnswerComment
has text: thanks a lot, I am inexperience in programming, so ask weird questions. I thought that multithreading is the only option. I will read about subrocess and try to implement it.
comment on: http://stackoverflow.com/a/52154195
score: 0

http://stackoverflow.com/comment/91509858
type: Comment
type: QuestionComment
score: 0
has text: @NedU I try to use QGraphicsDropShadowEffect but I see that it is not possible since it applies to the edge of the widget and does not consider the text, I see that there is another possibility: to use QML, for that I ask you what QPushButton signals do you need or what properties? is to emulate the behavior of QPushButton using QML but that can be used with classic widgets.
comment on: http://stackoverflow.com/q/52266968

scikit-learn
tags question: http://stackoverflow.com/q/52116717
tags question: http://stackoverflow.com/q/52249158
tags question: http://stackoverflow.com/q/52260698
tags question: http://stackoverflow.com/q/52144245
tags question: http://stackoverflow.com/q/52132599
tags question: http://stackoverflow.com/q/52146092
tags question: http://stackoverflow.com/q/52211025
tags question: http://stackoverflow.com/q/52226200
tags question: http://stackoverflow.com/q/52159619
tags question: http://stackoverflow.com/q/52189626
tags question: http://stackoverflow.com/q/52159617
tags question: http://stackoverflow.com/q/52171610
tags question: http://stackoverflow.com/q/52250852
tags question: http://stackoverflow.com/q/52235024
tags question: http://stackoverflow.com/q/52116786
tags question: http://stackoverflow.com/q/52123026
tags question: http://stackoverflow.com/q/52209312
tags question: http://stackoverflow.com/q/52185337
tags question: http://stackoverflow.com/q/52123168
tags question: http://stackoverflow.com/q/52133732
tags question: http://stackoverflow.com/q/52196422
tags question: http://stackoverflow.com/q/52157223
tags question: http://stackoverflow.com/q/52124261
tags question: http://stackoverflow.com/q/52159536
tags question: http://stackoverflow.com/q/52215603
tags question: http://stackoverflow.com/q/52256360
tags question: http://stackoverflow.com/q/52267654
tags question: http://stackoverflow.com/q/52188561
tags question: http://stackoverflow.com/q/52129773
tags question: http://stackoverflow.com/q/52173203
tags question: http://stackoverflow.com/q/52168051
tags question: http://stackoverflow.com/q/52155419
tags question: http://stackoverflow.com/q/52250115
tags question: http://stackoverflow.com/q/52239610
tags question: http://stackoverflow.com/q/52173269
tags question: http://stackoverflow.com/q/52198701
tags question: http://stackoverflow.com/q/52132774
tags question: http://stackoverflow.com/q/52252107
tags question: http://stackoverflow.com/q/52224813
tags question: http://stackoverflow.com/q/52146685
tags question: http://stackoverflow.com/q/52194375
tags question: http://stackoverflow.com/q/52250029
tags question: http://stackoverflow.com/q/52236768
tags question: http://stackoverflow.com/q/52178328
tags question: http://stackoverflow.com/q/52262800
tags question: http://stackoverflow.com/q/52144670
tag name: scikit-learn
tags question: http://stackoverflow.com/q/52151548
tags question: http://stackoverflow.com/q/52151765
tags question: http://stackoverflow.com/q/52270766
tags question: http://stackoverflow.com/q/52254126
tags question: http://stackoverflow.com/q/52125784
tags question: http://stackoverflow.com/q/52166308
tags question: http://stackoverflow.com/q/52237668
type: Tag
tags question: http://stackoverflow.com/q/52173064
tags question: http://stackoverflow.com/q/52245357
tags question: http://stackoverflow.com/q/52194407
tags question: http://stackoverflow.com/q/52176616
tags question: http://stackoverflow.com/q/52206267
tags question: http://stackoverflow.com/q/52159019
tags question: http://stackoverflow.com/q/52186091
tags question: http://stackoverflow.com/q/52266473
tags question: http://stackoverflow.com/q/52149376
tags question: http://stackoverflow.com/q/52236640
tags question: http://stackoverflow.com/q/52153979
tags question: http://stackoverflow.com/q/52220426
tags question: http://stackoverflow.com/q/52251651
tags question: http://stackoverflow.com/q/52269187
tags question: http://stackoverflow.com/q/52268430
tags question: http://stackoverflow.com/q/52267797
tags question: http://stackoverflow.com/q/52244317
tags question: http://stackoverflow.com/q/52118969
tags question: http://stackoverflow.com/q/52254618
tags question: http://stackoverflow.com/q/52214779
tags question: http://stackoverflow.com/q/52261948
tags question: http://stackoverflow.com/q/52196856
tags question: http://stackoverflow.com/q/52153256
tags question: http://stackoverflow.com/q/52209069
tags question: http://stackoverflow.com/q/52217151

http://stackoverflow.com/q/52228116
type: Question
score: 0
has body: From the python shell I can add a new post to my database but from the Django admin panel it's showing a type error. I am using Django with MySQL. with SQLite3 It's working fine but what is the problem with MySQL? Here is the error with complete trackback: TypeError at /admin/blog/post/1/change/ not all arguments converted during string formatting Request Method: POST Request URL: http://127.0.0.1:8000/admin/blog/post/1/change/ Django Version: 2.1.1 Exception Type: TypeError Exception Value: not all arguments converted during string formatting Exception Location: F:\myproject\venv\lib\site- packages\django\db\models\lookups.py in process_lhs, line 157 Python Executable: F:\myproject\venv\Scripts\python.exe Python Version: 3.6.4 Python Path: ['F:\\myproject', 'F:\\myproject\\venv\\Scripts\\python36.zip', 'C:\\Users\\Anuj\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Anuj\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Anuj\\AppData\\Local\\Programs\\Python\\Python36', 'F:\\myproject\\venv', 'F:\\myproject\\venv\\lib\\site-packages', 'F:\\myproject\\venv\\lib\\site-packages\\setuptools-39.1.0- py3.6.egg', 'F:\\myproject\\venv\\lib\\site-packages\\pip-10.0.1-py3.6.egg'] Server time: Fri, 7 Sep 2018 18:28:47 +0000 Here is the complete traceback of my error complete traceback Django admin panel
has comment: http://stackoverflow.com/comment/91406113
tagged with: python
has comment: http://stackoverflow.com/comment/91407790
has title: Cannot create a new post from django admin panel, but from python shell it's created
answer count: 0
type: UnansweredQuestion
tagged with: mysql
tagged with: django
has comment: http://stackoverflow.com/comment/91427941
has comment: http://stackoverflow.com/comment/91415240

pickle
tags question: http://stackoverflow.com/q/52241188
tags question: http://stackoverflow.com/q/52166572
tags question: http://stackoverflow.com/q/52180055
type: Tag
tags question: http://stackoverflow.com/q/52130635
tags question: http://stackoverflow.com/q/52185507
tag name: pickle

http://stackoverflow.com/comment/99838638
type: AnswerComment
comment on: http://stackoverflow.com/a/52186874
type: Comment
has text: If I understood well, to sum up your first four paragraphs, `pickle.dumps(obj)` checks that `getattr(sys.modules[type(obj).__module__], type(obj).__qualname__) == type(obj)`.
score: 0

http://stackoverflow.com/a/52262676
score: 1
answers question: http://stackoverflow.com/q/52261948
type: AcceptedAnswer
has body: You are fitting a new TfidfVectorizer on test data. This will give wrong results. You should use the same object which you fitted on train data. Do this: vec_train = TfidfVectorizer() X_train = vec_train.fit_transform(df_train['text']) X_test = vec_train.transform(df_test['text']) After that, as @MohammedKashif said, you need to first train your LogisticRegression model and then predict on test. clf.fit(X_train, y_train) y_pred = clf.predict(X_test) After that you can use the scoring code without any errors.
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52261948

http://stackoverflow.com/comment/91303539
type: QuestionComment
has text: What is `m` here?
comment on: http://stackoverflow.com/q/52176575
score: 0
type: Comment

http://stackoverflow.com/comment/91382984
has text: This doesn't work, throws an error saying `TypeError: invalid type comparison `
comment on: http://stackoverflow.com/a/52217159
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52248835
type: Answer
upvote count: 4
has body: Should be if number in primes (not if number == primes)
downvote count: 0
answers question: http://stackoverflow.com/q/52248806
score: 4

http://stackoverflow.com/a/52151926
type: Answer
has body: You can use np.tile and feed to pd.DataFrame: res = pd.DataFrame(np.tile(df.values, (1, 10)), columns=[f'A{i:02d}' for i in range(1, 11)]) print(res) A01 A02 A03 A04 A05 A06 A07 A08 A09 A10 0 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2 1.3 1.3 1.3 1.3 1.3 1.3 1.3 1.3 1.3 1.3 I advise not to repeat column names, as this may cause problems in subsequent logic.
score: 0
answers question: http://stackoverflow.com/q/52151831

http://stackoverflow.com/comment/91238425
type: QuestionComment
has text: Maybe a glance for a very old post: https://stackoverflow.com/questions/1133857/how-accurate-is-pythons-time-sleep ?
comment on: http://stackoverflow.com/q/52144249
score: 0
type: Comment

http://stackoverflow.com/q/52250852
type: Question
has answer: http://stackoverflow.com/a/52251065
downvote count: 0
tagged with: scikit-learn
favorite count: 0
answer count: 1
tagged with: python
has body: I'm trying to use Naive Bayes algorithm for one of my requirements. In this, I have planned to use "One-hot Encode" for hyper plane. I have used the following code for running my algorithm. But, I'm not sure how to use "One-hot Encode". Please find the below code: from sklearn.preprocessing import MultiLabelBinarizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import BernoulliNB from sklearn.metrics import confusion_matrix def load_data(filename): x = list() y = list() with open(filename) as file: file.readline() for line in file: line = line.strip().split(',') y.append(line[1]) x.append(line[0].split()) return x, y X_train, y_train = load_data('/Users/Desktop/abc/train.csv') X_test, y_test = load_data('/Users/Desktop/abc/test.csv') onehot_enc = MultiLabelBinarizer() onehot_enc.fit(X_train) bnbc = BernoulliNB(binarize=None) bnbc.fit(onehot_enc.transform(X_train), y_train) score = bnbc.score(onehot_enc.transform(X_test), y_test) print("score of Naive Bayes algo is :" , score) Can anyone please suggest me whether the above written code is correct ?
accepted answer: http://stackoverflow.com/a/52251065
upvote count: 2
score: 2
type: AnsweredQuestion
has title: How to use One-hot Encode while using NaiveBayes algorithm?

http://stackoverflow.com/q/52264326
favorite count: 0
upvote count: 0
type: UnansweredQuestion
has body: I have some time stamped financial data as shown below: Sample Data: transaction_type transaction_announced_date transaction_size_USDmm target_company_name ------------------ ---------------------------- ------------------------ --------------------- B 11/12/2017 8000 Company A A 4/19/2017 NULL Company A A 2/12/2016 200 Company A A 5/24/2016 NULL Company A A 6/1/2016 3500 Company A B 7/7/2016 NULL Company A A 9/22/2016 30 Company A A 12/4/2014 2800 Company A A 1/16/2015 1691 Company B A 3/22/2015 NULL Company B B 7/31/2015 1000 Company C A 8/19/2015 NULL Company C A 8/25/2015 NULL Company C For companies that have had a transaction B, I want to find the sum of that company's prior transactions A (based on announced dates) and add that value in a new column called 'sum_prior_trans_A'. Expected Results: transaction_type transaction_announced_date transaction_size_USDmm target_company_name sum_prior_trans_A ------------------ ---------------------------- ------------------------ --------------------- ------------------- B 11/12/2017 8000 Company A 6530 B 7/7/2016 NULL Company A 2830 B 7/31/2015 1000 Company C NaN Current approach: #input dataframe trans_data #add a new column that is the sum of all prior transactions A. #Will later drop all transactions A rows to be only left with transactions B as desired. trans_data['sum_previous_private_placements'] = trans_data.groupby(['target_company_name', 'transaction_type', 'transaction_announced_date']).filter(lambda row: (trans_data['target_company_name'] == row['target_company_name']) &amp; (trans_data['transaction_announced_date'] == row['transaction_announced_date']) &amp; (trans_data['transaction_type'] == 'A'))['transaction_size_USDmm'].sum() I am receiving the following error: ValueError: Can only compare identically-labeled Series objects How can I find the sum of prior transactions A for each row (company) and add that value in a new column called 'sum_prior_trans_A' without running into misaligned Series object erro…
tagged with: python
linked to: http://stackoverflow.com/q/16353729
has comment: http://stackoverflow.com/comment/91477029
type: Question
has title: Comparing misaligned Series object
downvote count: 2
score: -2
answer count: 1
has answer: http://stackoverflow.com/a/52281696
tagged with: pandas

http://stackoverflow.com/q/52211716
answer count: 0
has body: So I have had success deploying django applications on python 2.7, but this is my first time trying it with 3.6 and django 2.1, and for some reason apache keeps getting me this error: [Thu Sep 06 17:23:13.591266 2018] [core:notice] [pid 18011] AH00051: child pid 18164 exit signal Aborted (6), possible coredump in /etc/apache2 Fatal Python error: Py_Initialize: Unable to get the locale encoding I have looked over the internet but cant find a solution. Here is my VirtualHost: Listen 8081 &lt;VirtualHost *:8081&gt; ServerName mysite.com WSGIDaemonProcess Project python-home=/home/happyuser/myproject_tst/venv python-path=/home/happyuser/myproject_tst WSGIProcessGroup myproject WSGIScriptAlias / /home/happyuser/myproject_tst/myproject/myproject/wsgi.py ErrorLog /home/happyuser/apache_errors.log Alias /static /home/happyuser/myproject_tst/myproject/static/ &lt;Directory /home/happyuser/myproject_tst/myproject&gt; &lt;Files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; &lt;Directory /home/happyuser/myproject_tst/myproject/static&gt; Options Indexes FollowSymLinks AllowOverride None Require all granted &lt;/Directory&gt; LogLevel debug &lt;/VirtualHost&gt; Any suggestion is much appreciated
tagged with: mod-wsgi
type: Question
downvote count: 0
has title: Apache + Wsgi + Django 2.1 + Virtualenv 3 = Fatal Python error: Py_Initialize: Unable to get the locale encoding
score: 1
favorite count: 0
tagged with: python-3.x
tagged with: django-wsgi
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python

http://stackoverflow.com/q/52231471
tagged with: python
has comment: http://stackoverflow.com/comment/91412471
has comment: http://stackoverflow.com/comment/91412424
has body: I'm trying to write a very simple keylogger but when I run the program, it throws me an error I can't decode. It says: ArgumentError: argument 3: : int too long to convert. I can't understand why, I take it my key_presses arguments are being converted (in this case their not) into ints, but why are they not? here's the full error traceback: https://gyazo.com/2995334b1859724df213e7e39033fc81 import keyboard file = open("Tips.txt", "w") keyboard_loop = True while keyboard_loop is True: if keyboard.is_pressed("a") or keyboard.is_pressed("ctrl + a"): file.append("w") if keyboard.is_pressed("b") or keyboard.is_pressed("ctrl + b"): file.append("b") if keyboard.is_pressed("c") or keyboard.is_pressed("ctrl + c"): file.append("c") if keyboard.is_pressed("d") or keyboard.is_pressed("ctrl + d"): file.append("d") if keyboard.is_pressed("e") or keyboard.is_pressed("ctrl + e"): file.append("e") if keyboard.is_pressed("f") or keyboard.is_pressed("ctrl + f"): file.append("f") if keyboard.is_pressed("g") or keyboard.is_pressed("ctrl + g"): file.append("g") if keyboard.is_pressed("h") or keyboard.is_pressed("ctrl + h"): file.append("h") if keyboard.is_pressed("i") or keyboard.is_pressed("ctrl + i"): file.append("i") if keyboard.is_pressed("j") or keyboard.is_pressed("ctrl + j"): file.append("j") if keyboard.is_pressed("k") or keyboard.is_pressed("ctrl + k"): file.append("k") if keyboard.is_pressed("l") or keyboard.is_pressed("ctrl + l"): file.append("l") if keyboard.is_pressed("m") or keyboard.is_pressed("ctrl + m"): file.append("m") if keyboard.is_pressed("n") or keyboard.is_pressed("ctrl + n"): file.append("n") if keyboard.is_pressed("o") or keyboard.is_pressed("ctrl + o"): file.append("o") if keyboard.is_pressed("p") or keyboard.is_pressed("ctrl + p"): file.append("p") if keyboard.is_pressed("q") or keyboard.is_pressed("ctrl + q"): file.append("q") if keyboard.is_pressed("r") or keyboard.is_pressed("ctrl + r"): file.append("r") if keyboard.is_pressed("s") or keyboard.is_pressed("c…
type: Question
has comment: http://stackoverflow.com/comment/91412479
score: 0
has comment: http://stackoverflow.com/comment/91412525
has title: Python Keyboard module
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/52199534
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52199157
answers question: http://stackoverflow.com/q/52199157
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91356886
has body: You need to create a SlugField and then write a save() function to create slug on the basis of some field and then it should work fine. from django.utils.text import slugify class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(max_length=40) text = RichTextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title # Write the save() method def save(self): if not self.id: self.slug = slugify(self.title) super(Post, self).save() def get_update_url(self): return reverse('post:update', kwargs={'slug': self.slug})
upvote count: 1

http://stackoverflow.com/comment/92241278
has text: Okay, I will give it a shot and update the answer if I have a working solution
type: Comment
comment on: http://stackoverflow.com/a/52174883
score: 0
type: AnswerComment

http://stackoverflow.com/q/52223432
downvote count: 0
type: UnansweredQuestion
tagged with: physics
tagged with: odeint
has body: I have a uni assignment where I have to create model for lunar descent. Model starts from a height and descends with two engines who are placed under an angle. This is the part of the code I have issues with: F1 = f*np.array([1, 1, 0.5, 0, 0, 1, 1]) #f-thrust in newtons F2 = f*np.array([1, 1, 0.5, 0, 0, 1, 1]) #F1 and F2 regime of engines for each time step(percentage of thrust) t = np.arange(0, np.size(F1), dt) #time domain #a,b - angles of engines according to global coordinate system #s0x, v0x, s0y, v0y, fi0, omg0 - initial values #m - mass def model_engine(u, t): x, vx, y, vy, phi, w = u d1 = vx d2 = (1/(m))*(F1*np.cos((a)) - F2*np.cos((b))) d3 = vy d4 = (1/(m))*(F1*np.sin((a)) + F2*np.sin((b))) + g d5 = w d6 = (F1*np.cos(a)*(h/2) - F1*np.sin(a)*(w/2) + F2*np.sin(b)*(w/2) - F2*np.cos(b)*(h/2))/((1/12)*(m)*h**2) return np.array([d1, d2, d3, d4, d5, d6]) U = odeint(model_engine, [s0x, v0x, s0y, v0y, fi0, omg0], t) I dont know how to implement diferent F1 for each timestep in definition? I get ValueError: setting an array element with a sequence. The same is with the variable mass, it depends on engines regime. The solution gives angle of spacecraft (d6). Equations written in this way always give a and b as 45 degrees which is obviously not correct because the spacecraft rotates. How can I take solution (angle) from previous step and put it in current step? See photo for clarification
tagged with: python
has title: Can you solve ode with variable constants?
tagged with: ode
score: 1
has answer: http://stackoverflow.com/a/52226559
type: Question
tagged with: numpy
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91397000

http://stackoverflow.com/a/52224811
answers question: http://stackoverflow.com/q/52224142
downvote count: 0
type: Answer
upvote count: 6
score: 6
has body: You could consider using where: df.environment.where((~df.environment.isnull()) &amp; (df.event != 'add_rd'), 'RD', inplace=True) If the condition is not met, the values is replaced by the second element.

http://stackoverflow.com/q/52161219
has answer: http://stackoverflow.com/a/52161281
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/52161281
has title: How can I make line plots appear on the same figure instead of on different figures?
favorite count: 0
tagged with: python
tagged with: plot
type: AnsweredQuestion
has body: I have a dataframe as follows: data = {'Contact':['Email', 'SMS', 'Email', 'Other', 'In Person', 'Other', 'SMS', 'Other', 'Phone', 'Email', 'Other', 'Phone', 'Phone', 'In Person', 'Email', 'Email', 'Other', 'Other', 'Other', 'Phone', 'Other', 'Email', 'Other', 'Other'], 'Age': [34, 50, 30, 43, 38, 43, 26, 37, 30, 30, 34, 38, 48, 30, 46, 37, 29, 36, 31, 31, 53, 25, 37, 25]} data = pd.DataFrame(data, columns=['Contact', 'Age']) data I want to bin the Age column into 10 groups, and then plot the percentage of each group as lineplot, for each unique Contact value separately. Since there are 5 unique values in Contact, which are 'Email', 'SMS', 'Other', 'In Person', 'Phone', I expect there to be 1 plot in which there should be 5 lines, one each for each of the unique Contact values. But I am getting the following: contacts = data['Contact'].unique() for c in contacts: df = data[data['Contact']==c] y,binEdges=np.histogram(df['Age'], bins=10) y = 100*y/sum(y) bincenters = 0.5*(binEdges[1:]+binEdges[:-1]) plt.plot(bincenters,y,label=c) plt.xlabel('Age') plt.ylabel('Percentage count') plt.show()
score: 1
tagged with: matplotlib
upvote count: 1
type: Question

http://stackoverflow.com/q/52239489
tagged with: cuda
tagged with: numba-pro
score: 3
answer count: 0
upvote count: 3
type: Question
linked to: http://stackoverflow.com/q/6913206
has comment: http://stackoverflow.com/comment/91427855
has title: what causes CUDA_ERROR_LAUNCH_TIMEOUT in python numba?
has comment: http://stackoverflow.com/comment/112944350
duplicate of: http://stackoverflow.com/q/6913206
downvote count: 0
has comment: http://stackoverflow.com/comment/91427981
has comment: http://stackoverflow.com/comment/91427928
has comment: http://stackoverflow.com/comment/91427903
has comment: http://stackoverflow.com/comment/91427879
favorite count: 0
has comment: http://stackoverflow.com/comment/91427901
has comment: http://stackoverflow.com/comment/91428694
has comment: http://stackoverflow.com/comment/91427852
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91428102
tagged with: numba
tagged with: python
has body: I am experimenting how to use cuda inside numba. However there is something occurred in numba that I do not understand. Here is my code from numba import cuda @cuda.jit def matmul(A, B, C): """Perform square matrix multiplication of C = A * B """ d=cuda.local.array((3,3),dtype=numba.float64) i, j = cuda.grid(2) if i &lt; C.shape[0] and j &lt; C.shape[1]: tmp = 0. for k in range(A.shape[1]): tmp += A[i, k] * B[k, j] C[i, j] = tmp This is the matrix function I self defined for testing using numba.cuda. Before running the tests, I also loaded the arrays in the following code: import numpy as np a=np.random.rand(2000,2000) b=np.random.rand(2000,2000) c=np.empty((2000,2000)) a1=cuda.to_device(a) b1=cuda.to_device(b) c1=cuda.to_device(c) Then I used the following code for experiment: from time import time count =0 start=time() for i in range(2000): matmul[(256,256),(16,16)](a1,b1,c1) count +=1 print(count) The for loops ran just fine for the first 1028 runs. However it gave me an error at the 1029th run and the error message is as the following: Here is my cuda information called from numba.cuda from numba import cuda gpu = cuda.get_current_device() print("name = %s" % gpu.name) print("maxThreadsPerBlock = %s" % str(gpu.MAX_THREADS_PER_BLOCK)) print("maxBlockDimX = %s" % str(gpu.MAX_BLOCK_DIM_X)) print("maxBlockDimY = %s" % str(gpu.MAX_BLOCK_DIM_Y)) print("maxBlockDimZ = %s" % str(gpu.MAX_BLOCK_DIM_Z)) print("maxGridDimX = %s" % str(gpu.MAX_GRID_DIM_X)) print("maxGridDimY = %s" % str(gpu.MAX_GRID_DIM_Y)) print("maxGridDimZ = %s" % str(gpu.MAX_GRID_DIM_Z)) print("maxSharedMemoryPerBlock = %s" % str(gpu.MAX_SHARED_MEMORY_PER_BLOCK)) print("asyncEngineCount = %s" % str(gpu.ASYNC_ENGINE_COUNT)) print("canMapHostMemory = %s" % str(gpu.CAN_MAP_HOST_MEMORY)) print("multiProcessorCount = %s" % str(gpu.MULTIPROCESSOR_COUNT)) print("warpSize = %s" % str(gpu.WARP_SIZE)) print("unifiedAddressing = %s" % str(gpu.UNIFIED_ADDRESSING)) print("pciBusID = %s" % str(gpu.PCI_BUS_ID)) print("…

http://stackoverflow.com/comment/127713894
type: Comment
has text: @calocedrus Thanks, updated, feel free to update the example if you have the rights next time :)
comment on: http://stackoverflow.com/a/52212995
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91404907
type: QuestionComment
comment on: http://stackoverflow.com/q/52227707
type: Comment
score: 2
has text: What were you expecting `"shiprow{}".format(i=range(0,10))` to do?

http://stackoverflow.com/a/52214736
has comment: http://stackoverflow.com/comment/91405475
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/52210917
has body: You should refactor your views.py to return a single queryset of Requisition objects that match your conditions, annotated with the aggregated price data you want to provide. Then you need to refactor your html template to iterate over the single queryset. Using the Django ORM to its max will make your code much shorter, and will run much faster. In views.py from django.db.models import Sum def pending_action(request): user_req_lines_incomplete = RequisitionLine.objects.filter(parent_req__username=request.user).exclude(status__status='Completed')) user_reqs = Requisition.objects.filter(par_req_line__in=user_requisition_lines_incomplete).annotate(aggregated_price=Sum('par_req_line__total_price')) return render(request, 'req/pending_action.html', {'user_reqs':user_reqs}) Please note that there's a little trickery going on under the hood in the Django ORM when you do a filter on a related model before annotating on that model. When you filter(par_req_line__in that also means that the annotation that happens later in the line will only be calculated on par_req_lines that match the filter condition. So your aggregation will sum only the lines that are in user_req_lines_incomplete. I'm 95% sure that's what you want, but feel free to clarify if you're looking for a different condition. I struggled a bit to follow all of your code with the many for loops and names. (No judgement.) In pending_action.html Pending Action {% for req in user_reqs %} {{req}} {% for line in req.par_req_line.all %x} {{line}} {{line.description}} {{line.quantity}} {{line.total_price}} {{line.status}} {% endfor %} Total price: {{req.aggregated_price}} {% endfor %} Hope that helps.
has comment: http://stackoverflow.com/comment/91397502
answers question: http://stackoverflow.com/q/52210917
has comment: http://stackoverflow.com/comment/91396804
has comment: http://stackoverflow.com/comment/91396265
type: Answer
has comment: http://stackoverflow.com/comment/91395932
has comment: http://stackoverflow.com/comment/91395138
has comment: http://stackoverflow.com/comment/91397029

http://stackoverflow.com/a/52233083
has body: So my best guess is that you are facing permission issues. Why don't you copy the file to C:\Users\akjain> and run python TweetExtract.py &gt; your-file.txt
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52232592
accepted answer of: http://stackoverflow.com/q/52232592
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52235410
type: UnansweredQuestion
type: Question
has body: I want to intialize a array with random gaussian with standard deviation of 0.08 in python. I was able to find something like this self.biases = [np.random.randn(y, 1) for y in sizes[1:]] However it for standard deviation of 1.
tagged with: basis
has answer: http://stackoverflow.com/a/52235460
tagged with: gaussian
answer count: 1
tagged with: neural-network
score: 0
has title: Random Gaussian with standard deviation
tagged with: python

http://stackoverflow.com/q/52176813
upvote count: 1
score: 1
has title: Import variable from python script to jupyter ipython notebook
type: Question
has body: I am newbie to python and searched for 2 days to get solution but could not get find any solution. Please help me. I have two python(newkmeans.py,newbisecting.py) files and one ipython jupyter notebook. I am running newbiecting.py from ipython notebook by calling it as %newbisecting.py which in turn calls newkmeans.py file. Now newkmeans.py file generates few set of variables like for example list values list1. I want to access this list1[] in ipython jupyter notebook. How can I do this? Please help me out. I have tried using from newkmeans import list1 in ipython juypter notebook but could not get any results.
downvote count: 0
tagged with: sharing
tagged with: variables
has comment: http://stackoverflow.com/comment/91303970
tagged with: python
favorite count: 0
tagged with: jupyter-notebook
answer count: 0
has comment: http://stackoverflow.com/comment/91304426
type: UnansweredQuestion

http://stackoverflow.com/q/52221458
tagged with: gis
accepted answer: http://stackoverflow.com/a/52221895
type: AnsweredQuestion
has title: When to transform GPS co-ordinates
score: 1
has answer: http://stackoverflow.com/a/52221895
linked to: http://stackoverflow.com/q/43892459
type: Question
upvote count: 1
answer count: 1
downvote count: 0
has body: I have no real experience with GIS data, so when what I believed to be a simple problem has turned out to have more subtleties to it, I am dangerously unprepared! I want to be able to classify a GPS position as inside/outside a polygon defined by GPS co-ordinates. It turns out this is the well-known (but not to me) point-in-polygon problem. I have read many questions/answers on https://gis.stackexchange.com/ (and here e.g. this). Shapely seems a good solution, but assumes the co-ordinates are on the same cartesian plane, i.e. not GPS? So I would first need to transform my GPS points to UTM points. Do I need to introduce this extra step, however, if the points being compared (i.e. the point and the polygon) are always going to be naturally within the same UTM zone. They should always be within the same town/city, so can I just leave them as GPS and use the lat/long co-ordinates in Shapely? I also came across this UTM-WGS84 converter so I could convert my lat/long pairs using this package, and then use those UTM pairs in Shapely, but I would like to avoid any extra dependencies where possible.
tagged with: latitude-longitude
favorite count: 0
tagged with: python
tagged with: gps
tagged with: utm

http://stackoverflow.com/q/52116574
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91184540
score: 3
upvote count: 3
has body: I am trying to plot some weather data over a map using Basemap (I'm open to trying cartopy also) on Python. Right now, my weather data looks like this. My data source is basically an array with each position corresponding to a square of the grid and each value indicating the color that square should be. The code used to generate this image looks like this, where each square of the grid equals to 1000 m: grid_0 = np.asarray(dec.split()) grid_1=np.reshape(grid_0,(n_cols,n_rows)) grid_2 = grid_1.astype(float) # Make plot plt.figure(figsize=(30,30)) fig, ax = plt.subplots() plt.axis('off') cax = ax.imshow(grid_2, interpolation='nearest', cmap=cmap) I have the information on where geographically the lower corner of the grid is located. I believe that the best way of plotting this on a map is somehow using the contourf() function, but I'm quite new to Basemap and can't find a way of transforming this to something that contourf() can understand. To lpot the map I'm using Basemap, where lon_air and lat_air are the coordinates of a certain airport: fig=figure(1, figsize=(19, 15)) m = Basemap(projection='cyl', llcrnrlon=lon_air-25, llcrnrlat=lat_air-15, urcrnrlon=lon_air+25, urcrnrlat=lat_air+15, resolution='h', area_thresh=10000) m.drawstates(linewidth=0.5, color='black', zorder=4) m.drawcountries(linewidth=2.0, color='white', zorder=3) m.drawmapboundary(fill_color='#e5f5ff') m.fillcontinents(color='#DFDFDF', zorder=1) m.scatter(lon_air, lat_air,marker='o',color='k', zorder=10) x0, y0 = lon_air-((360*920)/(4*np.pi*6371)),lat_air-((360*920)/(4*np.pi*6371)) x1, y1 = lon_air+((360*920)/(4*np.pi*6371)), lat_air+((360*920)/(4*np.pi*6371)) im = plt.imshow(plt.imread('./pngs/9905.png'), extent=(x0, x1, y0, y1), zorder=2) plt.show() I will edit the post if somebody think that more details are needed. Thanks in advance to everyone!
has answer: http://stackoverflow.com/a/52196978
type: Question
tagged with: weather
tagged with: contourf
has title: Weather data over maps
has comment: http://stackoverflow.com/comment/91244795
has comment: http://stackoverflow.com/comment/91208062
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/27275669
tagged with: matplotlib-basemap
favorite count: 0

http://stackoverflow.com/q/52128294
has comment: http://stackoverflow.com/comment/91207090
upvote count: 1
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52136343
accepted answer: http://stackoverflow.com/a/52136343
favorite count: 0
has comment: http://stackoverflow.com/comment/91216777
has comment: http://stackoverflow.com/comment/91207203
tagged with: python
has comment: http://stackoverflow.com/comment/91207242
has body: In my script I have a while True loop that constantly checks a mysql database. My problem is, that this while True loop seems to run only once! I added variable i, but it's also stuck at 0. Can anyone help me? import mysql.connector import serial import threading import time mydb = mysql.connector.connect( host="", user="", passwd="", database="" ) cursor = mydb.cursor(buffered=True) getData = "SELECT * FROM log" ser = serial.Serial( port="/dev/tty.usbmodem14111" ) def serial_read(): while True: line = ser.readline().decode('utf-8') return line def serial_write(mode): while serial_read().startswith("OK") == False: print(f"Set: {handle_data().mode}") ser.write(f"Set: {handle_data().mode}".encode('utf-8')) return True def handle_data(): modeOld = None i = 0 while True: i += 1 cursor.execute(getData) mydb.commit() values = cursor.fetchall() mode = values[-1][1] print(serial_read()) if mode != modeOld: print("{}: {}".format(i, mode)) serial_write(mode) modeOld = mode if serial_write(mode) == True: print("Mode Set successfully!") serial_read_thread = threading.Thread(target=serial_read()) handle_data_thread = threading.Thread(target=handle_data()) serial_read_thread.start() handle_data_thread.start() Edit 1: I deleted the try except block Edit 2: Now I know that it's in the if mode != modeOld-block. I just can't find the error there. Edit 3: I now use threading. It still seems to iterate only once
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91207186
has title: Why is my while True loop stcuk at i = 0?
has comment: http://stackoverflow.com/comment/91207245
has comment: http://stackoverflow.com/comment/91207223
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91207217
score: 1
has comment: http://stackoverflow.com/comment/91220428
has comment: http://stackoverflow.com/comment/91207288
linked to: http://stackoverflow.com/q/17553543
type: Question

http://stackoverflow.com/q/52147358
upvote count: 1
tagged with: python
downvote count: 1
type: Question
tagged with: pyspark
answer count: 1
has answer: http://stackoverflow.com/a/52149408
score: 0
tagged with: apache-spark
tagged with: sql
has body: My table is like below: +--------+-----+----+----------+ | grDate|Items|rate| unitName| +--------+-----+----+----------+ |20131222| SOY|34.7|Samastipur| |20131223| SOY|34.7|Samastipur| |20131224| SOY|34.7|Samastipur| |20131225| SOY|34.0|Samastipur| |20131225| SOY|34.7|Samastipur| |20131227| SOY|34.7|Samastipur| |20131228| SOY|34.7|Samastipur| |20131229| SOY|34.7|Samastipur| |20131230| SOY|34.6|Samastipur| |20131230| SOY|34.7|Samastipur| |20131231| SOY|34.7|Samastipur| |20140101| SOY|34.6|Samastipur| |20140102| SOY|34.6|Samastipur| |20140103| SOY|34.6|Samastipur| |20140106| SOY|34.6|Samastipur| |20140107| SOY|34.6|Samastipur| |20140110| SOY|33.9|Samastipur| |20140111| SOY|33.9|Samastipur| |20140112| SOY|33.9|Samastipur| |20140113| SOY|33.9|Samastipur| +--------+-----+----+----------+ only showing top 20 rows What I want is to calculate avg of rate column week wise and create a new table having those values. I am trying to execute this query spjsoya.createOrReplaceTempView("spjsoya") spark.sql("SELECT grDate , (sum(total)/(WEEK(MAX(rate)) - WEEK(MIN(rate))+1)) AS rate FROM spjsoya WHERE YEAR(grDate)='2013' GROUP BY grDate").show() but it gives me error pyspark.sql.utils.AnalysisException: u"Undefined function: 'WEEK'. This function is neither a registered temporary function nor a permanent function registered in the database 'default'.; line 1 pos 29" How can I write the correct query to take avg week wise ?
favorite count: 0
has comment: http://stackoverflow.com/comment/91246251
type: UnansweredQuestion
has title: How to calculate average per week in pyspark from a table?

http://stackoverflow.com/a/52242881
has body: Based on your description, it looks like you would want to do the following: l = [] for _ in range(num): l.append(input().split()) Please note that split() is returning strings (that were parts of the input) and not integer numbers. If you want to have a list of lists of numbers (i.e., float or int), then you will want to convert strings to numbers of appropriate type: l = [] for _ in range(num): l.append(list(map(float, input().split()))) # float &lt;-&gt; int (if needed) or, if you insist on one-liners: l = [list(map(float, input().split())) for _ in range(num)] Also note that Python does not have the notion of 2D arrays. That is a concept in the numpy package. You also tagged your question with numpy. So, if your purpose is to input a square 2D numpy array you could do the following: import numpy as np l = np.array([input('Enter line: ').split() for _ in range(num)], dtype=np.float) Example: In [18]: np.array([input('Enter line: ').split() for _ in range(num)], dtype=np.float) Enter line: 1 2 3 Enter line: 4 5 6 Enter line: 7 8 9 Out[18]: array([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]])
answers question: http://stackoverflow.com/q/52242405
type: Answer
accepted answer of: http://stackoverflow.com/q/52242405
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52247573
score: -1
has title: how to access object's method inside a with statement?
type: Question
has comment: http://stackoverflow.com/comment/91443128
linked to: http://stackoverflow.com/q/5093382
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52247771
tagged with: python
has body: I am trying to create a class to be used with the 'with' statement in python 3 but inside the 'with' statement I don't have access to the object or the methods. For example, Running the following code: class Openizer: def __init__(self, something): self._something = something def __enter__(self): print('entered') def __exit__(self, exc_type, exc_value, traceback): print('exited') def print_something(self): print(self._something) with Openizer('something') as op: op.print_something() raises the following exception: Traceback (most recent call last): File "openizer.py", line 16, in &lt;module&gt; op.print_something() AttributeError: 'NoneType' object has no attribute 'print_something' If I try to print(op) it prints 'None'. Why is that? am I using the with statement wrong? what is the correct way? Is it possible to instantiate a class with the 'with' statement and inside the 'with' statement call the instantiated object's methods? Consider the open() function, it instantiated a file object which can than be read from or written to, I'd like to do something similar.
tagged with: python-3.x
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/5093382
tagged with: methods
tagged with: with-statement
downvote count: 1
has comment: http://stackoverflow.com/comment/91443163

http://stackoverflow.com/a/52130809
has body: import json names = requests.get('https://api') Json = json.loads(names) filtered_names = {k:v for k,v in Json.items() if "Pitbull" in v} Now one question in our mind must come what does this json.py do? Well for Answer to this question you can refer enter link description here Hope this doesn't throw AttributeError
type: Answer
answers question: http://stackoverflow.com/q/52130720
score: 0

http://stackoverflow.com/q/52185205
downvote count: 2
upvote count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/91322026
has answer: http://stackoverflow.com/a/52185453
score: -1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52189399
has title: Django how to render dictionary in the template
tagged with: python
has comment: http://stackoverflow.com/comment/91326692
favorite count: 0
has body: I have this dictionary data={ 'user': user.username, 'punti_capitano': {'nome_capitano':team.capitano.display_name,'lista_punti':point_cap_list}, 'punti_rider2': {'nome_rider2':team.rider_2.display_name,'lista_punti':point_rider2_list}, 'punti_rider3': {'nome_rider3':team.rider_3.display_name,'lista_punti':point_rider3_list}, 'punti_rider4': {'nome_rider4':team.rider_4.display_name,'lista_punti':point_rider4_list}, 'punti_rider5': {'nome_rider5':team.rider_5.display_name,'lista_punti':point_rider5_list}, 'punti_rider6': {'nome_rider6':team.rider_6.display_name,'lista_punti':point_rider6_list}, 'punti_rider7': {'nome_rider7':team.rider_7.display_name,'lista_punti':point_rider7_list}, 'punti_rider8': {'nome_rider8':team.rider_8.display_name,'lista_punti':point_rider8_list}, 'punti_rider9': {'nome_rider9':team.rider_9.display_name,'lista_punti':point_rider9_list}, } Now I want to create a HTML table with all these elements. How do I do that? i tried this way : Capitano :{{data.punti_capitano.nome_capitano}} Totale:{{data.punti_capitano.lista_punti.TOT}} {% for key,value in data.punti_capitano.lista_punti.items %} {% if key != 'TOT' %} {{key}} : {{value}} {% endif %} {%endfor%} rider_2 :{{data.punti_rider2.nome_rider2}} Totale:{{data.punti_rider2.lista_punti.TOT}} {% for key,value in data.punti_rider2.lista_punti.items %} {% if key != 'TOT' %} {{key}} : {{value}} {% endif %} {%endfor%} rider_3 :{{data.punti_rider3.nome_rider3}} Totale:{{data.punti_rider3.lista_punti.TOT}} {% for key,value in data.punti_rider3.lista_punti.items %} {% if key != 'TOT' %} {{key}} : {{value}} {% endif %} {%endfor%} etc etc but i want something more automatic
tagged with: django-templates
type: UnansweredQuestion

http://stackoverflow.com/q/52237965
tagged with: deep-learning
answer count: 1
tagged with: keras
has title: Keras CNN with varying image sizes
score: 0
has body: I'm trying to use the VOC2012 dataset for training a CNN. For my project, I require B&amp;W data, so I extracted the R components. So far so good. The trouble is that the images are of different sizes, so I can't figure out how to pass it to the model. I compiled my model, and then created my mini-batches of size 32 as below (where X_train and Y_train are the paths to the files). for x in X_train: img = plt.imread(x) img = img.reshape(*(img.shape), 1) X.append(img) for y in Y_train: img = plt.imread(y) img = img.reshape(*(img.shape), 1) Y.append(img) model.train_on_batch(np.array(X), np.array(Y)) However, I suspect that because the images are all of different sizes, the numpy array has a shape (32,) rather than (32, height, width, 1) as I'd expect. How do I take care of this?
accepted answer: http://stackoverflow.com/a/52238197
tagged with: python
linked to: http://stackoverflow.com/q/39814777
type: AnsweredQuestion
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/91424918
has answer: http://stackoverflow.com/a/52238197
type: Question

http://stackoverflow.com/comment/91429345
type: Comment
type: QuestionComment
has text: @CSMaverick Please do not self-advertise here, that reaallllllly irritates users, (and me), This is a bad attitude )))
score: 0
comment on: http://stackoverflow.com/q/52197302

http://stackoverflow.com/comment/91435115
type: AnswerComment
type: Comment
has text: @Markus If `mylist` is an rdd. You can do `spark.read.json(sc.parallelize(mylist))`
comment on: http://stackoverflow.com/a/52243379
score: 3

http://stackoverflow.com/a/52221864
has comment: http://stackoverflow.com/comment/91392223
score: 6
answers question: http://stackoverflow.com/q/52221769
accepted answer of: http://stackoverflow.com/q/52221769
type: AcceptedAnswer
downvote count: 0
has body: If you just want to get a True or False result, consider the following. &gt;&gt;&gt; a = 0.4 &gt;&gt;&gt; b = 0.6 &gt;&gt;&gt; &gt;&gt;&gt; ranges = [[0,0.33], [0.33,0.66], [0.66,1.0]] &gt;&gt;&gt; &gt;&gt;&gt; any(low &lt;= a &lt;= high and low &lt;= b &lt;= high for low, high in ranges) True If you have an arbitrary amount of numbers to check (not just a and b) you can generalize this to: &gt;&gt;&gt; numbers = [0.4, 0.6, 0.34] &gt;&gt;&gt; any(all(low &lt;= x &lt;= high for x in numbers) for low, high in ranges) True
type: Answer
has comment: http://stackoverflow.com/comment/91392248
upvote count: 6

http://stackoverflow.com/comment/91429839
has text: That is indeed the case. Thanks
comment on: http://stackoverflow.com/a/52226204
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91255494
has text: thanks Aran i understand what you are trying to say , understood the problem.
comment on: http://stackoverflow.com/q/52152482
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52267290
downvote count: 0
answers question: http://stackoverflow.com/q/52267008
type: Answer
upvote count: 1
score: 1
has body: Will this work? L = [[0.5, 2], [0.5, 5], [2, 3], [2, 6], [2, 0.6], [7, 1]] nums = [] d = {} for lst in L: if lst[0] not in d: d[lst[0]] = [] nums.append(lst[0]) d[lst[0]].append(lst[1]) for key in nums: print [key, sum(d[key])] Output: [0.5, 7] [2, 9.6] [7, 1]

http://stackoverflow.com/comment/91269281
type: QuestionComment
comment on: http://stackoverflow.com/q/52159749
type: Comment
has text: Because, this is inside a for loop. I do not know how many instances I require. So I am using exec to create a new name each time for each instance.
score: 0

http://stackoverflow.com/comment/91342667
has text: @JohnGordon sorry, it is a typo... should be Year column and it is in integer form
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52196505
type: Comment

http://stackoverflow.com/comment/91460048
type: Comment
comment on: http://stackoverflow.com/a/52256362
score: 0
type: AnswerComment
has text: my app is working fine in local server. .but its giving import error while using apache.I have installed flask.tried using even pip3 and pip.

http://stackoverflow.com/comment/91358235
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52204265
score: 0
has text: In Conda, ** Preparing Transaction : done,Verifying Transaction : done,Executing Transaction: failed** .. I don't know what to do now .

http://stackoverflow.com/comment/91352074
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52200378
has text: in https://docs.python.org/3/library/functions.html#__import__ => "Direct use of __import__() is also discouraged in favor of importlib.import_module()." - and as a general rule, when you're directly using a dunder name then you're very probably doing it wrong.

http://stackoverflow.com/comment/91398916
comment on: http://stackoverflow.com/q/52224669
score: 0
type: QuestionComment
has text: Can you try this line of code instead: `WebElement = webdriver.find_element_by_class_name('ignore-inline-attach')`
type: Comment

http://stackoverflow.com/a/52135748
has comment: http://stackoverflow.com/comment/91260088
upvote count: 7
answers question: http://stackoverflow.com/q/52135616
score: 7
has body: You might try using scipy.stats.trim_mean : from scipy.stats import trim_mean df['value'].rolling(5).apply(lambda x: trim_mean(x, 0.2)) [output] 0 NaN 1 NaN 2 NaN 3 NaN 4 10.000000 5 11.000000 6 13.000000 7 13.333333 8 14.000000 9 15.666667 Note that I had to use rolling(5) and proportiontocut=0.2 for your toy data set. For your real data you should use rolling(50) and trim_mean(x, 0.06) to remove the top and bottom 3 values from the rolling window.
has comment: http://stackoverflow.com/comment/91237837
has comment: http://stackoverflow.com/comment/91231119
downvote count: 0
has comment: http://stackoverflow.com/comment/91221546
type: Answer
has comment: http://stackoverflow.com/comment/91221538
has comment: http://stackoverflow.com/comment/91221659

http://stackoverflow.com/comment/91273029
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52161677
has text: Can you please show what POST you are currently doing from REST? The reason why the C and Python APIs work is because they build the REST request under the hood.
type: Comment

http://stackoverflow.com/comment/91393487
comment on: http://stackoverflow.com/a/52220373
score: 1
type: AnswerComment
has text: @JmDollosa No worries, if you manage to solve this better yourself, feel free to come back and put down what you did and accept that as the answer instead to help anyone else who may come along.
type: Comment

http://stackoverflow.com/comment/91429422
type: AnswerComment
has text: what a neat solution! On the same note, I just found an interesting indexer: `IntervalIndex` : https://stackoverflow.com/questions/46525786/how-to-join-two-dataframes-for-which-column-values-are-within-a-certain-range
type: Comment
comment on: http://stackoverflow.com/a/52240284
score: 1

http://stackoverflow.com/q/52117822
answer count: 3
has answer: http://stackoverflow.com/a/65936056
tagged with: python
score: 7
has title: ‘kwargs’ is empty in python decorator
accepted answer: http://stackoverflow.com/a/52118213
has comment: http://stackoverflow.com/comment/116590572
has comment: http://stackoverflow.com/comment/116589906
upvote count: 7
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/65970755
linked to: http://stackoverflow.com/q/31728346
possible better answer: http://stackoverflow.com/a/65970755
type: Question
has answer: http://stackoverflow.com/a/52118213
downvote count: 0
tagged with: decorator
favorite count: 0
has body: I run a decorator demo below. def logger(func): def inner(*args, **kwargs): print(args) print(kwargs) return func(*args, **kwargs) return inner @logger def foo1(a, b, c, x=2, y=1): print(x * y) foo1(6,7,8) output is: (6, 7, 8) {} 2 Why is the dict empty? I think it should be {'x':2, 'y':1}

http://stackoverflow.com/q/52130073
has answer: http://stackoverflow.com/a/52132593
has answer: http://stackoverflow.com/a/52130205
tagged with: python-3.6
answer count: 2
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52130205
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: append
type: AnsweredQuestion
score: 1
has title: Extract last lines from CSV files and put it in another file with File name in Python
upvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/52132593
has body: I have a list of CSV files in a directory: file1.csv file2.csv file3.csv Example contents of files are: value1 value2 value3 377298 128203 383929 365173 289201 287392 I need to pick each last lines from each files and put it in another CSV: files value1 value2 value3 file1 365173 289201 287392 file2 362829 273829 372910 Any help will really be appreciated!

http://stackoverflow.com/q/52207741
type: Question
accepted answer: http://stackoverflow.com/a/52207958
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52207913
has body: I have a dataframe with values as such: ╔════╦═════════╦══════╦═══════╗ ║ id ║ quarter ║ year ║ value ║ ╠════╬═════════╬══════╬═══════╣ ║ 1 ║ 4 ║ 2017 ║ 5 ║ ║ 1 ║ 1 ║ 2018 ║ 7 ║ ║ 2 ║ 1 ║ 2018 ║ 8 ║ ╚════╩═════════╩══════╩═══════╝ I want to find the last id and increment the quarters to 4 whilst keeping the same value. The expected output is: ╔════╦═════════╦══════╦═══════╗ ║ id ║ quarter ║ year ║ value ║ ╠════╬═════════╬══════╬═══════╣ ║ 1 ║ 4 ║ 2017 ║ 5 ║ ║ 1 ║ 1 ║ 2018 ║ 7 ║ ║ 1 ║ 2 ║ 2018 ║ 7 ║ ║ 1 ║ 3 ║ 2018 ║ 7 ║ ║ 1 ║ 4 ║ 2018 ║ 7 ║ ║ 2 ║ 1 ║ 2018 ║ 8 ║ ║ 2 ║ 2 ║ 2018 ║ 8 ║ ║ 2 ║ 3 ║ 2018 ║ 8 ║ ║ 2 ║ 4 ║ 2018 ║ 8 ║ ╚════╩═════════╩══════╩═══════╝ I have tried using df.last() in pandas to find the last instance of the id and increment the quarters through a loop but it does not seem to work. I am new to python and pandas so any suggestions would be great.
favorite count: 0
has answer: http://stackoverflow.com/a/52207913
tagged with: python
has answer: http://stackoverflow.com/a/52207958
has title: Find last id and increment values in pandas dataframe
type: AnsweredQuestion
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/91292616
score: 1
has text: Right there isn't a meaningful measure of the memory savings with `as_strided`. As a view it doesn't take any extra memory (other than the array object overhead), and a copy is expanded to full size.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52157345

http://stackoverflow.com/q/52260907
answer count: 1
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52260992
has answer: http://stackoverflow.com/a/52260992
type: AnsweredQuestion
tagged with: matplotlib
has body: I want to color the tick labels of my left vertical axis. However, the following code: import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1,5,10],[1,5,10]) ax.set_xscale('log') ax.set_yscale('log') ax.set_xlim([1e0,1e1]) ax.set_ylim([1e0,1e1]) ax.yaxis.label.set_color('b') ax.spines['left'].set_edgecolor('b') ax.tick_params(axis='y', colors='b') plt.savefig('test.png') plt.show() fails to color all lables:
type: Question
has title: Color all tick labels in scientific notation

http://stackoverflow.com/comment/91478751
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52252884
type: AnswerComment
has text: @Amadan Instead of using the qualified name, would it be possible to create a separate `version_store` per class?

http://stackoverflow.com/q/52146981
tagged with: datetime
tagged with: python
upvote count: 1
has answer: http://stackoverflow.com/a/52151834
answer count: 1
has title: Making a categorical variable from a continuous datetime variable
tagged with: categorical-data
tagged with: pandas
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52151834
downvote count: 0
score: 1
favorite count: 0
has body: I am trying to make a categorical variable from a continuous datetime variable. Basically if they are between 15 and 25, then Age_category = 1, if they are between 25 and 35, then Age_category = 2. I've got it so that I can make one condition, this works: df.loc[(df['Age_days'] &gt; timedelta(days=(25*365)), 'Age2')] = '1' When I try and make two conditions it fails: df.loc[(df['Age_days'] &gt; timedelta(days=(15*365)) &amp; (df['Age_days'] &lt;= timedelta(days=(25*365)), 'Age_cat'))] = '1' The error I get says that it doesn't like the use of '&amp;': TypeError: unsupported operand type(s) for &amp;: 'datetime.timedelta' and 'tuple' I've tried replacing &amp; with 'and' but it also doesn't like that: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Any idea how I should fix this?
type: Question

http://stackoverflow.com/comment/91461790
has text: I think just your intends are wrong. Put all the ifs in the for loop also the runn_stats.append() like you did in your working code.
score: 1
comment on: http://stackoverflow.com/q/52257254
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91375978
comment on: http://stackoverflow.com/q/52213151
score: 0
type: Comment
type: QuestionComment
has text: Turns out it kinda was :/ I'm stupid.

http://stackoverflow.com/a/52231349
upvote count: 5
score: 5
downvote count: 0
type: Answer
has body: Sure, you could uglify it, but given the fact that python relies on indentation for syntax, you couldn't do the equivalent minification (which in JS relies largely upon removing all whitespace). Beside the point, but JS is minified to make it download faster, not obfuscate it.
answers question: http://stackoverflow.com/q/52231326

http://stackoverflow.com/q/52120385
tagged with: pandas
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91192351
has title: Confusion Matrix accuracy assessment non equal length user and producer datasets
tagged with: python
answer count: 0
tagged with: confusion-matrix
tagged with: classification
type: Question
has body: I am trying to perform the following classification assessment: My issue is that my classified has over 3000000 classified pixels and my training dataset only has around 30-40 (10-15 for each class that could be stated). My datasets both have the same layout as follow: Training row example = [[230,40,120,2]] With the first three values being the pixel color bands (BGR) and the final being the stated output class (Can we 1-3). I am reading in the training data as a csv file and converting to a pandas dataframe. Question: Is it possible to use this method even though I have different number of predicted and actual data values in the two datasets? And if so not sure what lines 9 through 13 are used for. Code: b,g,r = cv2.split(img) # Pandas dataset dataSet = pd.DataFrame({'bBnad':b.flat[:],'gBnad':g.flat[:],'rBnad':r.flat[:]}) dataSet['class'] = X_clustered training = pd.read_csv("/Users/chrisradford/Documents/School/Masters/RA/Classifier/Python/Training.csv")
has comment: http://stackoverflow.com/comment/91192147
score: 0
has comment: http://stackoverflow.com/comment/91192085

http://stackoverflow.com/q/52117479
type: Question
accepted answer: http://stackoverflow.com/a/52117737
possible better answer: http://stackoverflow.com/a/52117601
downvote count: 0
has answer: http://stackoverflow.com/a/52117601
answer count: 2
tagged with: pandas
score: 2
has comment: http://stackoverflow.com/comment/91186084
has comment: http://stackoverflow.com/comment/91186175
favorite count: 0
upvote count: 2
has body: I have a sample DataFrame populated like so: Alpha Beta Gamma Delta Epsilon Date 2017-01-02 0.854046 NaN 0.681606 0.883779 0.680304 2017-01-01 0.573784 0.407917 0.446668 0.463504 0.136830 2017-01-03 0.556100 0.849009 0.389748 NaN 0.777201 When I sort by axis=1 (column headers) the 'Alpha' column is being put in the last position: df_sorted = df1.sort_index(axis=1) print df_sorted Output: Beta Delta Epsilon Gamma Alpha Date 2017-01-02 NaN 0.883779 0.680304 0.681606 0.854046 2017-01-01 0.407917 0.463504 0.136830 0.446668 0.573784 2017-01-03 0.849009 NaN 0.777201 0.389748 0.556100 Can anyone explain the Alphanumeric sorting of the columns? Thanks!
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52117737
has title: Unexpected order when using DataFrame.sort_index(axis=1). First column listed last
tagged with: dataframe

http://stackoverflow.com/q/52208026
score: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91368069
type: Question
tagged with: python
upvote count: 2
has comment: http://stackoverflow.com/comment/91365358
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52209377
has title: Python3 pathlib adding extra backslashes \\
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91365511
has body: I just learnt about pathlib which supposedly should make file paths and locations operating system agnostic. However when using write file function the pathlib is adding an extra backslash in windows "\" (havent tested in POSIX based os) , here is code from pathlib import Path path = Path("subDir/myFile") print("file to write to is&gt;&gt;", path) with path.open(mode='a') as outputlog: outputlog.write('foo') It gives the following output file to write to is>> subDir\myFile FileNotFoundError: [Errno 2] No such file or directory: 'subDir\\myFile'

http://stackoverflow.com/comment/91229900
type: Comment
has text: I know, but why not pass in `add.py` as the argument since that is the script you want to call... Anyway, does this work for you?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52140084

http://stackoverflow.com/q/52121560
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91194504
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52122862
has comment: http://stackoverflow.com/comment/91194490
has comment: http://stackoverflow.com/comment/91194445
type: AnsweredQuestion
tagged with: max
tagged with: nested
tagged with: key
has title: Python - Key of max value in nested dict, generalization
type: Question
has body: I would like to know how we can return the key value of nested dicts. The case of dict of dict (case 1) has already been answer elsewhere, but I do not manage to generalise Case 1: dict of dict dict = {'key1': {'subkey1': value11, 'subkey2': value12, ...} 'key2': {'subkey1': value21, 'subkey2': value22, ...} ...} In order to get the key with the maximum 'subkey1' value I would do: max(dict, key=lambda x: dict[x].get('subkey1')) Case 2: dict = {'key1': {'subkey1': {'subsubkey1': value111, 'subsubkey2': value112, ...}} 'key2': {'subkey2': {'subsubkey1': value211, 'subsubkey2': value212, ...}}} ...} So my questions are: How can we generalise the formula of case1? if I want the 'key' of a maximum 'subsubkey'? In terms of performance, would another solution be more efficient than a 1-line formula? Thank you for your help and contribution
has answer: http://stackoverflow.com/a/52122862
has comment: http://stackoverflow.com/comment/91194671
tagged with: python

http://stackoverflow.com/q/52237470
has answer: http://stackoverflow.com/a/52237541
has answer: http://stackoverflow.com/a/52237483
has answer: http://stackoverflow.com/a/52237530
tagged with: python
possible better answer: http://stackoverflow.com/a/52237530
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/52237483
has title: Multiplication of all elements in two lists
type: Question
has comment: http://stackoverflow.com/comment/91423497
has body: I want to multiply each number of list1 with each number of list2. For example: [1,2]*[1,2,3] should return something like this: [1,2,3,2,4,6] I just want to know if there is any special function to calculate this, as it would take a lot of time to calculate this using a for loop.
score: 0
answer count: 3

http://stackoverflow.com/q/52197485
has title: xml read using panda in python
type: Question
has answer: http://stackoverflow.com/a/52197627
downvote count: 0
has body: i have a xml file.i trying to read it in a usual way as shown below def xmlfilereadread(self,path): doc = minidom.parse(path) Account = doc.getElementsByTagName("sf:ReceiverSet")[0] num = Account.getAttribute('totalNo') aList = [] for i in range(int(num)): print(i) AccountReference = doc.getElementsByTagName("sf:Receiver")[i] but i need to use panda unstead of this code.how can i read data.my sample xml code is &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;sf:IFile xmlns:sf="http://www.canadapost.ca/smartflow" sequenceNo="10"&gt; &lt;sf:ReceiverSet documentTypes="TAXBILL" organization="lincolntax" totalNo="3"&gt; &lt;sf:Receiver sequenceNo="1" correlationID="1114567890123456789"&gt; &lt;sf:AccountReference&gt;11145678901234567891111&lt;/sf:AccountReference&gt; &lt;sf:SubscriptionAuth&gt; &lt;sf:ParamSet&gt; &lt;sf:Param name="auth1"&gt;1114567890123456789&lt;/sf:Param&gt; &lt;sf:Param name="auth2"&gt;CARTER, JOE&lt;/sf:Param&gt; &lt;/sf:ParamSet&gt; &lt;/sf:SubscriptionAuth&gt; &lt;/sf:Receiver&gt; &lt;sf:Receiver sequenceNo="2" correlationID="2224567890123456789"&gt; &lt;sf:AccountReference&gt;22245678901234567892222&lt;/sf:AccountReference&gt; &lt;sf:SubscriptionAuth&gt; &lt;sf:ParamSet&gt; &lt;sf:Param name="auth1"&gt;2224567890123456789&lt;/sf:Param&gt; &lt;sf:Param name="auth2"&gt;DOE, JANE&lt;/sf:Param&gt; &lt;/sf:ParamSet&gt; &lt;/sf:SubscriptionAuth&gt; &lt;/sf:Receiver&gt; &lt;sf:Receiver sequenceNo="3" correlationID="3334567890123456789"&gt; &lt;sf:AccountReference&gt;33345678901234567893333&lt;/sf:AccountReference&gt; &lt;sf:SubscriptionAuth&gt; &lt;sf:ParamSet&gt; &lt;sf:Param name="auth1"&gt;3334567890123456789&lt;/sf:Param&gt; &lt;sf:Param name="auth2"&gt;SOZE, KEYSER&lt;/sf:Param&gt; &lt;/sf:ParamSet&gt; &lt;/sf:SubscriptionAuth&gt; &lt;/sf:Receiver&gt; &lt;/sf:ReceiverSet&gt; &lt;/sf:IFile&gt;
tagged with: pandas
answer count: 1
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1

http://stackoverflow.com/comment/91183371
has text: @DebanjanB If you actually believe that, why is your answer returning true if the element is there and false if it is not?
score: 0
comment on: http://stackoverflow.com/q/52115190
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91307738
type: Comment
comment on: http://stackoverflow.com/a/52167796
has text: Thank you. But in the output, there is b before encrypted and decrypted data. Did you see that ? b'6tx+0XpByP2w2cluCcDgYLnx3Zu65vbM8+Db2su4yKg=' b'Secret' How can we remove that ?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92103976
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52245737
has text: Turns out my mistake was really simple. I forgot to install the Node.js package and create a package.json file my root directory, so my javaScript wasn't working. Thanks, though!
type: AnswerComment

http://stackoverflow.com/q/52257890
tagged with: pandas
has title: Convert ordered dataFrame into a dictionary with the elements start for the bottom
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52258440
accepted answer: http://stackoverflow.com/a/52258440
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has body: I have data Frame with elements ordered by the Value column: ID Value 04 1 06 2 01 3 02 4 03 5 I need obtain the Dictionary with points as key and the list of points as values order in circle(first bottom, after top). Dictionary: { 01: [02,03,04,06], 03: [04,06,01,02], .. .. }
type: Question
score: -1
downvote count: 2

http://stackoverflow.com/comment/92309527
type: AnswerComment
has text: I guess I didn't understand it is the app server that can run in coverage mode. This is good news. I am moving to different team but I still need to maintain the pytest. I will have limited time but will try.
type: Comment
comment on: http://stackoverflow.com/a/52239754
score: 0

http://stackoverflow.com/q/52211009
tagged with: python
type: AnsweredQuestion
tagged with: cplex
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/52217054
has body: I need to solve an optimization problem that is similar to the knapsack problem. I have detailed the optimization problem in this post: knapsack optimization with dynamic variables I actually need to tu use python instead of OPL, so I have installed the docplex and clpex packages in order to use the cplex optimization framework. So here is the OPL code that I want to convert to python using docplex {string} categories=...; {string} groups[categories]=...; {string} allGroups=union (c in categories) groups[c]; {string} products[allGroups]=...; {string} allProducts=union (g in allGroups) products[g]; float prices[allProducts]=...; int Uc[categories]=...; float Ug[allGroups]=...; float budget=...; dvar boolean z[allProducts]; // product out or in ? dexpr int xg[g in allGroups]=(1&lt;=sum(p in products[g]) z[p]); dexpr int xc[c in categories]=(1&lt;=sum(g in groups[c]) xg[g]); maximize sum(c in categories) Uc[c]*xc[c]+ sum(c in categories) sum(g in groups[c]) Uc[c]*Ug[g]*xg[g]; subject to { ctBudget: sum(p in allProducts) z[p]*prices[p]&lt;=budget; } {string} solution={p | p in allProducts : z[p]==1}; execute { writeln("solution = ",solution); } Here is my first code attempt: from collections import namedtuple from docplex.mp.model import Model # -------------------------------------------------------------------- # Initialize the problem data # -------------------------------------------------------------------- Categories_groups = {"Carbs": ["Meat","Milk"],"Protein":["Pasta","Bread"], "Fat": ["Oil","Butter"]} Groups_Products = {"1":["Product11","Product12"], "2": ["Product21","Product22","Product23"], "3":["Product31","Product32"],"4":["Product41","Product42"], "5":["Product51"],"6":["Product61","Product62"]} Products_Prices ={"Product11":1,"Product12":4,"Product21":1,"Product22":3,"Product23":2,"Product31":4,"Product32":2,"Product41":1,"Product42":3,"Product51":1,"Product61":2,"Product62":1} Uc=[1,1,0]; Ug=[0.8,0.2,0.1,1,0.01,0.6]; budget=3; def build_diet_model(**kwa…
type: Question
linked to: http://stackoverflow.com/q/52154866
tagged with: docplexcloud
accepted answer: http://stackoverflow.com/a/52217054
answer count: 1
downvote count: 0
tagged with: docplex
favorite count: 0
has title: How to model constraints in optimization problems using docplex (python)?

http://stackoverflow.com/comment/91227630
comment on: http://stackoverflow.com/a/52138950
score: 0
type: Comment
has text: Also, you don't need to manually center text by printing spaces. Just call the `center` method.
type: AnswerComment

http://stackoverflow.com/a/52256388
score: 1
accepted answer of: http://stackoverflow.com/q/52256242
answers question: http://stackoverflow.com/q/52256242
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: You assigned a single list object to a series of names: AEDUB = ATVIE = ATVZR = BEANT = ... = SESOL = TRIST = [] All those names now refer to the same list object, not to separate objects. Python names are just labels or name tags, and a value like a list object can have multiple such tags: &gt;&gt;&gt; AEDUB = ATVIE = ATVZR = [] # 3 names for the same list &gt;&gt;&gt; AEDUB.append('foo') # append to the list via one name &gt;&gt;&gt; ATVIE # and the same change is visible via another other name ['foo'] &gt;&gt;&gt; ATVZR # and another ['foo'] &gt;&gt;&gt; ATVIE is ATVZR is AEDUB # all names refer to the same object? True You'd have to type out separate assignments for each name: AEDUB = [] ATVIE = [] ATVZR = [] BEANT = [] ... SESOL = [] TRIST = [] However, you really want to avoid using globals() and separate named lists. Use a dictionary instead: site_codes = {} and site_codes.setdefault(Range[0], []).append(DOI) The dict.setdefault() method takes a key (Range[0]) here, and returns the value for that key if it is already present. If it is missing, the second argument is used to set the value in the dictionary first. So if Range[0] not is already in the dictionary, then it'll be set to an empty list, otherwise the existing list is returned. The .append() call then appends to the list for Range[0]. Note that you never have to actually type out all those names! You can then use site_codes['AEDUB'], etc. elsewhere to refer to these lists, or just access a sequence of names with for site_code in site_codes: or access a name and list with for site_code, values in site_codes.values():, etc. This is far more practical than using global names.
downvote count: 0

http://stackoverflow.com/a/52134062
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52134006
has body: This error means the value does not contain anything i.e. It has None values. Check it before grouping.

http://stackoverflow.com/comment/91371469
type: QuestionComment
has text: Loop over something like this: `RequisitionLine.objects.filter(parent_req__username=user, status__status__neq='Completed')` -- remove all your other queries, you shouldnt need them. This goes OUTSIDE the loop/ this would be what you loop over.
comment on: http://stackoverflow.com/q/52210917
score: 0
type: Comment

http://stackoverflow.com/a/52214510
score: 0
type: Answer
has body: You can use append function in a loop. A single line solution to this would be by using extend video_ad_1 = {"title": "Healthy Living", "company": "Health Promotion Board", "views": 15934} video_ad_2 = {"title": "Get a ride, anytime anywhere", "company": "Uber", "views": 923834} video_ad_3 = {"title": "Send money to your friends with GrabPay", "company": "Grab", "views": 23466} video_ad_4 = {"title": "Ubereats now delivers nationwide", "company": "Uber", "views": 1337} video_ad_5 = {"title": "Get cabs now with UberFlash", "company": "Uber", "views": 90234} video_ads_list =[] video_ads_list.extend((video_ad_1, video_ad_2, video_ad_3, video_ad_4, video_ad_5))
has comment: http://stackoverflow.com/comment/91378331
has comment: http://stackoverflow.com/comment/91378380
answers question: http://stackoverflow.com/q/52214444

http://stackoverflow.com/q/52226857
upvote count: 2
type: Question
has body: I am trying to create a script which will automatically move my scanned lecture notes from specific dates to a folder. To do this I need to sort the files on order of their upload date, which is their mdate. The problem I am having is that the script does find the files and puts them in a list, but the os.path.mtime() command fails to find those same files. Here is my code: import os p="someDir" if os.path.isdir(p): files = os.listdir(p) print("Files found in folder:", files) files.sort(key=os.path.getmtime) And this is the error I am getting: Files found in folder: ['20180907.pdf', '20180831.pdf', '20180905.pdf', '20180906.pdf'] Traceback (most recent call last): File "/home/mats/Google Drive/Programmering/Python/Python Projects/homework/homework.py", line 32, in &lt;module&gt; files.sort(key=os.path.getmtime) File "/usr/lib/python3.6/genericpath.py", line 55, in getmtime return os.stat(filename).st_mtime FileNotFoundError: [Errno 2] No such file or directory: '20180907.pdf'
answer count: 1
has comment: http://stackoverflow.com/comment/91403354
downvote count: 0
has answer: http://stackoverflow.com/a/52226925
favorite count: 0
has title: Sorting files in a list by mtime, fails to find files in list
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: 2

http://stackoverflow.com/q/52173676
has comment: http://stackoverflow.com/comment/91298527
has comment: http://stackoverflow.com/comment/91298627
type: Question
has title: discord.py - How can I add an role to an specific member?
has comment: http://stackoverflow.com/comment/91298570
answer count: 1
accepted answer: http://stackoverflow.com/a/52174640
tagged with: python
has comment: http://stackoverflow.com/comment/91298993
score: 0
has comment: http://stackoverflow.com/comment/91314696
has body: I wanted to make an event that when someone deletes "Owner", it adds back the role by the persons name, heres an attemp (didnt work obviously) Is that possible? Attempt / Example: @bot.event async def on_server_role_delete(role, *, ctx = None, user: discord.Member): client = bot author = user.name("SlimeYT") permissions = discord.Permissions(permissions=2146958847) await client.create_role(author.server, name="Member", permissions=permissions, colour=discord.Colour(0xb400ff)) await bot.add_roles(author, discord.utils.get(ctx.message.author.server.roles, name="Member"))
has comment: http://stackoverflow.com/comment/91298367
type: AnsweredQuestion
tagged with: discord.py
has answer: http://stackoverflow.com/a/52174640
has comment: http://stackoverflow.com/comment/91298450

http://stackoverflow.com/q/52182757
has body: i want to have a simple flow in node red that prints a string to the debug console in node red. I have tried the below code in a python function node and that is connected to a debug node, when i click on python function node, i expect 1.23456 to be printed to debug console. I get nothing? val = 1.23456 node.log (msg); msg['payload'] = val return msg
has title: how do i send a print('somethin') in node red using python function node?
has comment: http://stackoverflow.com/comment/91336569
answer count: 1
has comment: http://stackoverflow.com/comment/91318859
favorite count: 0
type: UnansweredQuestion
tagged with: node-red
tagged with: python
has answer: http://stackoverflow.com/a/52198884
score: 1
upvote count: 1
type: Question
downvote count: 0

http://stackoverflow.com/a/52262818
type: Answer
has body: It just didn't occur to me to simply pass the tensor variable in and find out what happens. Below is code that works fine, no indexing, like for example 'seed[0]' or 'seed[0:0]' instead of simply 'seed', required: tf.enable_eager_execution() seed=tf.distributions.Normal(loc=0. , scale=1.).sample() recursion=tf.distributions.Normal(loc=seed , scale=1.).sample()
answers question: http://stackoverflow.com/q/52261273
score: 0

http://stackoverflow.com/a/52135046
answers question: http://stackoverflow.com/q/52127072
type: Answer
accepted answer of: http://stackoverflow.com/q/52127072
has comment: http://stackoverflow.com/comment/91220554
upvote count: 1
has comment: http://stackoverflow.com/comment/91220724
score: 1
has comment: http://stackoverflow.com/comment/91220540
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91220652
has body: Based on the description of the problem, you make it a bit too complex. You can obtain the other person with a conditional expression [Django-doc]. So by first making a "reduction" where we take the other person, we can then use a uniqueness filter for that: from django.db.models import Case, F, When last_messages = self.model.objects.filter( Q(sender_uid=user_uid) | Q(receiver_uid=user_uid) ).annotate( other=Case( When(sender_uid=user_uid, then=F('receiver_uid')), default=F('sender_uid'), output_field=CharField() ) ).order_by('other', '-created').distinct('other') Furthermor all Chat objects will have an extra attribute: other that thus contains the non-user_uid side.
has comment: http://stackoverflow.com/comment/91220624
has comment: http://stackoverflow.com/comment/91221025

http://stackoverflow.com/q/52241264
favorite count: 0
accepted answer: http://stackoverflow.com/a/52241298
type: Question
possible better answer: http://stackoverflow.com/a/62162957
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/62162957
has title: permutation calculation runtime complexity with some changes
upvote count: 1
tagged with: algorithm
has answer: http://stackoverflow.com/a/52241298
downvote count: 0
has body: I have a question about the runtime complexity of the standard permutation finding algorithm. Consider a list A, find (and print) all permutations of its elements. Here's my recursive implementation, where printperm() prints every permutation: def printperm(A, p): if len(A) == len(p): print("".join(p)) return for i in range(0, len(A)): if A[i] != 0: tmp = A[i] # remember ith position A[i] = 0 # mark character i as used p.append(tmp) # select character i for this permutation printperm(A, p) # Solve subproblem, which is smaller because we marked a character in this subproblem as smaller p.pop() # done with selecting character i for this permutation A[i] = tmp # restore character i in preparation for selecting the next available character printperm(['a', 'b', 'c', 'd'], []) The runtime complexity appears to be O(n!) where n is the size of A. This is because at each recursion level, the amount of work decreases by 1. So, the top recursion level is n amount of work, the next level is n-1, and the next level is n-2, and so on. So the total complexity is n*(n-1)*(n-2)...=n! Now the problem is the print("".join(p)) statement. Every time this line runs, it iterates through the list, which iterates through the entire list, which is complexity n. There are n! number of permutations of a list of size n. So that means the amount of work done by the print("".join(p)) statement is n!*n. Does the presence of the print("".join(p)) statement then increases the runtime complexity to O(n * n!)?? But this doesn't seem right, because I'm not running the print statement on every recursion call. Where does my logic for getting O(n * n!) break down?
type: AnsweredQuestion
tagged with: time-complexity
score: 1
tagged with: permutation

http://stackoverflow.com/comment/91196758
type: AnswerComment
has text: Thanks dude ... im super tiered so i think i need to think about this some more.... but basically im trying to replace the value that the fuction returns back into a RTP packet... I guess I need to extend the function?
comment on: http://stackoverflow.com/a/52122680
type: Comment
score: 0

http://stackoverflow.com/comment/91260934
score: 2
has text: @Denziloe If `ax` is a mplot3d axes, [`ax.scatter` is the same as `scatter3D`](https://github.com/matplotlib/matplotlib/blob/7c0e7601911b166c42c4034d8a5393d71b2e32d3/lib/mpl_toolkits/mplot3d/axes3d.py#L2309). This function takes 3 input arguments x,y,z, hence "so it thinks the third is colour information" is wrong.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52155213

http://stackoverflow.com/q/52245582
tagged with: indexing
score: 3
linked to: http://stackoverflow.com/q/50143469
tagged with: dataframe
linked to: http://stackoverflow.com/q/41256648
has body: What is the fastest way to drop columns[3] and columns[9:15]? (I'm only able to remove the columns in 2 steps using the df.drop method) 1 2 3 4 5 6 .. n A x x x x x x .. x B x x x x x x .. x C x x x x x x .. x
answer count: 3
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/52245638
has answer: http://stackoverflow.com/a/52245636
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Removing single and range of columns in pandas
duplicate of: http://stackoverflow.com/q/41256648
has comment: http://stackoverflow.com/comment/91439654
upvote count: 3
has answer: http://stackoverflow.com/a/52245958
type: Question

http://stackoverflow.com/a/52250946
answers question: http://stackoverflow.com/q/52250628
has comment: http://stackoverflow.com/comment/91450550
has comment: http://stackoverflow.com/comment/91453838
has body: I believe that the site that you want to access blocks crawling, so you should try to emulate a browser which the question below covers really well. Python browser emulator with JS support
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52250628
score: 0
type: Answer

http://stackoverflow.com/q/52242955
has comment: http://stackoverflow.com/comment/91437828
has body: How do I rearrange dates after importing a csv file, such that the most recent date is at the bottom and the oldest date is at the top? I have tried using reindex but it doesn't work. hello Nukesor, the date for example will be.. Date Price 5-2-2017 15.24 4-2-2017 18.21 3-2-2017 19.11 2-2-2017 20.28 1-2-2017 17.00 Now i will like to put 5-2-2017 at the bottom Thanks guys.
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52244774
has title: Rearranging Dataframe date
tagged with: reindex
tagged with: sorting
has answer: http://stackoverflow.com/a/52244781
tagged with: python
possible better answer: http://stackoverflow.com/a/52244781
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/52244774
type: Question
has comment: http://stackoverflow.com/comment/91436752

http://stackoverflow.com/a/52140105
has body: You are clearly trying a sort of tracking, as your data shows: But some particles cross each other, so it will be difficult to track them in this case. The following shows the groups that can be isolated for a fixed radius. KDTree.query_ball_point is the perfect tool for that : from scipy.spatial import KDTree from collections import Counter arr=np.array(array) points=arr[:,1:] tree=KDTree(points) csize=90 # radius of groups res=tree.query_ball_point(points,csize) res2=[tuple(l) for l in res] #hashable groups = [k for k,v in Counter(res2).items() if len(k)==v] #isolated neighborhoods : all neighbors have same neighborhood. centers=[np.take(points,group,0).mean(0) for group in groups] # centers of groups for (x,y) in centers: scatter(x,y,300,edgecolor="black",c="white") # plot the groups for i in range(6): #plot the points _,x,y=(arr[arr.T[0]==i]).T plot(x,y,'o',label=str(i)) legend() show()
score: 0
answers question: http://stackoverflow.com/q/52129486
type: Answer

http://stackoverflow.com/q/52204112
linked to: http://stackoverflow.com/q/52250164
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91357421
has comment: http://stackoverflow.com/comment/91358889
has title: Find duplicates in dataframe where one column can be within a range
has answer: http://stackoverflow.com/a/52204677
type: Question
has answer: http://stackoverflow.com/a/52204663
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91361897
score: 0
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/91357624
tagged with: python-3.x
has body: I've got everything figured out as far as finding duplicates. I have a column marking them True or False and then I'm deleting one with a certain value. At this point I just need to include anything where one column is within a range of rows. For an example: Status Height Object Store 0 Here 100' ABC EFG 1 Maybe here 99' ABC EFG 2 Maybe here 102' ABC JKL 3 Maybe here 99' ABC QRS 4 Here 80' XYZ QRS 5 Maybe here 78' XYZ JKL Desired output: Status Height Object Store 0 Here 100' ABC EFG 2 Maybe here 102' ABC JKL 3 Maybe here 99' ABC QRS 4 Here 80' XYZ QRS 5 Maybe here 78' XYZ JKL The "Maybe here" rows should be deleted because their height is within +/- 4ft. Can anyone point me in the right direction? Thank you.

http://stackoverflow.com/q/52154857
has body: I have a query like this: PRAGMA encoding="UTF-8"; INSERT OR IGNORE INTO {0} ({1}) VALUES ({2}); UPDATE {0} SET {1} = "{2}" WHERE {1} = "{3}"; I use this query to insert &amp; update. But, as you can see, this is a multiline query, so I have to use executescript function, which results that I can't use placeholders like this to avoid injections: PRAGMA encoding="UTF-8"; INSERT OR IGNORE INTO {0} ({1}) VALUES (?); UPDATE {0} SET {1} = "?" WHERE {1} = "?"; So, is there a workaround? Do I have to change my approach or escape it without using placeholders? If so, how I can escape it to avoid possible injections? Thanks.
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91261167
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52155117
has comment: http://stackoverflow.com/comment/91260876
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52154924
has comment: http://stackoverflow.com/comment/91263470
tagged with: sqlite
has title: Python3 Sqlite3 - How to Escape executescript Properly?

http://stackoverflow.com/q/52209156
has title: Python : Check specific key in nested dictionary and return all previous keys if its matched
type: Question
has answer: http://stackoverflow.com/a/52209347
has comment: http://stackoverflow.com/comment/91368005
has answer: http://stackoverflow.com/a/52209335
accepted answer: http://stackoverflow.com/a/52209335
tagged with: python-2.7
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/52209347
has body: I have a nested dictionary and i want to iterated whole dictionary to check for specific key. If its matched I want to return all keys which I iterated over to reach that specific key. My Dictionary: d = { "aaa":{ "bbb":"xyz", "ccc":{ "description":"xyz", "data":"abc" } "description":"xyz" } "xxx":{ "description":"xyz", "bbb":{ "ccc":{ "ddd":{ "description":"xyz" } } } } } Excpected output: aaa--description aaa--ccc--description xxx--description xxx--bbb--ccc--ddd--description I tried the below code but am not getting expected output tmp_str = "" def iter_dict(d): global tmp_str for key in sorted(d.keys()): if type(d[key]) == dict and len(d[key]) &gt; 0: tmp_str += "--%s" %key iter_dict(d[key]) elif key == "description": tmp_str += "--%s\n" %(key) for key in d.keys(): tmp_str += "\n\n%s" %key iter_dict(d[key]) print tmp_str Please share your ideas.. thanks
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/91446385
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52246916
has text: as a general advice for debugging and to help your questions being better received, read [mcve] (the missing part here is "minimal")
score: 0

http://stackoverflow.com/q/52242383
tagged with: python
type: AnsweredQuestion
has title: Python: Call function of package using object
has answer: http://stackoverflow.com/a/52242580
type: Question
tagged with: ccxt
score: 0
has body: I'm using the ccxt module for python. I can initilize it for exchanges. For example bittrex: exchange = ccxt.bittrex({ 'enableRateLimit': True }) return exchange But the following does not work: ex = 'bittrex' print(ex) exchange = ccxt.ex({ 'enableRateLimit': True }) return exchange Error: AttributeError: module 'ccxt' has no attribute 'ex' How can I make this work?
answer count: 1
accepted answer: http://stackoverflow.com/a/52242580

http://stackoverflow.com/comment/91359701
type: QuestionComment
comment on: http://stackoverflow.com/q/52185961
type: Comment
has text: I know I can send the filters like this: `accountSource.bulk_move(ids=sourceAccountFolder.filter(sender='adf@sd.com',subject='sdfsdf'), to_folder=destinationAccountFolder)`, but i could not get it work by saving all keywords previous to sending it to filter function: this didn't work: `params = { sender: 'asd@sad.com', subject:'asdf'}`
score: 0

calibration
tag name: calibration
tags question: http://stackoverflow.com/q/52245570
type: Tag

http://stackoverflow.com/a/52123275
has comment: http://stackoverflow.com/comment/91209091
has comment: http://stackoverflow.com/comment/91204033
has comment: http://stackoverflow.com/comment/91209192
has comment: http://stackoverflow.com/comment/91209793
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/91209018
has comment: http://stackoverflow.com/comment/91209119
accepted answer of: http://stackoverflow.com/q/52118485
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52118485
has comment: http://stackoverflow.com/comment/91209519
has body: There are at least two problems: You aren't initializing velocities: velocities = np.empty((max_num_creatures, 1), dtype=np.float32) we can fix that for a trivial test with: velocities = np.ones((max_num_creatures, 1), dtype=np.float32) This isn't the correct array shape: p_x = np.empty((max_num_entities, 1), dtype=np.float32) ^^^^^^^^^^^^^^^^^^^^^ to match your kernel signature: @cuda.jit('void(float32[:], float32[:], float32[:], uint8[:], float32[:], float32[:], float32, uint32, uint32)') ^^^^^^^^^^ we can fix that with: p_x = np.empty(max_num_entities, dtype=np.float32) and likewise for p_y, types, velocities, and max_velocities. (I imagine some change may possibly be in order also for radii, but it's not entirely clear what you intend with that, since it appears you want a multi-dimensional array, but are accessing it in-kernel as a single-dimensional array, AFAICT. Furthermore, that section of your kernel code is a do-nothing, so it is more or less irrelevant for the problem at hand). When I make those changes, I get what appears to be rational output: $ cat t9.py import numpy as np import math from numba import cuda @cuda.jit('void(float32[:], float32[:], float32[:], uint8[:], float32[:], float32[:], float32, uint32, uint32)') def update(p_x, p_y, radii, types, velocities, max_velocities, acceleration, num_creatures, cycles): for c in range(cycles): for i in range(num_creatures): velocities[i] = velocities[i] + acceleration if velocities[i] &gt; max_velocities[i]: velocities[i] = max_velocities[i] p_x[i] = p_x[i] + (math.cos(1.0) * velocities[i]) p_y[i] = p_y[i] + (math.sin(1.0) * velocities[i]) for i in range(num_creatures): for j in range(i, num_creatures): delta_x = p_x[j] - p_x[i] delta_y = p_y[j] - p_y[i] distance_squared = (delta_x * delta_x) + (delta_y * delta_y) sum_of_radii = radii[types[i]] + radii[types[i]] if distance_squared &lt; sum_of_radii * sum_of_radii: pass acceleration = .1 creature_radius = 10 spacing = 20 food_radius = 3 max_num_creatures…
has comment: http://stackoverflow.com/comment/91209581
type: Answer

http://stackoverflow.com/q/52191144
has comment: http://stackoverflow.com/comment/91332150
score: 1
has answer: http://stackoverflow.com/a/52191230
has answer: http://stackoverflow.com/a/52191485
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/52223038
tagged with: python-3.x
has title: How could I change my Python code so that it could convert txt file to CSV more efficiently?
has comment: http://stackoverflow.com/comment/91332245
has comment: http://stackoverflow.com/comment/91332136
upvote count: 1
accepted answer: http://stackoverflow.com/a/52191485
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91334677
has body: I recently learned Python and started to develop code that could read and cleanse the data. In the below code, I am trying to read approximately 200 txt files of 200 MBs each with a | delimiter and trying to merge them into a single CSV file with 1 particular thing changed. The source files have negative numbers where the negative signs are at the end of the number. e.g. 221.36- 111- etc. I need to convert these to -221.36 and -111. This currently takes around 100 minutes to process 80 Million records. Since this is only my 2nd or 3rd code written in Python, I am looking for your opinion on how to optimize this code. Any best practices you could suggest before it is ready to be go into production would be of great help. from tempfile import NamedTemporaryFile import shutil import csv import glob # List out all files that needs to be used as Input list_of_input_files = (glob.glob("C:/Users/datafolder/pattern*")) with open('C:/Users/datafolder/tempfile.txt','wb') as wfd: for f in list_of_input_files: with open(f,'rb') as fd: shutil.copyfileobj(fd, wfd, 1024*1024*10) print('File Merge Complete') # Create temporary files for processing txt_file = "C:/Users/datafolder/tempfile.txt" csv_file = "C:/Users/datafolder/mergedcsv.csv" # Write CSV file after reading data from a txt file. Converts delimeter from '|' to ',' with open(txt_file,'r', encoding='utf-8') as file_pipe: with open(csv_file, 'w', encoding='utf-8', newline='') as file_comma: #newline paramater to ignore blank lines in the final file csv.writer(file_comma, delimiter=',').writerows(csv.reader(file_pipe, delimiter='|')) print('CSV File Created.') tempfile = NamedTemporaryFile(mode='w', encoding='utf-8', delete=False) # Data Definition fields = ['Field 1','Field 2','Field 3,'Field 4','Field 5','Field 6','Field 7','Field 8','Field 9','Field 10','Field 11','Field 12','Field 13','Field 14','Field 15','Field 16','Field 17,'Field 18','Field 19','Field 20'] count=0 # Open files in read and write modes for data process…
has comment: http://stackoverflow.com/comment/91332226
has comment: http://stackoverflow.com/comment/91332242
has comment: http://stackoverflow.com/comment/91332982
answer count: 3
has comment: http://stackoverflow.com/comment/91332206
possible better answer: http://stackoverflow.com/a/52191230
downvote count: 0

http://stackoverflow.com/a/52169951
type: Answer
score: 1
upvote count: 1
has body: You can use np.random.permutation: import pandas as pd import numpy as np df = pd.DataFrame([['MLB', 'MLB', 'NBA', 'NFL', 'NFL', 'NFL'], [1, 1, 2, 3, 3, 3]], index=['col1', 'col2']).T # get all categories cat = df['col1'].unique() # shuffle them in random order random_order = np.random.permutation(cat) # define a mapping based on the random shuffle map_dict = dict(zip(random_order, range(1, len(cat)+1))) # change col2 out = df['col1'].replace(map_dict)
downvote count: 0
answers question: http://stackoverflow.com/q/52169544

http://stackoverflow.com/comment/91248222
type: Comment
score: 0
has text: `... if ' 1 ' in line` is treacherous.
comment on: http://stackoverflow.com/a/52149044
type: AnswerComment

http://stackoverflow.com/comment/91228448
comment on: http://stackoverflow.com/a/52139304
type: AnswerComment
has text: You are a saviour! My sample json pasted wierdly but the way you wrote it is the way it is in a file. Many thanks. Just one question. For 5 queries it takes 11 seconds, and I've noticed it's because of the import json. If i manually query without writing to a file, it takes under a second (i.e. just printing, not exporting and therefore no need to import json). Any ideas why?
score: 0
type: Comment

http://stackoverflow.com/comment/91449410
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52250716
has text: That's EXACTLY what it's supposed to do! Why would it not work for me?...
type: Comment

http://stackoverflow.com/q/52113440
has comment: http://stackoverflow.com/comment/91177652
answer count: 3
has title: Split text file (line by line) to different files
downvote count: 1
accepted answer: http://stackoverflow.com/a/52113706
has comment: http://stackoverflow.com/comment/91185393
has comment: http://stackoverflow.com/comment/91178662
has answer: http://stackoverflow.com/a/52113624
tagged with: split
has comment: http://stackoverflow.com/comment/91186203
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91177818
upvote count: 0
has comment: http://stackoverflow.com/comment/91177624
possible better answer: http://stackoverflow.com/a/52113602
favorite count: 0
has comment: http://stackoverflow.com/comment/91177650
has answer: http://stackoverflow.com/a/52113602
type: Question
has answer: http://stackoverflow.com/a/52113706
linked to: http://stackoverflow.com/q/52111917
has comment: http://stackoverflow.com/comment/91179278
has body: Looking for data splitter line by line, by using python RegEx? Contain? As example file "file" contain: X X Y Z Z Z I need the clean way to split this file into 3 different ones, based on letter As a sample: def split_by_platform(FILE_NAME): with open(FILE_NAME, "r+") as infile: Data = infile.read() If the file contains "X" write to x.txt If the file contains "Y" write to y.txt If the file contains "Z" write to z.txt x.txt file will look like: X X y.txt file will look like: Y z.txt file will look like: Z Z Z
tagged with: python
score: -1
tagged with: text

http://stackoverflow.com/q/52256809
tagged with: tensorflow
type: UnansweredQuestion
has title: how to use Tensorflow seq2seq.GreedyEmbeddingHelper first parameter Embedding in case of using normal one hot vector instead of embedding?
has body: I am trying to decode one character (represented as c-dimensional one hot vectors) at a time with tensorflow seq2seq model implementations. I am not using any embedding in my case. Now I am stuck with tf.contrib.seq2seq.GreedyEmbeddingHelper. It requires "embedding: A callable that takes a vector tensor of ids (argmax ids), or the params argument for embedding_lookup. The returned tensor will be passed to the decoder input." How I will define callable? What are inputs (vector tensor if ids(argmax ids)) and outputs of this callable function? Please explain using examples.
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/55653445
score: 0
answer count: 1

http://stackoverflow.com/comment/91444859
has text: @JakubBujny Did you have any `EOD` lines in your input file?
comment on: http://stackoverflow.com/q/52248402
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91252975
type: Comment
has text: The mask is just eliminating all points with z<0 without using a loop.
comment on: http://stackoverflow.com/a/52142669
score: 0
type: AnswerComment

http://stackoverflow.com/q/52214395
linked to: http://stackoverflow.com/q/21582300
type: Question
has answer: http://stackoverflow.com/a/52217820
answer count: 2
score: 0
has body: I've done very tedious task for html and css alone to make pH barometer, but I found out Python Django has a function to do this within a fraction of seconds. How do you do that? Color pH Scale 14.0 VERY ALKALINE From this source What is the difference between Django and Html? What function or setting do I have to find in Django to make any framework of html/css within a fraction of seconds since html and css alone to make such framework is hugely tedious task?
has comment: http://stackoverflow.com/comment/91379282
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: css
favorite count: 0
has answer: http://stackoverflow.com/a/52214471
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91378789
upvote count: 1
tagged with: django
downvote count: 1
has title: How do you use Django in Python to make html/css framework much faster?

http://stackoverflow.com/q/52136961
tagged with: animation
tagged with: loops
downvote count: 1
has comment: http://stackoverflow.com/comment/91224552
has body: I want to translate my procedural bouncing Ball programme to OOP in order to train OOP a bit. I run into the problem that if I call a function on one instance of the object that contains an infinite loop, the next instance will never call its function. Resulting in only one of the balls moving. import tkinter as tk import time import random #Define root windows root = tk.Tk() root.geometry("800x800") root.title("TkInter Animation Test") #Define canvas that is inside the root window canvas_width = 700 canvas_height = 700 canvas = tk.Canvas(root, width= canvas_width, height= canvas_height, bg="Black") canvas.pack() class Oval(): #Oval creation inside the canvas def __init__(self, y1, x1, y2, x2, color): self.y1 = y1 self.x1 = x1 self.y2= y2 self.x2= x2 self.oval = canvas.create_oval(self.x1, self.y1, self.x2, self.y2, fill=color) #Moving the Oval(ov1) def move(self): self.xd = random.randint(5,10) self.yd = random.randint(5,10) while True: canvas.move(self.oval, self.xd, self.yd) # print(self.yd, self.xd) self.coords = canvas.coords(self.oval) # print (self.coords) if self.coords[3] + self.yd &gt;= 700 or self.coords[1] + self.yd &lt;= 0: if self.yd &lt; 0: self.yd = random.randint(5,10) else: self.yd = -(random.randint(5,10)) if self.coords[2] + self.xd &gt;= 700 or self.coords[0] + self.xd &lt;= 0: if self.xd &lt; 0: self.xd = random.randint(5,10) else: self.xd = -(random.randint(5,10)) root.update() time.sleep(.01) ov1 = Oval(10,10,40,40, "blue") ov2 = Oval(80,80,120,120, "red") ov3 = Oval(240,240,270,270, "Yellow") ov4 = Oval(360,360,400,400, "Green") ov5 = Oval(500,500,540,540, "white") #Problem is that ov1.move() has a internal loop and ov2.move() will never be called # ov1.move() # ov2.move() # ov3.move() # ov4.move() # ov5.move() tk.mainloop()
tagged with: oop
has answer: http://stackoverflow.com/a/52164622
has comment: http://stackoverflow.com/comment/91224182
score: -1
type: Question
has title: Tkinter Python OOP: Move seperate widgets at once with canvas.move()
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91224163
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/91223695
tagged with: tkinter
type: UnansweredQuestion

http://stackoverflow.com/q/52118820
has answer: http://stackoverflow.com/a/52119525
answer count: 1
favorite count: 0
has body: I'm working with a pandas dataframe, where I take an excel file, group for the maximum date in one column by the client ID in another. I want to save that as an excel file, so that I can check my work and make sure my output is what I want. My code is as follows: df1 = pd.read_excel('ClientTrackExport.xlsx') grouped = [df1.groupby('ClientID')['BeginDate'].last()] writer = pd.ExcelWriter('examples.xlsx') grouped.to_excel(writer, 'Sheet 1', index=False) writer.save() And I get this error message: AttributeError: 'list' object has no attribute 'to_excel' I followed the Pandas documentation to the letter, so I'm stuck. Any thoughts?
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
tagged with: excel
type: Question
tagged with: dataframe
upvote count: 2
has title: Pandas dataframe to excel: AttributeError: 'list' object has no attribute 'to_excel'
tagged with: pandas

conda
tags question: http://stackoverflow.com/q/52175881
tags question: http://stackoverflow.com/q/52218951
tags question: http://stackoverflow.com/q/52185521
tags question: http://stackoverflow.com/q/52248147
tags question: http://stackoverflow.com/q/52200373
tags question: http://stackoverflow.com/q/52210212
tags question: http://stackoverflow.com/q/52135390
tag name: conda
tags question: http://stackoverflow.com/q/52184147
tags question: http://stackoverflow.com/q/52247021
tags question: http://stackoverflow.com/q/52219238
tags question: http://stackoverflow.com/q/52217730
tags question: http://stackoverflow.com/q/52162907
tags question: http://stackoverflow.com/q/52257564
tags question: http://stackoverflow.com/q/52263338
tags question: http://stackoverflow.com/q/52227492
tags question: http://stackoverflow.com/q/52226942
type: Tag
tags question: http://stackoverflow.com/q/52260093
tags question: http://stackoverflow.com/q/52123842

http://stackoverflow.com/q/52250115
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has body: According to the definition of the average precision (AP) score in here, the AP is calculated based on the precision and increment in recall across thresholds. In the average_precision_score function, the mandatory parameters are as follows: y_true: True binary labels in binary label indicators. y_score: Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). To my understanding, y_true is a list of the ground truth classes to which each record belongs. y_score is the list of predicted classes corresponding to each record. Likewise, for a binary classification task, y_true = [1,0,0,1,1] and y_score = [0,0,0,1,0] would be feasible parameters, where for record 1, the ground truth class is positive (1) but the predicted class is negative (0). We attempt our classification task with different thresholds. Hence we get different y_score lists for each threshold. In that case, when I apply the average_precision_score function, I would obtain an AP value per each threshold. Not a single value across thresholds as implied by the definition. In the sklearn function there is no 'threshold' parameter anyway. Can you please tell me whether my understanding of the average_precision_score function in sklearn is correct? If so, what is the reason for the contradiction with the definition?
tagged with: python
has title: How does sklearn comput the average_precision_score?
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: machine-learning
type: Question
accepted answer: http://stackoverflow.com/a/52255256
linked to: http://stackoverflow.com/q/52167659
has answer: http://stackoverflow.com/a/52255256

http://stackoverflow.com/comment/91385612
type: Comment
comment on: http://stackoverflow.com/a/52136781
type: AnswerComment
has text: @BlackThunder I've saved it correctly and still it's not working.
score: 0

http://stackoverflow.com/a/52163163
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52162125
upvote count: 2
answers question: http://stackoverflow.com/q/52162125
type: AcceptedAnswer
type: Answer
has body: If you look at the C++ example you refer to you'll see that the VerticalTextDelegate::paint implementation is basically fixing up the QPainter transform and then calling the base class implementation QStyledItemDelegate::paint. You need to do likewise (untested)... def paint(self, painter, option, index): optionCopy = QtGui.QStyleOptionViewItem(option) rectCenter = QtCore.QPointF(QtCore.QRectF(option.rect).center()) painter.save() painter.translate(rectCenter.x(), rectCenter.y()) painter.rotate(-90.0) painter.translate(-rectCenter.x(), -rectCenter.y()) optionCopy.rect = painter.worldTransform().mapRect(option.rect) # Call the base class implementation super(VerticalTextDelegate, self).paint(painter, optionCopy, index) painter.restore()

http://stackoverflow.com/q/52124181
tagged with: python
has answer: http://stackoverflow.com/a/52126158
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/52124205
type: Question
tagged with: date
has body: I am trying to use Astropy to determine a coordinate on a date/time. I want to create a list that includes dates and times increasing by the hour. For example: [2018-01-01 00:00:00,2018-01-01 01:00:00,2018-01-01 02:00:00] However, I need to have the dates be from 2018-01-01 to 2019-08-31 and include hours 0 to 24, i.e.: [2018-01-01 00:00:00,2018-01-01 01:00:00,2018-01-01 02:00:00,....2018-01-01 23:00:00,2018-01-02 00:00:00,2018-01-02 01:00:00,2018-01-02 02:00:00,.... 2018-01-02 23:00:00,...] This is what I have code thus far : import pandas as pd import numpy as np dates=[] for i in np.arange(0,24): d=pd.date_range('2018-01-01', periods=243) + pd.Timedelta(hours=i) dates.append(d) tim=[] for j,k in zip(np.arange(0,24),np.arange(0,243)): t=dates[j][k] tim.append(t) print(tim) which returns: [Timestamp('2018-01-01 00:00:00', freq='D'), Timestamp('2018-01-02 01:00:00', freq='D'), Timestamp('2018-01-03 02:00:00', freq='D'), Timestamp('2018-01-04 03:00:00', freq='D'), Timestamp('2018-01-05 04:00:00', freq='D'), Timestamp('2018-01-06 05:00:00', freq='D'), Timestamp('2018-01-07 06:00:00', freq='D'), Timestamp('2018-01-08 07:00:00', freq='D'), Timestamp('2018-01-09 08:00:00', freq='D'), Timestamp('2018-01-10 09:00:00', freq='D'), Timestamp('2018-01-11 10:00:00', freq='D'), Timestamp('2018-01-12 11:00:00', freq='D'), Timestamp('2018-01-13 12:00:00', freq='D'), Timestamp('2018-01-14 13:00:00', freq='D'), Timestamp('2018-01-15 14:00:00', freq='D'), Timestamp('2018-01-16 15:00:00', freq='D'), Timestamp('2018-01-17 16:00:00', freq='D'), Timestamp('2018-01-18 17:00:00', freq='D'), Timestamp('2018-01-19 18:00:00', freq='D'), Timestamp('2018-01-20 19:00:00', freq='D'), Timestamp('2018-01-21 20:00:00', freq='D'), Timestamp('2018-01-22 21:00:00', freq='D'), Timestamp('2018-01-23 22:00:00', freq='D'), Timestamp('2018-01-24 23:00:00', freq='D')] Please help! Thank you.
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: time
has title: Trying to Create a List with Dates and Times in Python without Time Stamps
tagged with: datetime

http://stackoverflow.com/q/52255037
answer count: 1
downvote count: 0
has body: I have a piece of python script that runs through a continuous loop (~5Hz) to obtain data from a set of sensors connected to my PC, much like a proximity sensor. I would like to translate this sensor data into audio output, using python and in a continuous manner. That is: whilst my sensor loop is running I want to generate and play a continuous sinusoidal audio sound, of which the frequency is modulated by the sensor output (e.g. higher sensor value = higher frequency). This is sort of the output that I want (without the GUI, of course: http://www.szynalski.com/tone-generator/) I've looked through a lot of the available packages (pyDub, pyAudio, Winsound)but all seem to solve a piece of the puzzle, either signal generation, saving or playing, but I can't seem to find out how to combine them. It's possible to perform frequency modulation and link different frequencies together and then save them, how to play them in real-time and without clogging up my sensor It's possible to play threaded audio using WinSound -> but how to update frequence in real-time? Or is this not a feasible route to walk on using python and should I write a script that inputs the sensor data into another more audio-friendly language? Thanks.
favorite count: 0
tagged with: frequency
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91473128
tagged with: audio
score: 1
upvote count: 1
type: Question
has title: Python: translate sensor data into continuous frequency modulated audio
has comment: http://stackoverflow.com/comment/91473023
has comment: http://stackoverflow.com/comment/91470888
tagged with: modulation
has comment: http://stackoverflow.com/comment/91470678
has answer: http://stackoverflow.com/a/52256949
has comment: http://stackoverflow.com/comment/91474615

http://stackoverflow.com/comment/91382200
type: QuestionComment
comment on: http://stackoverflow.com/q/52206232
has text: Glad I could help, and good luck finding your bug! Btw, you can just edit this question instead of posting a new one by clicking [edit].
score: 0
type: Comment

http://stackoverflow.com/comment/91364656
score: 1
comment on: http://stackoverflow.com/q/52207648
type: Comment
has text: Is this python 2 or 3?
type: QuestionComment

http://stackoverflow.com/comment/91487961
type: QuestionComment
type: Comment
has text: @cricket_007 particularly *indexing* for-loops. If you have to loop over rows, then you should at least use `itertuples`.
score: 1
comment on: http://stackoverflow.com/q/52270185

snakemake
tags question: http://stackoverflow.com/q/52257564
tags question: http://stackoverflow.com/q/52261082
tag name: snakemake
type: Tag
tags question: http://stackoverflow.com/q/52221954

http://stackoverflow.com/comment/91373396
type: QuestionComment
comment on: http://stackoverflow.com/q/52212006
score: 0
type: Comment
has text: `isinstance(element, int)` does nothing. You ignore the return value.

http://stackoverflow.com/comment/91367636
type: AnswerComment
score: 0
type: Comment
has text: Oh my god! Thank you thank you! You definitely helped me understand better what I was doing. I knew that I had to do it but not necessarily why. Reformatting the data file and using 1 space in between values instead of 2 spaces worked excellently. I understand where I went wrong now, thank you!
comment on: http://stackoverflow.com/a/52209071

http://stackoverflow.com/a/52231906
answers question: http://stackoverflow.com/q/52231686
score: 2
upvote count: 2
has body: Since you want 29,281 resulting graphs, labelling must be important for you (IOW, you're not modding out by isomorphism.) Using a brute-force approach in networkx: from itertools import combinations, product import networkx as nx def gen_dag(num_nodes): all_edges = list(combinations(range(num_nodes), 2)) for p in product([None, 1, -1], repeat=len(all_edges)): G = nx.DiGraph() G.add_nodes_from(range(num_nodes)) edges = [edge[::edge_dir] for edge, edge_dir in zip(all_edges, p) if edge_dir] G.add_edges_from(edges) if nx.is_directed_acyclic_graph(G): yield G which gives In [75]: graphs = list(gen_dag(5)) In [76]: len(graphs) Out[76]: 29281 and (for example) In [79]: graphs[1234].edges() Out[79]: OutEdgeView([(3, 1), (3, 4), (4, 0), (4, 2)]) In [80]: nx.adjacency_matrix(graphs[1234]).todense() Out[80]: matrix([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 1, 0, 0]], dtype=int64)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91413398
accepted answer of: http://stackoverflow.com/q/52231686
type: Answer

http://stackoverflow.com/a/52188363
upvote count: 2
answers question: http://stackoverflow.com/q/52188203
downvote count: 0
has body: df.profile_id.str.split(",",expand=True).set_index(a.user).stack().reset_index(level=1, drop=True).reset_index().rename(columns={0:"profile_id"})
type: Answer
score: 2

http://stackoverflow.com/a/53810082
upvote count: 0
answers question: http://stackoverflow.com/q/52236276
score: -1
downvote count: 1
type: Answer
has body: pytesseract should be sufficient, if the file is in 'png' or 'jpg' form. now suppose image is the name of your image. Please write the below code. from PIL import Image from pytesseract import image_to_string import pytesseract pytesseract.pytesseract.tesseract_cmd = r'C:/Program Files (x86)/Tesseract-OCR/tesseract.exe' im = Image.open('F:/kush/invert.jpg') pytesseract.image_to_string(im, lang = 'eng')

http://stackoverflow.com/q/52140256
has comment: http://stackoverflow.com/comment/91230148
answer count: 3
tagged with: indentation
favorite count: 0
linked to: http://stackoverflow.com/q/21764912
score: -4
tagged with: python
has comment: http://stackoverflow.com/comment/91245417
has comment: http://stackoverflow.com/comment/91230150
downvote count: 4
type: AnsweredQuestion
upvote count: 0
has title: How to fix "IndentationError: expected an indented block" in Python?
has comment: http://stackoverflow.com/comment/91230223
has comment: http://stackoverflow.com/comment/91230144
has body: I am trying to do a API test on a URL with Python, I have the following code block def simple_get(url): try: page_response = requests.get(page_link, timeout=5) if page_response.status_code == 200: # extract else: print(page_response.status_code) # notify, try again except requests.Timeout as e: print("It is time to timeout") print(str(e)) except # other exception When I run it give me the following error File "&lt;ipython-input-16-6291efcb97a0&gt;", line 11 else: ^ IndentationError: expected an indented block I dont understand why is the notebook still asking for indentation when I already have the "else" statement indented
has answer: http://stackoverflow.com/a/52140292
accepted answer: http://stackoverflow.com/a/52140292
type: Question
has comment: http://stackoverflow.com/comment/91230146
has answer: http://stackoverflow.com/a/52140766
tagged with: if-statement
has comment: http://stackoverflow.com/comment/91230161
possible better answer: http://stackoverflow.com/a/52140510
has answer: http://stackoverflow.com/a/52140510
has comment: http://stackoverflow.com/comment/91245411

http://stackoverflow.com/q/52200599
tagged with: tensorflow
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52210172
accepted answer: http://stackoverflow.com/a/52210172
answer count: 1
downvote count: 0
tagged with: keras
has body: I am doing king of transfer learning. What I have done is First train the model with the big datasets and save the weights. Then I train the model with my dataset by freezing the layers. But I see there was some overfitting. So I try to change the dropout of the model and load the weights since the numbers are changing while drop out are changing. I find difficulties to change the dropout. Directly my question is, Is it possible to change the model's dropout while loading the weights? my scenario 1 is like that model defined. train the model. list item save weights. ... redefine the dropout others are not changed in the model load the weights . I got the error. 2nd Scenario model1 defined. train the model. save weights load model1 weights to model1 .... model2 defined by changing the dropouts. try to set the wights of model1 to model 2 using for loop except for the dropout layer. I got an error. This is the error I got. File "/home/sathiyakugan/PycharmProjects/internal-apps/apps/support-tools/EscalationApp/LSTM_Attention_IMDB_New_open.py", line 343, in &lt;module&gt; NewModel.layers[i].set_weights(layer.get_weights()) File "/home/sathiyakugan/PycharmProjects/Python/venv/lib/python3.5/site-packages/keras/engine/base_layer.py", line 1062, in set_weights str(weights)[:50] + '...') ValueError: You called `set_weights(weights)` on layer "lstm_5" with a weight list of length 1, but the layer was expecting 3 weights. Provided weights: [array([[ 0. , 0. , 0. , ..., 0.... What is the right way to go? Since I am new to Keras, I am struggling to go further.
favorite count: 0
has comment: http://stackoverflow.com/comment/91350927
has title: Add DropOut after loading the weights in Keras
tagged with: python
tagged with: nlp
tagged with: transfer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91351366

http://stackoverflow.com/q/52113386
answer count: 3
has comment: http://stackoverflow.com/comment/91177247
tagged with: python
has title: Return None in function: TypeError: object of type 'NoneType' has no len()
favorite count: 0
has answer: http://stackoverflow.com/a/52114144
downvote count: 1
type: AnsweredQuestion
tagged with: lda
score: -1
type: Question
accepted answer: http://stackoverflow.com/a/52114144
has comment: http://stackoverflow.com/comment/91177251
has answer: http://stackoverflow.com/a/52113464
tagged with: nonetype
upvote count: 0
has answer: http://stackoverflow.com/a/52113474
has body: I am trying to print my topics and texts from each topic in LDA. But a None after printing the topics is disrupting my script. I can print my topics but not the texts. import pandas import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.decomposition import LatentDirichletAllocation n_top_words = 5 n_components = 5 def print_top_words(model, feature_names, n_top_words): for topic_idx, topic in enumerate(model.components_): message = "Topic #%d: " % topic_idx message += " ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]]) return message text = pandas.read_csv('text.csv', encoding = 'utf-8') text_list = text.values.tolist() tf_vectorizer = CountVectorizer() tf = tf_vectorizer.fit_transform(text_list) lda = LatentDirichletAllocation(n_components=n_components, learning_method='batch', max_iter=25, random_state=0) doc_distr = lda.fit_transform(tf) tf_feature_names = tf_vectorizer.get_feature_names() print (print_top_words(lda, tf_feature_names, n_top_words)) doc_distr = lda.fit_transform(tf) topics = print_top_words(lda, tf_feature_names, n_top_words) for i in range(len(topics)): print ("Topic {}:".format(i)) docs = np.argsort(doc_distr[:, i])[::-1] for j in docs[:10]: print (" ".join(text_list[j].split(",")[:2])) My output: Topic 0: no order mail received back Topic 1: cancel order wishes possible wish Topic 2: keep current informed delivery order Topic 3: faulty wooden box present side Topic 4: delivered received be produced urgent Topic 5: good waiting day response share Followed by this error: File "lda.py", line 41, in &lt;module&gt; for i in range(len(topics)): TypeError: object of type 'NoneType' has no len()
possible better answer: http://stackoverflow.com/a/52113464

http://stackoverflow.com/q/52201590
score: 0
answer count: 1
has title: PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed (multiprocessing)
has comment: http://stackoverflow.com/comment/91358296
linked to: http://stackoverflow.com/q/8804830
has comment: http://stackoverflow.com/comment/91355115
type: UnansweredQuestion
has body: I am going to implement a kind of time-series clustering method, which my optimization solution is based on frank-wolfe algorithm. I would like to parallelize it by multiprocessing library in python, but I face the following problem: Traceback (most recent call last): File "/home/ridha/Downloads/pycharm-2018.1.2/helpers/pyde/pydev_run_in_console.py", line 52, in run_file pydev_imports.execfile(file, globals, locals) # execute the script File "/home/ridha/Desktop/TICC-FW/TICC-master/example.py", line 8, in &lt;module&gt; (cluster_assignment, cluster_MRFs) = ticc.fit(input_file=fname) File "/home/ridha/Desktop/TICC-FW/TICC-master/TICC_solver.py", line 111, in fit train_cluster_inverse) File "/home/ridha/Desktop/TICC-FW/TICC-master/TICC_solver.py", line 295, in optimize_clusters val = optRes[cluster].get() File "/home/ridha/anaconda2/lib/python2.7/multiprocessing/pool.py", line 572, in get raise self._value PicklingError: Can't pickle &lt;type 'function'&gt;: attribute lookup __builtin__.function failed and my code is: probSize = self.window_size * size_blocks lamb = np.zeros((probSize, probSize)) + self.lambda_parameter S = np.cov(np.transpose(D_train)) empirical_covariances[cluster] = S # rho = 1 lamb_vec = lamb.flatten() lamb_vec_abs = np.absolute(lamb_vec) s_vec = S.flatten() aub = np.identity(probSize*probSize) bub = np.ones(probSize*probSize) def loss(x): theta = np.reshape(x, (probSize, probSize)) det_theta = -np.linalg.det(theta) return det_theta + (np.matmul(s_vec, x)) + ( np.matmul(lamb_vec_abs, np.absolute(x))) solver = FrankWolfe(f=loss, g=None, A_ub=aub, b_ub=bub, A_eq=None, b_eq=None, bounds=None, tol=1.0E-12, gradient_delta=1.0E-10, iteration_limit=1000) # solver.verbose = True # apply to process pool optRes[cluster] = pool.apply_async(solver) I would appreciate any help
has answer: http://stackoverflow.com/a/52204140
type: Question
has comment: http://stackoverflow.com/comment/91356407
tagged with: python

http://stackoverflow.com/a/52241446
answers question: http://stackoverflow.com/q/52209760
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52209760
type: Answer
has body: This issue has been resolved in the comments by Michael. Reproducing the comment below Set the lpCurrentDirectory parameter accordingly. It will be used to resolve relative paths (if a program doesn't set the current working directory explicitly later) –
score: 0

http://stackoverflow.com/comment/91378756
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52214768
has text: also you say `False`, it is `None`, you say `True`, it is a regex object
score: 1

http://stackoverflow.com/q/52149683
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52149788
downvote count: 3
has body: I've been figuring about question 7 of project Euler. I've worked out the my Python code, but it has no output, and I don't know if there are any grammatical and logical problems. Would you please help me check what's wrong with it? Here is the original question: By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? def isprime(n): for i in range(2,n): if n % i == 0: return False return True x = 3 counter = 2 while counter &lt;= 10001: if isprime(x): counter += 1 x += 2 else: x += 2 print (x)
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91249340
has comment: http://stackoverflow.com/comment/91250028
score: -1
has comment: http://stackoverflow.com/comment/91250081
possible better answer: http://stackoverflow.com/a/74911098
has answer: http://stackoverflow.com/a/74911098
has answer: http://stackoverflow.com/a/52149788
favorite count: 0
has comment: http://stackoverflow.com/comment/91249557
upvote count: 2
has title: Question about Project Euler problem 7 in Python
linked to: http://stackoverflow.com/q/48039350
tagged with: python
has comment: http://stackoverflow.com/comment/91249562

http://stackoverflow.com/comment/91334358
type: Comment
comment on: http://stackoverflow.com/a/52192301
type: AnswerComment
has text: Thank you, I did not know the inspect api could do that
score: 0

http://stackoverflow.com/q/52216260
score: 0
has comment: http://stackoverflow.com/comment/91381300
tagged with: pandas
answer count: 1
linked to: http://stackoverflow.com/q/20625582
tagged with: python
accepted answer: http://stackoverflow.com/a/52216311
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52216311
type: Question
tagged with: dataframe
has body: I have a pandas.DataFrame named fake_num: fake_num=pd.DataFrame([[1,2,3,4,np.nan,np.nan,np.nan],[1.1,1.2,1.3,1.4,1.6,1.8,2.5]]).T fake_num Out[4]: 0 1 0 1.0 1.1 1 2.0 1.2 2 3.0 1.3 3 4.0 1.4 4 NaN 1.6 5 NaN 1.8 6 NaN 2.5 I am trying to fill the NaN values using a linear regression: from sklearn.linear_model import LinearRegression fdrop=fake_num.dropna(axis=0,how='any') lr=LinearRegression() lr.fit(np.array(fdrop.iloc[:,1]).reshape(-1, 1),np.array(fdrop.iloc[:,0])) lr.predict(np.array(fake_num[np.isnan(fake_num[0])][1]).reshape(-1, 1)) Out[5]: array([ 6., 8., 15.]) The part I want to replace is fake_num[np.isnan(fake_num[0])][0]so what I want is: Out[6]: 0 1 0 1.0 1.1 1 2.0 1.2 2 3.0 1.3 3 4.0 1.4 4 6.0 1.6 5 8.0 1.8 6 5.0 2.5 While I tried: fake_num[np.isnan(fake_num[0])][0]=lr.predict(np.array(fake_num[np.isnan(fake_num.iloc[:,0])].iloc[:,1]).reshape(-1, 1)) fake_num __main__:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy Out[11]: 0 1 0 1.0 1.1 1 2.0 1.2 2 3.0 1.3 3 4.0 1.4 4 NaN 1.6 5 NaN 1.8 6 NaN 2.5 And fake_num[np.isnan(fake_num.loc[:,0])].loc[:,0]=lr.predict(np.array(fake_num[np.isnan(fake_num.iloc[:,0])].iloc[:,1]).reshape(-1, 1)) fake_num D:\Users\shan xu\Anaconda3\lib\site-packages\pandas\core\indexing.py:630: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy self.obj[item_labels[indexer[info_axis]]] = value Out[12]: 0 1 0 1.0 1.1 1 2.0 1.2 2 3.0 1.3 3 4.0 1.4 4 NaN 1.6 5 NaN 1.8 And fake_num[np.isnan(fake_num.iloc[:,0])].iloc[:,0]=lr.predict(np.array(fake_num[np.isnan(fake_num.iloc[:,0])].iloc[:,1]).reshape(-1, 1)) fak…
has title: replace a part of pandas data.frame by given array

http://stackoverflow.com/comment/91375534
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52212053
type: AnswerComment
has text: @cdarke That applies only to `man`. On my Debian box, `which pager` is `/usr/bin/pager -> /etc/alternatives/pager -> /bin/less`

http://stackoverflow.com/comment/91267103
has text: List comprehension implys that a list() to be generated. From your question, you do not need a list. So why do you need list comprehension?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52158494

http://stackoverflow.com/comment/91274137
has text: @SvenFester The browser recevie HTML from GET correctly. But when I click a button and want to refresh my page with POST . It didn't work.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52161656

http://stackoverflow.com/comment/95856186
type: Comment
comment on: http://stackoverflow.com/a/52131384
has text: Just tested, if you use `registerCustomWidget` with the exact class name, and you use the exact same class name in the XML `<widget>` definition, then the `<customwidgets/>` section can be omitted.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91223854
has text: Why do you say -10 is correct and +14 is not correct? [This page](https://www.zeitverschiebung.net/en/timezone/pacific--apia) says Pacific/Apia is UTC+13 normally and UTC+14 in DST.
score: 0
comment on: http://stackoverflow.com/q/52136980
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52235219
has title: Running Multiple Function calls inside pyspark in parallel
downvote count: 1
tagged with: multiprocessing
type: Question
tagged with: pyspark
has comment: http://stackoverflow.com/comment/91419319
score: -1
has body: I have a function which i am running in pyspark-shell import pandas as pd def compute(x): data = pd.read_csv("/tmp/data_{}.csv".format(x)) # Some Spark processing # Writes back final output in tmp I want to run this in parallel over a list of x. I tried this - x_list=[14,63] from multiprocessing import Process for x in x_list: p = Process(target = compute, args = (x,)) p.start() This finishes the script. I want them to run fully before script finishes. How can i achieve this ?
tagged with: python-multiprocessing
has comment: http://stackoverflow.com/comment/91419306
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52236975
has comment: http://stackoverflow.com/comment/91418983
favorite count: 0
accepted answer: http://stackoverflow.com/a/52236975
tagged with: pandas
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/91346782
comment on: http://stackoverflow.com/q/52198434
type: QuestionComment
type: Comment
score: 1
has text: If you let multiple threads call this function without protection, you have what is known as a [*race condition*](https://en.wikipedia.org/wiki/Race_condition). The behavior of such events is generally undefined and unpredictable (and usually leads to bad things happening).

http://stackoverflow.com/q/52186091
has comment: http://stackoverflow.com/comment/91325313
has comment: http://stackoverflow.com/comment/91325093
has body: I try to run the attached code and the attached error pops up. I try to run the code through pycharm and scikit learn and tensorflow are installed. I tried to perform python setup.py install as the comment suggests, in the path of C: \ Users \ nirkov \ AppData \ Roaming \ Python \ Python36 \ site-packages \ sklearn \ __ check_build And that did not solve the problem. Am I wrong where I execute the command? Does anyone know what the problem might be? (I was looking for this problem on the web, but unfortunately I could not fix the problem) the code - import numpy as np import tensorflow as tf from sklearn.datasets import fetch_california_housing housing = fetch_california_housing() m, n = housing.data.shape housing_data_plus_bias = np.c_[np.ones((m,1)),housing.data] X = tf.constant(housing_data_plus_bias, dtype=tf.float32, name="X") Y = tf.constant(housing.target.reshape(-1,1), dtype=tf.float32, name="Y") X_Transpose = tf.transpose(X) theta = tf.matmul(tf.matmul(tf.matrix_inverse(tf.matmul(X_Transpose, X)), X_Transpose), y) with tf.Session() as sess: theta_value = theta.eval() the error - "C:\Program Files\Python36\python.exe" "D:/Python Projects/learningTensorFlow/LinearRegressionWithTensorFlow.py" Traceback (most recent call last): File "C:\Users\nirkov\AppData\Roaming\Python\Python36\site-packages\sklearn\__check_build\__init__.py", line 44, in &lt;module&gt; from ._check_build import check_build # noqa ModuleNotFoundError: No module named 'sklearn.__check_build._check_build' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:/Python Projects/learningTensorFlow/LinearRegressionWithTensorFlow.py", line 3, in &lt;module&gt; from sklearn.datasets import fetch_california_housing File "C:\Users\nirkov\AppData\Roaming\Python\Python36\site-packages\sklearn\__init__.py", line 133, in &lt;module&gt; from . import __check_build File "C:\Users\nirkov\AppData\Roaming\Python\Python36\site-packages\sklearn\__check_buil…
type: UnansweredQuestion
tagged with: python
has title: Problems with importing dataset from scikit-learn
answer count: 0
score: 0
type: Question
has comment: http://stackoverflow.com/comment/91322457
tagged with: scikit-learn

http://stackoverflow.com/q/52142769
tagged with: python
has comment: http://stackoverflow.com/comment/91236060
has body: This is my current dataframe. df =pd.DataFrame({'Observation':index,'x':x,'y':y,'dx':np.round(dx, decimals =2),'vx':np.round(vx, decimals=2),'dy':np.round(dy, decimals=2),'vy':np.round(vy, decimals=2), 'pxy':np.round(pxy, decimals=2)}) df = df.reindex_axis(['Observation','x','y','dx','vx','dy','vy', 'pxy'], axis=1) df.loc['SUM']=df. df I would like the my Observation Column to the index of the dataframe. How can I do it? Also, is it possible for the values in columns dx,dy,vx,vy and pxy to be shown in 2 decimal place?
type: Question
tagged with: indexing
has answer: http://stackoverflow.com/a/52144824
has answer: http://stackoverflow.com/a/66730715
has comment: http://stackoverflow.com/comment/91262460
has answer: http://stackoverflow.com/a/52142837
tagged with: dataframe
score: 0
answer count: 3
tagged with: pandas
has title: How do I either remove index of the data frame or replace it?
has comment: http://stackoverflow.com/comment/91235611
tagged with: python-3.x
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/15619096

http://stackoverflow.com/a/52272137
upvote count: 8
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52161964
has body: There is a workaround to have optional parameters. The idea is to examine arguments before resolving them (Scala): val argName = 'ISO_8601_STRING' var argValue = null if (sysArgs.contains(s"--$argName")) argValue = GlueArgParser.getResolvedOptions(sysArgs, Array(argName))(argName)
score: 8

http://stackoverflow.com/a/52137260
has comment: http://stackoverflow.com/comment/91224191
type: Answer
has comment: http://stackoverflow.com/comment/91224377
downvote count: 0
has comment: http://stackoverflow.com/comment/91224264
has comment: http://stackoverflow.com/comment/91224432
score: 1
accepted answer of: http://stackoverflow.com/q/52137212
answers question: http://stackoverflow.com/q/52137212
upvote count: 1
type: AcceptedAnswer
has body: You can use re.findall to extract all xlarge urls using the regexp r'"xlarge":"(.*?)" &gt;&gt;&gt; re.findall(r'"xlarge":"(.*?)"', text) ['https://i.ebayimg.com/00/s/NTU5WDEwMjY=/z/TQMAAOSwkrFaZqhh/$_20.PNG', 'https://i.ebayimg.com/00/s/ODAwWDgwMA==/z/uX0AAOSwvGlaZqhU/$_20.JPG', 'https://i.ebayimg.com/00/s/NjMwWDk2MA==/z/n58AAOSwp-RaZqhn/$_20.PNG']
has comment: http://stackoverflow.com/comment/91224405

http://stackoverflow.com/a/52348190
has body: It's reasonable to have a very low level object that is used to access the db and is reused over and over again. In fact I think you're better off having a singleton that does the db access and is only created once per session. The only question from there is if you should have layers between the DB object and your business logic (likely answer is yes).
type: Answer
has comment: http://stackoverflow.com/comment/91649969
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52177830
answers question: http://stackoverflow.com/q/52177830
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/52255753
score: 3
upvote count: 3
has body: Simply use while? import os from os.path import join import subprocess def opening_file(lookfor): global store_1 for root, dirs, files in os.walk('/home/'): if lookfor in files: file = join(root, lookfor) store_1.append(join(root, lookfor)) if len(store_1) &lt;= 0: ask_1 = str(input("Your file was not found. Do you want to try again(Y/n)?:")) #This is where I have the problem elif len(store_1) &gt; 0: print("Your file was found") subprocess.call(["xdg-open", file]) #print(store_1) store_1 = [] print("Welcome to our program for working with files.") choice = "" while(choice.lower() != "f"): print("Press O for opening and editing a file, C for making a copy of a file. M for moving a file and R for renaming a file. If you are done working with the file, press F to end the program.") choice = str(input("Your choice:")) if choice == "O" or choice == "o": lookfor = input("File name(make sure to include the extension as well):") opening_file(lookfor)
accepted answer of: http://stackoverflow.com/q/52255642
answers question: http://stackoverflow.com/q/52255642
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91458698

http://stackoverflow.com/q/52188275
downvote count: 0
has answer: http://stackoverflow.com/a/52191659
has answer: http://stackoverflow.com/a/73396396
answer count: 3
has title: How to draw a square wherever you click in the pygame window
tagged with: pygame
has body: You probably know what I want to do from the title but here's a simple example: #User clicks somewhere in the pygame window pos = cursorPosition() #Function/Class that creates a square where the user clicked. I have tried this: import pygame import sys running = True pygame.init() screen = pygame.display.set_mode((800, 500)) pos = pygame.mouse.get_pos() class Create(): cx, cy = pygame.mouse.get_pos() square = pygame.Rect(cx, cy, 50, 50) def cube(self): self.square = pygame.Rect(self.cx, self.cy, 50, 50) pygame.draw.rect(screen, (255, 0, 0), self.square) pygame.display.flip() create = Create() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() create.cube() screen.fill((0, 255, 0)) pygame.display.flip() pygame.quit() sys.exit() But it just gives me a Blue screen and when I click anywhere it doesn't do anything, so if you can help me it would be much appreciated. Thanks! EDIT: I've managed to do it but now I face another problem: The square would appear only if I hold down the mouse button. This is the code import pygame import sys running = True pygame.init() screen = pygame.display.set_mode((800, 500)) pos = pygame.mouse.get_pos() class Create(): cx, cy = pygame.mouse.get_pos() square = pygame.Rect(cx, cy, 50, 50) def cube(self): self.cx, self.cy = pygame.mouse.get_pos() self.square = pygame.Rect(self.cx, self.cy, 50, 50) pygame.draw.rect(screen, (255, 0, 0), self.square) pygame.display.flip() create = Create() while running: screen.fill((0, 255, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.MOUSEBUTTONDOWN: create.cube() pygame.display.flip() pygame.quit() sys.exit()
favorite count: 0
has answer: http://stackoverflow.com/a/54951655
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
type: Question

http://stackoverflow.com/q/52131612
has comment: http://stackoverflow.com/comment/91213735
has comment: http://stackoverflow.com/comment/91216741
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/52131666
has comment: http://stackoverflow.com/comment/91213921
has body: I would like a list to be stored into another list from right to left diagonally without importing anything if possible eg. list = [[1, 4, 6] [6, 3, 7] [2, 7, 9]] say I'd like to store [6, 3, 2] into another list, how would i go about doing it? I have tried many ways for hours and still cant find a solution
type: Question
has title: Python right to left diagonal list
has answer: http://stackoverflow.com/a/52131666
tagged with: algorithm
has answer: http://stackoverflow.com/a/52133132
has answer: http://stackoverflow.com/a/52132689
score: 0
possible better answer: http://stackoverflow.com/a/52133132
tagged with: python-3.x
answer count: 5
has answer: http://stackoverflow.com/a/52136379
has answer: http://stackoverflow.com/a/52133155
tagged with: python

http://stackoverflow.com/comment/91288972
comment on: http://stackoverflow.com/a/52168095
type: Comment
has text: Adding a new method if you interested . :-)
score: 1
type: AnswerComment

http://stackoverflow.com/comment/91287972
has text: @BearBrown it's not a circular import problem. This happens even if I don't import anything from `utils/filters.py`. It's a name conflict between `utils/` and `polls/utils.py`. Python tries to find `filters.MyFilter` inside `polls/utils.py` and it doesn't so it throws the error. I just want to figure out a way to bypass this conflict and force python to look for `filters.MyFilter` inside the `utils/` package in the project root.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52168700

http://stackoverflow.com/a/52162003
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52161826
upvote count: 2
has comment: http://stackoverflow.com/comment/91273676
type: Answer
has comment: http://stackoverflow.com/comment/91273988
score: 2
has body: In your CheckoutView, you only call get_reserved_items_or_redirect(request). To make it works, just refactor your dispatch method to return the return value of this method. def dispatch(self, request, *args, **kwargs): if some_value: # Check if you need to perform redirect return get_reserved_items_or_redirect(request) else: # If redirect is not required return super().dispatch(request, *args, **kwargs)
answers question: http://stackoverflow.com/q/52161826

http://stackoverflow.com/q/52171040
tagged with: matplotlib
has body: The goal is to generate a single figure with multiple subplots. The following code generates 4 separate plots Sublists to plot: Can the same loop be used on both sets of data? x vs. y and b vs. p The difference between the two data sets is x vs. y will make 4 plots while b vs. p will make 2 x = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]] y = [[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]] p = [[17, 16, 6, 15, 6, 7, 6, 7, 9, 11], [16, 13, 9, 11, 12, 13, 6, 12, 13, 7]] b = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]] colours=['r','g','b','k'] Loop that plots them for i in range(len(x)): plt.plot(x[i], y[i],colours[i]) plt.show() Is it possible to create a function that loops through each created plot and adds it to one figure or a single pdf so that all 4 plots can be viewed at once?
accepted answer: http://stackoverflow.com/a/52171210
score: 0
answer count: 1
has title: Individual plots into one figure using matplotlib python
has answer: http://stackoverflow.com/a/52171210
tagged with: python
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/91308336
has text: @Mr.T Turns out the issue was that I copied and pasted instead of downloaded the file.
comment on: http://stackoverflow.com/q/52177938
type: Comment
type: QuestionComment
score: 0

pygsheets
tags question: http://stackoverflow.com/q/52159382
tags question: http://stackoverflow.com/q/52196342
tag name: pygsheets
type: Tag
tags question: http://stackoverflow.com/q/52169542

http://stackoverflow.com/q/52218538
has title: How to put variable length tick labels inside the plot canvas in matplotlib?
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91386015
tagged with: python
tagged with: plot
has body: I want to turn this: into something resembling this: All of the instructions I have come across just apply an offset to the label position and therefore only work if the labels are of a known width. code to produce a similar plot than the example: #!/usr/bin/env python3 import matplotlib.pyplot as plt yvalues = [ 'short name', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', 'slightly longer name' ] xvalues = [ [1, 5], [3, 7], [2, 6] ] fig, ax = plt.subplots() fig.set_size_inches(1280/fig.get_dpi(), 720/fig.get_dpi()) ax.axvline(40) for i in range(len(yvalues)): ax.plot(xvalues[i], (yvalues[i], yvalues[i])) plt.show()
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52218829
score: 1
tagged with: matplotlib
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91385995
has comment: http://stackoverflow.com/comment/91385898
accepted answer: http://stackoverflow.com/a/52218829

http://stackoverflow.com/a/52132963
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91216614
accepted answer of: http://stackoverflow.com/q/52132584
answers question: http://stackoverflow.com/q/52132584
has body: From the doc of plt.matshow Tick labels for the xaxis are placed on top. As ImportanceOfBeingErnest suggests, you can use plt.gca().xaxis.set_label_position('top') to move the x label. plt.figure(figsize=(10,10)) plt.matshow(norm_conf_mx,cmap="gray",fignum=1) plt.ylabel('Actual Class') plt.xlabel('Predicted Class') plt.xticks(nums, my_ticks) plt.yticks(nums, my_ticks) plt.gca().xaxis.set_label_position('top') plt.show() You can use plt.imshow to show the x axis values in the botton plt.figure(figsize=(10,10)) plt.imshow(norm_conf_mx,cmap="gray",) plt.ylabel('Actual Class') plt.xlabel('Predicted Class') plt.xticks(nums, my_ticks) plt.yticks(nums, my_ticks) plt.show()
type: Answer

http://stackoverflow.com/a/52168528
accepted answer of: http://stackoverflow.com/q/52166475
type: Answer
answers question: http://stackoverflow.com/q/52166475
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91290273
upvote count: 1
type: AcceptedAnswer
has body: If DataTables is sending a new value for draw to your server-- just read that value and send it back: @app.route("/api/result") def result_json(): return jsonify(z) Could just become (adjust the code if DataTables sends the values in some other way): @app.route("/api/result") def result_json(): z.update({'draw': request.form.get('draw')}) return jsonify(z) I'm not addressing that your code doesn't seem to do anything with filtering or searching, but at least it gives you a starting point to build from. Update From the XHR code you pasted-- it looks like DataTables is passing values in via querystrings-- so request.args.get('draw') would be the way to access that draw data-value.

http://stackoverflow.com/a/52270670
score: 0
has comment: http://stackoverflow.com/comment/91488931
answers question: http://stackoverflow.com/q/52270177
type: Answer
has body: The most probably you are making a mistake using flow_from_directory. Reading the docs: flow_from_directory(directory, ...) Where: directory: Path to the target directory. It should contain one subdirectory per class. Any PNG, JPG, BMP, PPM or TIF images inside each of the subdirectories directory tree will be included in the generator. That means that inside the directory that you are passing to this function, you have to create subdirectories and place your images inside this subdirectories. Otherwise, when the images are in the directory that you are passing (not subdirectories), indeed there are 0 images and 0 classes. EDIT Okay so in case of the prediction you want to perform I believe that you want to use the predict function as follows: (note that you have to provide data to the network just in the same format as you did during learning process) image = img_to_array(load_img(f"{directory}/{foldername}/{filename}")) # here you prepare the input data, for example here we take the gray image # gray scale is the 1st channel in the Lab color space color_me = rgb2lab((1.0 / 255) * color_me)[:, :, 0] color_me = color_me.reshape(color_me.shape + (1,)) # here data is in the format which is accepted by, in this case, my model # for your model you have to do the preparation just the same as in the case of learning process output = model.predict(np.array([color_me])) # and here you have your predicted output
has comment: http://stackoverflow.com/comment/91489054
has comment: http://stackoverflow.com/comment/91489025
has comment: http://stackoverflow.com/comment/91488551

http://stackoverflow.com/comment/91483752
type: QuestionComment
score: 1
has text: You simply need to give all your Label variables unique names. Right now you've named them all `self.label`. Or, much neater: you could use a container like a list to hold those objects rather than giving them all a name.
comment on: http://stackoverflow.com/q/52267945
type: Comment

http://stackoverflow.com/comment/91202196
type: Comment
comment on: http://stackoverflow.com/a/52118554
has text: 319 7.35E+11 HTTP Error 404: Not Found '@MarriottRewards 14 #RewardsPoints https://twitter.com/va0JsrIavm' Unknown https://twitter.com/va0JsrIavm' 496 7.35E+11 Parsed " Connect and Start Earning | Chirpify " United States https://twitter.com/GVNyqWEu5u Now you'd note for the URL alongside row 319 is https://twitter.com/va0JsrIavm', now since it has a punctuation at the end, the code is unable to parse the URL & gives the 404 error. Therefore, comes my question, "how do I Identify & Remove Special Characters / Punctuation for the end of a Python List of URL's". Hope this is more clear now.
score: 0
type: AnswerComment

http://stackoverflow.com/a/52267106
has comment: http://stackoverflow.com/comment/91483019
score: 0
answers question: http://stackoverflow.com/q/52266049
has comment: http://stackoverflow.com/comment/91483415
has comment: http://stackoverflow.com/comment/91482911
has body: I think I've found part of the problem. I was using the incorrect Newton's algorithm. While before I was using: x{k+1} = x{k}-f(x)⁄∇f(x) The correct update is: x{k+1} = x{k} - [f''(x{k})]-1f'(x{k}) When I changed this, the result still diverges, but it is slightly better. The new function is here: f = lambda x: 100*np.square(x[1]-np.square(x[0])) + np.square((1-x[0])) dfx1 = lambda x: -400*x[0]*x[1]+400*np.power(x[0],3)+2*x[0]-2 dfx2 = lambda x: 200*(x[1]-np.square(x[0])) dfx = lambda x: np.array([-400*x[0]*x[1]+400*np.power(x[0],3)+2*x[0]-2, 200*(x[1]-np.square(x[0]))]) dfx11 = lambda x: -400*(x[1])+1200*np.square(x[0])+2 dfx12 = lambda x: -400*x[0] dfx21 = lambda x: -400*x[0] dfx22 = lambda x: 200 hessian = lambda x: np.array(([dfx11(x0), dfx12(x0)], [dfx21(x0), dfx22(x0)])) inv_hessian = lambda x: inv(np.array(([dfx11(x0), dfx12(x0)], [dfx21(x0), dfx22(x0)]))) def newton(x, t, count, magnitude): xvalues=[] gradvalues=[] fvalues=[] temp = x-(inv_hessian(x).dot(dfx(x))) while count < 25: xvalues.append(x) gradvalues.append(dfx(x)) fvalues.append(f(x)) temp = x-(inv_hessian(x).dot(dfx(x))) x = temp magnitude = mag(dfx(x)) count+=1 if count > 100: break return xvalues, gradvalues, fvalues, count The nearest the solution gets to converging is after the first step, where it goes to (-1.05, 1.1). However, it still diverges. I'm never worked with the Newton-method so I am unsure if this is as accurate as the algorithm is meant to get or not.
type: Answer
has comment: http://stackoverflow.com/comment/91483396
has comment: http://stackoverflow.com/comment/91483351
has comment: http://stackoverflow.com/comment/91483289
has comment: http://stackoverflow.com/comment/91482790
has comment: http://stackoverflow.com/comment/91483614

http://stackoverflow.com/q/52180059
score: 1
has body: In my example, I've created a complete debug output of my test via logging. Everything works and I hand this over to a file. A few questions: Is it possible to write a File Pro test? Is there a possibility if a.) Is not possible to make the Debug Log Pro test clearer? i used for the first Info https://docs.python.org/3/library/logging.html task Single executed test either from the format mr faster and better log in the debug log Individual test after each test run a separate file used modules import testcore from testcore.control.ssh import SSH import unittest from test import support import logging import os used Debug information logging.basicConfig(filename='test.log', level=logging.DEBUG, format='%(asctime)s:%(created)f:%(levelno)s:%(message)s:%(process)d')
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
answer count: 1
tagged with: logging
has answer: http://stackoverflow.com/a/52208938
upvote count: 1
has title: Python logging more overview in logfile?
tagged with: unit-testing
type: UnansweredQuestion
tagged with: error-logging
downvote count: 0

http://stackoverflow.com/q/52146312
score: 0
answer count: 2
has title: netmiko connection error - TypeError: connect() got an unexpected keyword argument 'passphrase'
tagged with: cisco
has answer: http://stackoverflow.com/a/52229603
tagged with: python
has body: I'm taking my first steps with netmiko and trying a basic connection: from netmiko import ConnectHandler device = ConnectHandler(device_type="cisco_ios", ip="10.118.10.8", username="name", password="passowrd") output = device.send_command("show version") print output device.disconnect() I've tries device_type="cisco_ios" and arista_eos, on both occasions I receive the following: Traceback (most recent call last): File "netmiko_v1.py", line 3, in &lt;module&gt; device = ConnectHandler(device_type="cisco_ios", ip="10.118.10.8", username="name", password="password") File "build/bdist.linux-x86_64/egg/netmiko/ssh_dispatcher.py", line 205, in ConnectHandler File "build/bdist.linux-x86_64/egg/netmiko/base_connection.py", line 270, in __init__ File "build/bdist.linux-x86_64/egg/netmiko/base_connection.py", line 766, in establish_connection TypeError: connect() got an unexpected keyword argument 'passphrase' I'm assuming I'm getting something very simple and obvious wrong, any suggestions? To add packet capture shows nothing toward target IP addresses so assuming this is a local issue. Due to lack of privileges on host I had to install netmiko in user-space, not sure if this could cause issues?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91376423
has answer: http://stackoverflow.com/a/52306900
type: Question

http://stackoverflow.com/comment/91477395
comment on: http://stackoverflow.com/a/52264668
has text: How is it giving those zeros though?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91379599
comment on: http://stackoverflow.com/q/52188421
type: Comment
type: QuestionComment
has text: i am gonna increase the time between two screenshot intervals, like for 15 min,
score: 0

http://stackoverflow.com/q/52211142
tagged with: django-rest-framework
has title: Method "POST" not allowed with Django Rest Framework
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52214799
upvote count: 2
has comment: http://stackoverflow.com/comment/91371796
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91371924
tagged with: json-api
type: AnsweredQuestion
downvote count: 3
score: -1
accepted answer: http://stackoverflow.com/a/52214799
type: Question
linked to: http://stackoverflow.com/q/52267547
has comment: http://stackoverflow.com/comment/91373174
has comment: http://stackoverflow.com/comment/91482802
has body: I'm trying to create a JSON API compliant rest service using Django Rest Framework JSON API: https://django-rest-framework-json-api.readthedocs.io/en/stable/index.html I think I'm stuck at the Django Rest Framework level, but I am not certain. I think the GET request is working, but the POST is not because I get this response: $ curl -H 'Accept: application/vnd.api+json; indent=2' -X POST http://localhost:8000/greeters/ { "errors": [ { "detail": "Method \"POST\" not allowed.", "source": { "pointer": "/data" }, "status": "405" } ] } But the GET is fine: $ curl -H 'Accept: application/vnd.api+json; indent=2' http://localhost:8000/greeters/ { "data": {} } I've looked at other posts and the tutorials and it seems like I've missed something in my code that is not popping out at me. Hopefully, it will pop out at someone else who has more experience with Djang and Django Rest Framework. Thank you for your time :) Here's my code: my_project/urls.py from django.conf.urls import include from django.contrib import admin from django.urls import path, re_path urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^greeters/', include('greeter.urls')), ] greeter/urls.py from django.conf.urls import url, include from rest_framework import routers from .views import GreeterViewSet ROUTER = routers.DefaultRouter() ROUTER.register(r'^', GreeterViewSet) urlpatterns = [ url(r'^', include(ROUTER.urls)), ] greeter/views.py from rest_framework import viewsets from .models import Greeter from .serializers import GreeterSerializer class GreeterViewSet(viewsets.ModelViewSet): """API endpoints for Greeter""" queryset = Greeter.objects.all() serializer_class = GreeterSerializer # I've tried adding these methods in but none of it worked #def perform_create(self, serializer): # serializer.save(owner=self.request.user) #def create(self, request): # print('#########create') #def post(self, request): # print('#########post') greeter/serializers.py from rest_framework import serializers from .mo…

http://stackoverflow.com/q/52264469
has title: Determine number of records in tf.data.Dataset Tensorflow
has comment: http://stackoverflow.com/comment/91586906
downvote count: 0
tagged with: deep-learning
answer count: 1
linked to: http://stackoverflow.com/q/50737192
has answer: http://stackoverflow.com/a/52264626
favorite count: 0
duplicate of: http://stackoverflow.com/q/50737192
type: UnansweredQuestion
score: 6
tagged with: machine-learning
tagged with: python
upvote count: 6
has body: I would like to pass a dataset iterator into a function, but that function needs to know the length of the dataset. In the example below, I could pass len(datafiles) into my_custom_fn() function, but I'm wondering if I am able to extract the length of the data set from either iterator, batch_x, or batch_y classes so that I do not have to add it as an input. dataset = tf.data.FixedLengthRecordDataset(datafiles, record_bytes) iterator = dataset.make_initializable_iterator() sess.run(iterator.initializer) [batch_x, batch_y] = iterator.get_next() value = my_custom_fn(batch_x, batch_y) # lots of other stuff Thanks! Edit: This solution does not work in my case: tf.data.Dataset: how to get the dataset size (number of elements in a epoch)? After running tf.data.Dataset.list_files('{}/*.dat') tf.shape(tf.get_default_graph().get_tensor_by_name('MatchingFiles:0')[0]) returns &lt;tf.Tensor 'Shape_3:0' shape=(0,) dtype=int32&gt; I did find a solution that works for me. Add an iterator_scope to my code like: with tf.name_scope('iter'): dataset = tf.data.FixedLengthRecordDataset(datafiles, record_bytes) iterator = dataset.make_initializable_iterator() sess.run(iterator.initializer) [batch_x, batch_y] = iterator.get_next() value = my_custom_fn(batch_x, batch_y) # lots of other stuff Then from inside my_custom_fn call: def my_custom_fn(batch_x, batch_y): filenames = batch_x.graph.get_operation_by_name( 'iter/InputDataSet/filenames').outputs[0] n_epoch = sess.run(sess.graph.get_operation_by_name( 'iter/Iterator/count').outputs)[0] batch_size = sess.run(sess.graph.get_operation_by_name( 'iter/Iterator/batch_size').outputs)[0] # lots of other stuff Not sure if this is the best way, but it seems to work. Happy to take any advice on this, as it seem a little hacky.
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/91329682
type: QuestionComment
has text: Can you share the code used to create the publisher and publish the message?
score: 0
comment on: http://stackoverflow.com/q/52187418
type: Comment

http://stackoverflow.com/comment/91450410
type: AnswerComment
comment on: http://stackoverflow.com/a/52223174
type: Comment
has text: My version is `0.18.1.` Removed sort parameter and worked fine.
score: 1

http://stackoverflow.com/comment/91404503
comment on: http://stackoverflow.com/q/52227531
has text: Furthermore it looks to me that `image` in your code is just an `int` (for example `42`, so then `image['blog_image_path']` indeed makes no sense, you iterated over the keys.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91361340
has text: Did you try the solution here https://stackoverflow.com/questions/33404752/removing-emojis-from-a-string-in-python. I know they are removing it, but since you can find it then you can replace instead of just removing.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52205673

http://stackoverflow.com/comment/91186865
comment on: http://stackoverflow.com/a/52117368
has text: Thank you @blue_note. Is 'cert' referencing the return value of get_cert_data? Its not 100% clear to me
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52232754
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52231912
upvote count: 2
has body: When the condition that checks root.left and root.right is False, your isSymmetric function implicitly returns None. It should instead continue to check if one of root.left or root.right is not None, in which case it should return False; otherwise both root.left and root.right are None, and it should return True. Also, in the is_symmetric function, just because left.val == right.val it doesn't mean that the left subtree is symmetric to the right subtree, since there could be more children under them. It should simply return False when left.val != right.val: class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if root is None: return True if root.left and root.right: return self.is_symmetric(root.left,root.right) if root.left or root.right: return False return True def is_symmetric(self, left, right): if left is None and right is None: return True if right is None or left is None or left.val != right.val: return False return self.is_symmetric(left.left, right.right) and self.is_symmetric(left.right, right.left)
type: Answer

http://stackoverflow.com/q/52123816
type: Question
has comment: http://stackoverflow.com/comment/91202703
has comment: http://stackoverflow.com/comment/91202055
has body: I want to further bucket the output classes into fewer buckets in a classification problem. I have 4 output classes (i.e. 0, 1, 2, 3). But during training I also want to track the accuracy for 2 classes: treat 0 &amp; 1 as class 0 treat 2 &amp; 3 as class 1 For that I created a new metric and compiled it with the model: def new_classes_acc(y_true, y_pred): actual = tf.floor( y_true / 2 ) predicted = tf.floor( y_pred / 2 ) return K.categorical_crossentropy(actual, predicted) Compiled it like so: model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy', new_classes_acc]) I get nan as the accuracy value. What is the right way to do this?
upvote count: 2
answer count: 1
tagged with: keras
favorite count: 0
accepted answer: http://stackoverflow.com/a/52127761
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/52127761
type: AnsweredQuestion
score: 2
has title: custom keras metric returns nan
downvote count: 0
tagged with: loss-function
tagged with: tensorflow

http://stackoverflow.com/a/52156015
has body: Look at the matplotlib official doc : xlocs, xlabs = plt.xticks() put in xlocs your range, and in xlabs what you want to display. then: plt.xticks(xlocs, xlabs)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52155939

http://stackoverflow.com/a/52169901
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52169733
downvote count: 0
has body: You can calculate idxmin and then use np.in1d with pd.DataFrame.loc: idx = df.loc[df['ID'].isin([3,5]), 'Value'].idxmin() res = df.loc[~np.in1d(df.index, idx)] print(res) ID Value 0 1 100 1 2 250 3 4 400 4 5 600 5 7 800
type: Answer

http://stackoverflow.com/comment/91415802
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52232068
has text: Possible duplicate of [Read image grayscale opencv 3.0.0-dev](https://stackoverflow.com/questions/23339315/read-image-grayscale-opencv-3-0-0-dev)
score: 0

http://stackoverflow.com/comment/91313251
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52180216
has text: Could you please show the details of error and what are the django app installed. Which will be easy to reproduce

http://stackoverflow.com/a/52279727
type: Answer
answers question: http://stackoverflow.com/q/52268328
has comment: http://stackoverflow.com/comment/91598556
score: 0
has body: We had run into this exact problem and we then had to implement the data access functions into AWS Lambda Java 8 instead of Python 3.6 In Java 8, ojdbc*.jar (* --> version number of Oracle driver) can be simply bundled into the final zip and there are no other steps like trying to get Oracle Client Native Libraries. We did spend good amount of time to make AWS Lambda Python Function access Oracle DB, but I felt developing such modules in AWS Lambda Java 8 function is much simpler.

http://stackoverflow.com/a/54338391
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/95519425
answers question: http://stackoverflow.com/q/52133838
has comment: http://stackoverflow.com/comment/95494083
has comment: http://stackoverflow.com/comment/95497257
has body: You can use the answer here with Numpy 1.8 and up. I spent more time on this than I wanted, because the other answers treated the whole multidimensional array as a single search where top_k only looks at the last dimension. There's more information here, where the partition is used to specifically sort a given axis. To summarize, based upon the tensorflow signature (without name): def top_k(input, k=1, sorted=True): """Top k max pooling Args: input(ndarray): convolutional feature in heigh x width x channel format k(int): if k==1, it is equal to normal max pooling sorted(bool): whether to return the array sorted by channel value Returns: ndarray: k x (height x width) ndarray: k """ ind = np.argpartition(input, -k)[..., -k:] def get_entries(input, ind, sorted): if len(ind.shape) == 1: if sorted: ind = ind[np.argsort(-input[ind])] return input[ind], ind output, ind = zip(*[get_entries(inp, id, sorted) for inp, id in zip(input, ind)]) return np.array(output), np.array(ind) return get_entries(input, ind, sorted) Keep in mind, for your answer, you tested with arr = np.random.rand(3, 3, 3) arr1, ind1 = top_k(arr) arr2 = np.max(arr, axis=(0,1)) arr3, ind3 = tf.nn.top_k(arr) print(arr1) print(arr2) print(arr3.numpy()) but arr2.shape is (3,) and arr3.numpy().shape is (3, 3, 1). If you really want tf.nn.top_k like functionality, you should use np.array_equal(arr3, np.max(arr, axis=-1, keepdims=True)) as the test. I ran this with tf.enable_eager_execution() executed, hence the .numpy() instead of .eval().
downvote count: 0

http://stackoverflow.com/comment/91345278
comment on: http://stackoverflow.com/q/52197883
score: 0
type: QuestionComment
has text: @boandriy I know that it work on that way. But my problem here is that if I just want to be able to write an argument like video, output in the ffpeg script
type: Comment

http://stackoverflow.com/q/52118110
accepted answer: http://stackoverflow.com/a/52118150
duplicate of: http://stackoverflow.com/q/31726643
tagged with: plot
has comment: http://stackoverflow.com/comment/91187205
has comment: http://stackoverflow.com/comment/91187422
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91187377
type: AnsweredQuestion
answer count: 1
score: 1
has comment: http://stackoverflow.com/comment/91187233
favorite count: 0
has title: How to save multiple figures, not subplots, produced in a for loop as one figure?
type: Question
has comment: http://stackoverflow.com/comment/91187480
tagged with: python
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/52118150
has comment: http://stackoverflow.com/comment/91193190
tagged with: python-3.x
linked to: http://stackoverflow.com/q/31726643
upvote count: 3
downvote count: 2
has body: In Jupyter Notebook, I write the following code, as MCVE: import matplotlib.pyplot as plt import numpy as np x1 = np.linspace(-1, 1, 50) for x in range(4): plt.figure() plt.plot(x1) plt.savefig(str(x)+".png") # save figures separately It produces 4 plots, as expected. They are below each other in a row. I want to have a single saved output, containing all 4 plots. I don't mind if Jupyter Notebook does not show the plots as long as they are saved. My attempt: save the figures separately, as 0.png, 1.png, 2.png, 3.png, then merge them vertically. I hope there is an easier way to do this. How can I have a single saved output? EDIT: As suggested, I could do subplots, like this: fig,axes = plt.subplots(nrows=4) fig.set_size_inches(8,12) x1 = np.linspace(-1, 1, 50) for ax in axes: ax.plot(x1) plt.savefig("save_fig.png") I want to have many figures, not one fiugre with many subplots. How can I save the multiple figures without using subplots?

http://stackoverflow.com/comment/91236656
score: 2
comment on: http://stackoverflow.com/q/52143318
type: QuestionComment
has text: `a or b or c in x` does not test whether any of `a,b,c` are present in `x`: `(1 or 2 or 3 in {4}) == 1`.
type: Comment

pyspark
tags question: http://stackoverflow.com/q/52167460
tags question: http://stackoverflow.com/q/52200666
tags question: http://stackoverflow.com/q/52212709
tags question: http://stackoverflow.com/q/52200155
tags question: http://stackoverflow.com/q/52229581
tags question: http://stackoverflow.com/q/52177082
tags question: http://stackoverflow.com/q/52137351
tags question: http://stackoverflow.com/q/52162833
tags question: http://stackoverflow.com/q/52206946
tags question: http://stackoverflow.com/q/52246213
tags question: http://stackoverflow.com/q/52179685
tags question: http://stackoverflow.com/q/52235219
tags question: http://stackoverflow.com/q/52129269
tags question: http://stackoverflow.com/q/52234302
type: Tag
tags question: http://stackoverflow.com/q/52139266
tags question: http://stackoverflow.com/q/52121283
tags question: http://stackoverflow.com/q/52260568
tags question: http://stackoverflow.com/q/52157239
tags question: http://stackoverflow.com/q/52173037
tags question: http://stackoverflow.com/q/52196043
tags question: http://stackoverflow.com/q/52122857
tags question: http://stackoverflow.com/q/52178406
tags question: http://stackoverflow.com/q/52140278
tags question: http://stackoverflow.com/q/52232613
tags question: http://stackoverflow.com/q/52243200
tags question: http://stackoverflow.com/q/52238803
tags question: http://stackoverflow.com/q/52229323
tags question: http://stackoverflow.com/q/52191056
tags question: http://stackoverflow.com/q/52155170
tags question: http://stackoverflow.com/q/52147358
tags question: http://stackoverflow.com/q/52189704
tags question: http://stackoverflow.com/q/52246980
tags question: http://stackoverflow.com/q/52210211
tags question: http://stackoverflow.com/q/52124731
tags question: http://stackoverflow.com/q/52246451
tags question: http://stackoverflow.com/q/52219949
tags question: http://stackoverflow.com/q/52150705
tags question: http://stackoverflow.com/q/52136804
tags question: http://stackoverflow.com/q/52196261
tags question: http://stackoverflow.com/q/52122942
tags question: http://stackoverflow.com/q/52224651
tags question: http://stackoverflow.com/q/52241423
tag name: pyspark
tags question: http://stackoverflow.com/q/52160596

data-science
tags question: http://stackoverflow.com/q/52173203
tags question: http://stackoverflow.com/q/52132331
type: Tag
tags question: http://stackoverflow.com/q/52118454
tags question: http://stackoverflow.com/q/52217601
tags question: http://stackoverflow.com/q/52244867
tags question: http://stackoverflow.com/q/52189532
tags question: http://stackoverflow.com/q/52173968
tags question: http://stackoverflow.com/q/52128445
tags question: http://stackoverflow.com/q/52172448
tags question: http://stackoverflow.com/q/52136520
tags question: http://stackoverflow.com/q/52253787
tag name: data-science
tags question: http://stackoverflow.com/q/52188561

http://stackoverflow.com/comment/91226864
has text: Are you ***sure*** you're not using python 2?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52138539

http://stackoverflow.com/q/52247440
tagged with: opencv
score: 3
answer count: 0
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/91443042
tagged with: arrays
has comment: http://stackoverflow.com/comment/91449850
has body: I'm trying to do background subtraction using OpenCV trying to subtract two images from each other. One of the images is the background image and is fed to the program statically while the second image is taken from the webcam connected to the Raspberry Pi (the same webcam is used to capture the background image and both images have the same resolution). However I get the error: error: /build/opencv-VF5Hiu/opencv-2.4.9.1+dfsg/modules/core/src/arithm.cpp:1287: error: (-209) The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array' in function arithm_op my code is the following: import cv2 Original2 = cv2.imread("Original.png") Original2 = cv2.resize(Original2, (960, 720)) cap = cv2.VideoCapture(0) cap.set(3, 960) cap.set(4, 720) ret,tespi=cap.read() cap.release() cv2.imwrite('tespi.png',tespi) Edited2= cv2.imread('tespi.png') diffadd = cv2.subtract(Edited2, Original2) diffsub = cv2.subtract(Original2, Edited2) I tried resizing both pictures before subtracting them, tried enforcing the desired resolution, almost tried anything I could think of which is not that so many things since I'm just starting to learn programming in python. Can you please help me fix this issue ?
has comment: http://stackoverflow.com/comment/91490420
has comment: http://stackoverflow.com/comment/91493636
downvote count: 0
has title: Error (-209) The operation is neither 'array op array' --- How to resolve this issue?
favorite count: 0
has comment: http://stackoverflow.com/comment/91443928
type: UnansweredQuestion
tagged with: background-subtraction
has comment: http://stackoverflow.com/comment/91490559
tagged with: python

http://stackoverflow.com/a/52147010
upvote count: 2
type: Answer
score: 2
has body: s='17.17165756225586 -28.102264404296875,17.184370040893555 -28.200496673583984,17.1986083984375 -28.223613739013672,17.17165756225586 -28.102264404296875, 28.865726470947266 -28.761619567871094,28.80694007873535 -28.75750160217285,28.792499542236328 -28.706947326660156, 28.865726470947266 -28.761619567871094' #convert the input in a list of points coordinates = [tuple(map(float,el.split())) for el in s.split(",")] polygons = [] #find the polygons while coordinates: ind = coordinates[1:].index(coordinates[0]) polygons.append(coordinates[0:ind+2]) coordinates = coordinates[ind+2:] #output [(17.17165756225586, -28.102264404296875), (17.184370040893555, -28.200496673583984), (17.1986083984375, -28.223613739013672), (17.17165756225586, -28.102264404296875)] [(28.865726470947266, -28.761619567871094), (28.80694007873535, -28.75750160217285), (28.792499542236328, -28.706947326660156), (28.865726470947266, -28.761619567871094)]
downvote count: 0
answers question: http://stackoverflow.com/q/52146661

http://stackoverflow.com/comment/91340879
has text: @kevinkayaks I believe you are right. I did the following: `print(image_table['image'][:10]) #returns the first 10 arrays of images print(image_table['image'][:10].shape)) # (10,) print(type(image_table['image'][0])) #class 'numpy.ndarray' print(image_table['image'][0].shape) #184,184,1 ` Would you happen to know how I could fix this?
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52130755

http://stackoverflow.com/comment/91443163
comment on: http://stackoverflow.com/q/52247573
score: 1
has text: You never return anything in your `__enter__` method, so it implicitly returns `None`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91445147
type: Comment
comment on: http://stackoverflow.com/a/52233884
has text: Fyi - `xlwt` and `xlsxwriter` have methods `add_sheet` and `add_worksheet` respectively. Anyways, happy to help!
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91445788
comment on: http://stackoverflow.com/q/52240381
has text: I do not think this is a duplicate. 1) that’s an older version of Django. 2) that is pertaining to their app, not the admin one. How can a user affect the admin one?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52189815
upvote count: 1
score: 1
has body: You can add: # noinspection PyUnresolvedReferences on the line above the line you want the unresolved reference inspection to be disabled. It will not disable it anywhere else (from what I can see in my Pycharm 2018.2)
downvote count: 0
answers question: http://stackoverflow.com/q/52167595
type: Answer

http://stackoverflow.com/q/52229521
favorite count: 0
has answer: http://stackoverflow.com/a/52229565
tagged with: python
has title: Why is `dataclasses.asdict(obj)` > 10x slower than `obj.__dict__()`
has body: I am using Python 3.6 and the dataclasses backport package from ericvsmith. It seems that calling dataclasses.asdict(my_dataclass) is ~10x slower than calling my_dataclass.__dict__: In [172]: @dataclass ...: class MyDataClass: ...: a: int ...: b: int ...: c: str ...: In [173]: %%time ...: _ = [MyDataClass(1, 2, "A" * 1000).__dict__ for _ in range(1_000_000)] ...: CPU times: user 631 ms, sys: 249 ms, total: 880 ms Wall time: 880 ms In [175]: %%time ...: _ = [dataclasses.asdict(MyDataClass(1, 2, "A" * 1000)) for _ in range(1_000_000)] ...: CPU times: user 11.3 s, sys: 328 ms, total: 11.6 s Wall time: 11.7 s Is this expected behavior? In what cases should I have to use dataclasses.asdict(obj) instead of obj.__dict__? Edit: Using __dict__.copy() does not make a big difference: In [176]: %%time ...: _ = [MyDataClass(1, 2, "A" * 1000).__dict__.copy() for _ in range(1_000_000)] ...: CPU times: user 922 ms, sys: 48 ms, total: 970 ms Wall time: 970 ms
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52229565
type: Question
possible better answer: http://stackoverflow.com/a/78430135
has answer: http://stackoverflow.com/a/78430135
score: 63
answer count: 2
has comment: http://stackoverflow.com/comment/91408767
upvote count: 63
downvote count: 0
tagged with: python-dataclasses

http://stackoverflow.com/q/52227797
has comment: http://stackoverflow.com/comment/91405637
has comment: http://stackoverflow.com/comment/91405167
has answer: http://stackoverflow.com/a/52228122
has comment: http://stackoverflow.com/comment/91405532
type: UnansweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/91405270
type: Question
tagged with: python
answer count: 1
has title: How to Increase Axis: Pandas: ValueError: Length mismatch: Expected axis has 1 elements, new values have 30 elements
has body: How do I increase my axis to have 30 elements? I am facing this error ValueError: Length mismatch: Expected axis has 1 elements, new values have 30 elements Listed below is my code import pandas as pd df = pd.DataFrame() for chunk in pd.read_csv('verybig.csv', sep='|', header=None, chunksize=1000, low_memory=False): df = pd.concat([df, chunk], ignore_index=True) df.columns = ['MyTime','Attribute','Court','Energy','State','30','29','28','27','26','25','24','23','22','21','20','19','18','17','16','15','14','13','12','11','10','9','8','7','6'] I would like to note that verybig.csv is around 1GB UPDATE: After executing df.head(5) I see the following &gt;&gt;&gt; df.head(5) 0 0 2018-09-01 00:00:03,262, aid:Ut7XsnHXaqf6p4Pyc... 1 2018-09-01 00:00:16,966, aid:kzhUOAJRHxfgwKdmy... 2 2018-09-01 00:00:19,008, aid:QeKRGSs4QRP-f8dIZ... 3 2018-09-01 00:00:19,202, aid:ScGESqQOEY6YkrGoY... 4 2018-09-01 00:00:24,799, aid:Hajk1NF0tIIVELz2N... &gt;&gt;&gt; UPDATE 2: I think the path way to my solution is to split the above column (Column 0) using the comma as the separator after the following code is executed import pandas as pd df = pd.DataFrame() for chunk in pd.read_csv('verybig.csv', sep='|', header=None, chunksize=1000, low_memory=False): df = pd.concat([df, chunk], ignore_index=True)
score: 0

http://stackoverflow.com/comment/91438279
type: Comment
has text: if the answer helped you solve your problem, you can vote it up or accept it as the "right" answer :-)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52244818

http://stackoverflow.com/q/52249092
tagged with: tkinter
has comment: http://stackoverflow.com/comment/91446690
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52249373
score: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52249373
type: Question
has title: How to set variable in Tkinter OptionMenu?
has comment: http://stackoverflow.com/comment/91446858
has comment: http://stackoverflow.com/comment/91446846
has body: So my question is why the Tkinter OptionMenu is not setting to 4.5 as a default? Do I just have to put 4.5 at the beginning of the avgdisc_thresh list or am I doing something wrong? avgdisc_thresh = [3.5, 4, 4.5, 5, 5.5, 6] avgdisc_var = tk.StringVar() avgdisc_var.set("4.5") loss_option = ttk.OptionMenu( loss_top_win, avgdisc_var, *avgdisc_thresh) loss_option.grid( row=0, column=0) Thanks!
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/91432908
has text: Copying the entire structure to a new object is unnecessary if you just need to `print` it. Just `print(sorted(d, key=...))`
comment on: http://stackoverflow.com/a/52242145
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/q/52135459
has comment: http://stackoverflow.com/comment/124520438
has answer: http://stackoverflow.com/a/57128210
has answer: http://stackoverflow.com/a/52135531
has comment: http://stackoverflow.com/comment/91232824
has answer: http://stackoverflow.com/a/75896409
has answer: http://stackoverflow.com/a/62864575
type: Question
has answer: http://stackoverflow.com/a/62641834
score: 10
has answer: http://stackoverflow.com/a/76001030
answer count: 6
has body: I am reading in a CSV file as a DataFrame while defining each column's data type. This code gives an error if the CSV file has a blank row in it. How do I read the CSV without blank rows? dtype = {'material_id': object, 'location_id' : object, 'time_period_id' : int, 'demand' : int, 'sales_branch' : object, 'demand_type' : object } df = pd.read_csv('./demand.csv', dtype = dtype) I thought of one workaround of doing something like this but not sure if this is the efficient way: df=pd.read_csv('demand.csv') df=df.dropna() and then redefining the column data types in the df. Edit : Code - import pandas as pd dtype1 = {'material_id': object, 'location_id' : object, 'time_period_id' : int, 'demand' : int, 'sales_branch' : object, 'demand_type' : object } df = pd.read_csv('./demand.csv', dtype = dtype1) df Error - ValueError: Integer column has NA values in column 2 My CSV file's snapshot -
upvote count: 10
tagged with: blank-line
has comment: http://stackoverflow.com/comment/91240599
tagged with: pandas
has comment: http://stackoverflow.com/comment/91233302
downvote count: 0
has comment: http://stackoverflow.com/comment/91240717
favorite count: 0
has comment: http://stackoverflow.com/comment/91240658
has comment: http://stackoverflow.com/comment/91240449
has title: pandas read_csv remove blank rows
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python

http://stackoverflow.com/comment/91433158
type: Comment
type: AnswerComment
has text: Unfortunately, I am not the author of the exe. I agree with your recommendation, however. The exe handles some sensitive hardware and requires quite a bit of domain knowledge in order to rewrite. As such, I am stuck with the executable. What tutorial would you recommend for IPC (maybe using sockets) that would work in Python + Windows?
comment on: http://stackoverflow.com/a/52242187
score: 0

http://stackoverflow.com/comment/91349305
score: 0
comment on: http://stackoverflow.com/q/52200155
type: Comment
type: QuestionComment
has text: You cannot make assignments inside of lists.

http://stackoverflow.com/comment/91397958
comment on: http://stackoverflow.com/q/52221931
type: Comment
type: QuestionComment
has text: added the csv file link.
score: 0

http://stackoverflow.com/comment/91201596
has text: @VibeeshanRC Awesome! This is actually what I needed! I really appreciate you making the code very understandable, still new to C#. This will help me with other concepts as well. Thanks!
comment on: http://stackoverflow.com/a/52125292
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91477458
has text: you're right, my mistake - the values of the "duplicate" rows would still need to be aggregated (duplicate was definitely not the right choice of word). Does that mean i just need to do a .groupby(...).sum()?
type: Comment
comment on: http://stackoverflow.com/a/52262819
score: 0
type: AnswerComment

http://stackoverflow.com/q/52256451
tagged with: python
type: UnansweredQuestion
type: Question
tagged with: nltk
has answer: http://stackoverflow.com/a/52256672
tagged with: selector
score: 0
has comment: http://stackoverflow.com/comment/91460200
has title: when I “import nltk” show selectSelector error
answer count: 1
has comment: http://stackoverflow.com/comment/91499656
has body: &gt;&gt;&gt; import nltk Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/hexialong/anaconda3/lib/python3.6/site-packages/nltk/__init__.py", line 89, in &lt;module&gt; from nltk.internals import config_java File "/Users/hexialong/anaconda3/lib/python3.6/site-packages/nltk/internals.py", line 11, in &lt;module&gt; import subprocess File "/Users/hexialong/anaconda3/lib/python3.6/subprocess.py", line 138, in &lt;module&gt; import selectors File "/Users/hexialong/anaconda3/lib/python3.6/selectors.py", line 290, in &lt;module&gt; class SelectSelector(_BaseSelectorImpl): File "/Users/hexialong/anaconda3/lib/python3.6/selectors.py", line 317, in SelectSelector _select = select.select AttributeError: module 'select' has no attribute 'select' My environment is MacOS and python version is 3.6

http://stackoverflow.com/comment/91283180
type: QuestionComment
comment on: http://stackoverflow.com/q/52166750
score: 0
has text: because this is a dictionary - it stores only distinct key names. and you always assign the new value of i to the same key - thus all entries have a the same value.
type: Comment

http://stackoverflow.com/comment/91247906
comment on: http://stackoverflow.com/a/52129958
type: Comment
has text: managed = False is exactly what I needed, thanks? can you suggest a better way to phrase my question other than "without ORM"?
score: 0
type: AnswerComment

http://stackoverflow.com/a/52206274
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52206011
answers question: http://stackoverflow.com/q/52206011
has body: You are formatting the last section of your string: "%'".format(tablepx) before concatenating that to the result of "..." + str(cadena). So the {0} placeholder in the first string literal is not filled and you are left with "SELECT * FROM {0} WHERE rut LIKE '%...%'" as the query (with ... replaced by the value of cadena). You could fix that by moving the .format() call to the "SELECT * FROM {0} WHERE rut LIKE '%" string literal instead. Or by using a second placeholder {1} to show where the cadeda value should go, instead of using + concatenations. However, you should not be using string concatenation to put cadena into the string in the first place. You had the right idea, by using the ? placeholder and a query parameter value, but you forgot to add the % LIKE query characters to your cadena value. Simply add % characters to the start and end of cadena, then use the result of that as your parameter: like_string = '%{0}%'.format(cadena) consulta.execute( "SELECT * FROM {0} WHERE rut LIKE ?".format(tablepx), (like_string,)) The ? placeholder in the query string will be used to place a properly escaped LIKE query string, with % added to the start and end of the cadena value. I can't stress enough that using str.format() to interpolate a table name into a query string (as you do with tablepx) can open you up to SQL injection issues. See this other answer of mine for more advice on this, as well as alternatives. To be safe, I'd at least use "{0}" as the table name position and tablepx.replace('"', '""'), so that SQLite at least knows to only accept valid object names in that part of the string: like_string = '%{0}%'.format(cadena) consulta.execute( 'SELECT * FROM "{0}" WHERE rut LIKE ?'.format(tablepx.replace('"', '""')), (like_string,))
has comment: http://stackoverflow.com/comment/91387653
type: Answer
has comment: http://stackoverflow.com/comment/91362172
has comment: http://stackoverflow.com/comment/91366048
has comment: http://stackoverflow.com/comment/91362067
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/91253284
has text: I am having no problem importing them.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52151421

http://stackoverflow.com/comment/91299846
has text: @ottomeister oh apologies on the indentations not being accurate I was dead when I was posting this, ill edit it
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52165209

http://stackoverflow.com/comment/91338173
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52194205
score: 0
has text: "I cant change Python version on the server because others are using it & may break their code." - you can have your own Python 3 without messing with other users' Python 2.

http://stackoverflow.com/a/52277979
has comment: http://stackoverflow.com/comment/91510414
answers question: http://stackoverflow.com/q/52269397
score: 0
has body: Solution In revision to your comments, considering that this is only being applied to the example above and need only to alter those specific three lines, this will accomplish the task (included if location: in case you don't match keyword it won't erase your file by open('w') def change_text(new_text): content[1] = list(content[1]) y = list(new_text) content[1] = content[1][:6] + y + content[1][-2:] content[1] = ''.join(content[1]) def change_source_l(new_source_l): content[2] = list(content[2]) y = list(new_source_l) content[2] = content[2][:17] + y + content[2][-2:] content[2] = ''.join(content[2]) def change_target_l(new_target_l): content[3] = list(content[3]) y = list(new_target_l) content[3] = content[3][:17] + y + content[3][-2:] content[3] = ''.join(content[3]) filename = open('query.txt', 'r') content = filename.read() content = content.split() filename.close() name = open('query.txt', 'w') change_text('something') change_source_l('this') change_target_l('that') name.write('\n'.join(content)) name.close() Output (xenial)vash@localhost:~/python/LPTHW$ cat query.txt query{ text:"something", source_language:"this", target_language:"that", }, data_type:[16], params{ client:"xyz"
has comment: http://stackoverflow.com/comment/91510507
type: Answer
has comment: http://stackoverflow.com/comment/91510359
has comment: http://stackoverflow.com/comment/91519906
has comment: http://stackoverflow.com/comment/91551162
has comment: http://stackoverflow.com/comment/91519078

http://stackoverflow.com/comment/91221337
type: QuestionComment
comment on: http://stackoverflow.com/q/52135497
has text: Why not create a prepare stept that opens the xlsx, checks `if not A1 == 'ANR':` and if so: insert a cell as `A1` with content `'ANR'` that pushes all other cells 1 down. Now you got the same format for both files and can do the rest without hassle?
score: 0
type: Comment

http://stackoverflow.com/a/52212422
has body: I'm not aware of any simple way to do this directly. Matplotlib can do things like drop shadows but that won't give you blur. However, matplotlib's Agg renderer has support for custom filters. You can see examples here. Specifically, you might be able to do something with the GaussianFilter example. Here I think it's being used to generate the blurred drop shadows but you could figure out how to get it to do what you want in your case. Note that what you are doing in these cases is manually defining a process_image() which works directly on image data. You may also want to look at this question regarding plotting blurred points.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52212326
has comment: http://stackoverflow.com/comment/91401104
downvote count: 0
score: 1

http://stackoverflow.com/comment/91282859
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52165774
has text: I am using Linux, python 2.7 on virtual Environment, i try to do flask-web application to connect mysql databases,
score: 0

http://stackoverflow.com/a/52177048
has body: My solution for this issue was to add the dependency to my Pipfile and then re-generate Pipfile.lock. This was necessary despite requirements.txt already having the dependency listed.
type: Answer
answers question: http://stackoverflow.com/q/52155023
score: 0
has comment: http://stackoverflow.com/comment/91316428

http://stackoverflow.com/comment/91294027
score: 0
has text: Yeah I have, everything’s between 0 and 1. However I don’t think that’s the issue here, the problem is out of 2002 columns passed in per time step, 2000 of them are from the text
comment on: http://stackoverflow.com/q/52170404
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52174607
has comment: http://stackoverflow.com/comment/91331130
has body: Have you indented correctly ? I have runned your code on my machine (Windows 8.1) with proper indentation and it worked fine. Indented code: import matplotlib.pyplot as plt from sklearn import datasets from sklearn import svm import numpy digits=datasets.load_digits() ''' print(digits.data) print(digits.target) print(digits.images[0]) ''' clf=svm.SVC(gamma=0.001, C=1.0) print(len(digits.data)) x,y = digits.data[:-1],digits.target[:-1] clf.fit(x,y) print('prediction:',clf.predict([digits.data[-1]])) plt.imshow(digits.images[-1], cmap=plt.cm.gray_r, interpolation="nearest") plt.show() Furthermore, if it doesn't work, then try changing the kernel/interpreter. Try Python 3.6.x kernel/interpreter. p.s: I have used Python 3.6.0 on Thonny IDE to run test this code and it worked fine on my machine.
score: 0
answers question: http://stackoverflow.com/q/52171610
has comment: http://stackoverflow.com/comment/91350695
type: Answer
has comment: http://stackoverflow.com/comment/91350773
accepted answer of: http://stackoverflow.com/q/52171610
has comment: http://stackoverflow.com/comment/91362873
has comment: http://stackoverflow.com/comment/91362219
has comment: http://stackoverflow.com/comment/91355584
has comment: http://stackoverflow.com/comment/91350787
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91362234

http://stackoverflow.com/a/52210857
type: Answer
downvote count: 0
score: 5
accepted answer of: http://stackoverflow.com/q/52210355
has body: The only way you can access an instance variable is as an attribute of self. When you just refer to var, that's never an instance variable; it's always a local, enclosing, global, or builtin variable. In your method definition: def lookup(self, var=var): print(var) … you have a parameter named var. Parameters are local variables. The print(var) inside the body prints that local variable. What about this? def lookup(self, var=var): var = var Again, var is a local variable—a parameter. So, you're just assigning the current value of that local variable to the same variable. Which has no useful effect, but of course it's perfectly legal. Where does the parameter's value come from? At function call time, if you pass an argument, that argument gets bound to the parameter; if you don't, it gets filled in with the default value. OK, so where does the default value come from? At function definition time (when the def statement is executed), var is looked up in the current scope—that is, the body of the class definition—and its value is stored as a default in the function object (it should be visible as foo.lookup.__defaults__[0]). So, the default value is "value goes here". Notice that it's not a closure capture or other reference to the class attribute. When the class statement is executed, it uses that same class body namespace to build the class's attributes, so you end up with foo.var as another name for the same value that's in foo.lookup.__defaults__[0]. But they're completely independent names for that value; you can reassign foo.var = 3, and the default value for lookup's parameter will still be "value goes here". So, to answer your specific questions: Will it store it in the class variable, the instance variable, or a new variable with the same name? None of the above. It stores it in a local variable that already exists, because it's a parameter. Will it get the class variable, instance variable, or the method's variable? If by "the method's variable" you mean the …
answers question: http://stackoverflow.com/q/52210355
type: AcceptedAnswer
upvote count: 5

http://stackoverflow.com/q/52248068
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91444012
favorite count: 0
possible better answer: http://stackoverflow.com/a/52248115
has body: I have a dictionary with multiple values follows: dict_a = {1: {'a':1, 'b':2, 'c':3}, 2:{'a': 4, 'b':5, c:'6'}} . I want the result as such: [('a',(1,4)),('b',(2,5)), ('c',(3,6))] I wrote a code: for keys, values in dict_a: for k, v in values: print(v) But the result comes like ('a',1),('b',2).... I am little stuck here. Can anyone help me on this please!!!
upvote count: 2
has comment: http://stackoverflow.com/comment/91443966
has answer: http://stackoverflow.com/a/52248115
has comment: http://stackoverflow.com/comment/91443960
type: AnsweredQuestion
score: 2
tagged with: list
has answer: http://stackoverflow.com/a/52248123
has comment: http://stackoverflow.com/comment/91443943
has comment: http://stackoverflow.com/comment/91443973
tagged with: list-comprehension
type: Question
answer count: 2
downvote count: 0
has title: Dictionary with multiple values to tuple
accepted answer: http://stackoverflow.com/a/52248123
tagged with: tuples
tagged with: python

http://stackoverflow.com/comment/91642958
has text: will do that now.
comment on: http://stackoverflow.com/a/52267460
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52267018
has comment: http://stackoverflow.com/comment/91482119
has comment: http://stackoverflow.com/comment/91482375
has comment: http://stackoverflow.com/comment/91482123
has comment: http://stackoverflow.com/comment/91482610
type: Answer
accepted answer of: http://stackoverflow.com/q/52267008
has comment: http://stackoverflow.com/comment/91482087
has comment: http://stackoverflow.com/comment/91481902
has comment: http://stackoverflow.com/comment/91481915
upvote count: 4
has comment: http://stackoverflow.com/comment/91482430
has comment: http://stackoverflow.com/comment/91482322
has body: Accumulate with a defaultdict: &gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; data = defaultdict(int) &gt;&gt;&gt; L = [[0.5, 2], [0.5, 5], [2, 3], [2, 6], [2, 0.6], [7, 1]] &gt;&gt;&gt; for k, v in L: ... data[k] += v ... &gt;&gt;&gt; [[k,v] for (k,v) in data.items()] [[0.5, 7], [2, 9.6], [7, 1]] Note that the value for 2 was automatically "promoted" to a float by addition, even though this is a defaultdict of int. This is to match the desired output posted in the question, but I think you should consider to use homogeneous output types rather than a mix of int and float.
has comment: http://stackoverflow.com/comment/91482390
answers question: http://stackoverflow.com/q/52267008
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/91482301
type: AcceptedAnswer

http://stackoverflow.com/q/52178795
tagged with: jinja2
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91311828
has comment: http://stackoverflow.com/comment/91310178
score: 0
answer count: 1
tagged with: textbox
has answer: http://stackoverflow.com/a/52181202
tagged with: python
has body: I created a small program to get user entered text and save the text in a html file. Here is my example small program. from tkinter import * from jinja2 import Template root=Tk() textBox=Text(root, height=2, width=10) textBox.pack() buttonSave=Button(root, height=1, width=10, text="Save", command=lambda: createCaseDetails()) buttonSave.pack() def createCaseDetails(): # Create The template html for case report t = Template(""" &lt;!DOCTYPE html&gt; &lt;html lang="en" &gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Case Report&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;&lt;span class="blue"&gt;&amp;lt;&lt;/span&gt;Evidence&lt;span class="blue"&gt;&amp;gt;&lt;/span&gt; &lt;span class="yellow"&gt;System Information&lt;/pan&gt;&lt;/h1&gt; &lt;h2&gt;Created with love by bluebear119 &lt;/h2&gt; &lt;h3&gt;Case Description&lt;/h3&gt; &lt;p&gt;{{Case_Description}&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; """) f = open('Case Report.html', 'w') inputvalue = textBox.get("1.0", "end-1c") print(inputvalue) message = t.render(Case_Description=inputvalue) f.write(message) f.close() print("Case Report.html file saved.") mainloop() But when I implement this in my huge code, I cannot use the variable since is from same class but in another function's variable. I defined the createCaseDetails() function at top-level,but my text box is in another function, button is in another function as well. How can I press the button and save the Case description text in html. The textbox and button will define in a same class like this: Class CreateCaseInterface(Frame): def caseInformation(self): ... Case_Description_text=Text(self.caseInfoFrame,width=30,height=11,yscrollcommand=CaseDescripyscrollbar.set) Case_Description_text.grid(row =4, column =1,pady=5) def UACaseManagement(self): Executebtn = Button(self.UACaseManagementFrame, text="Execute for create and save the case file", command=createCaseDetails(self),width=30,height=5) Executebtn.grid(row=12,column= 4,sticky=W,pady=5,colu…
has title: Tkinter : Use Button Click command get text box value and save in html
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/52181202

http://stackoverflow.com/q/52196481
tagged with: python
has answer: http://stackoverflow.com/a/52196562
upvote count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52196512
downvote count: 2
score: 1
tagged with: slice
type: Question
answer count: 2
has body: The slice syntax is a handy way to refer to sub-parts of sequences – typically strings and lists. The slice s[start:end] is the elements beginning at start and extending up to but not including end. E.g letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] print(letters[2:5]) This will give Output : ['c', 'd', 'e'] But how does extended slicing work. print(letters[2:4:5]) The above print statement will give ['c'] as output. I can't understand how?
linked to: http://stackoverflow.com/q/509211
favorite count: 0
duplicate of: http://stackoverflow.com/q/509211
has title: How does extended slicing in python works?

http://stackoverflow.com/q/52209653
has body: I've been trying to plot parts of a pandas dataframe using the Matplotlib Step-function. However I'm unable to colorize individual datapoints or "steps" based on other categories that are part that instance. Precisely I want to create a merit-order graph that plots operating costs over capacity as a single step chart. New Code df = pd.read_csv("merit_v1.csv") df = df[df.energy_source != "Hydro"] df = df.sort_values(by="margC",ascending=True) df["capacity"] = round(df["capacity"].cumsum() / 1000, 3) y = df["margC"].tolist() x = df["capacity"].tolist() x_app = x[1:] y_app = y[:len(y)-1] x = x + x_app + [0] y = y + y_app + [y[0]] x = sorted(x) y = sorted(y) colors = [] energy = df["energy_source"].tolist() for item in energy: if item == "Nuclear": color = "#DDF45B" if item == "Coal": color = "#141115" if item == "Lignite": color = "#8D6346" if item == "Bioenergy": color = "#5A720F" if item == "Natural Gas": color = "#4C2B36" if item == "Oil": color = "#C1A5A9" colors.append(color) colors = list(np.repeat(colors, 2)) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) fig, ax = plt.subplots() lc = LineCollection(segments, color = colors) lc.set_linewidth(2) line = ax.add_collection(lc) ax.set_xlim(-5, max(x) + 5) ax.set_ylim(0, max(y) + 5) ax.fill_between(x,y, facecolor="w") ax.set_title("Merit-Order des europäischen Kraftwerkparks") ax.set_xlabel('Kummulierte Leistung GW') ax.set_ylabel('Grenzkosten €/MWh') plt.show()
type: Question
has comment: http://stackoverflow.com/comment/91372103
tagged with: charts
tagged with: matplotlib
has title: Python/Pandas Using different colors for data points in a step function
has comment: http://stackoverflow.com/comment/91389021
tagged with: pandas
has comment: http://stackoverflow.com/comment/91369226
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91372225
tagged with: python
has comment: http://stackoverflow.com/comment/91398607
has comment: http://stackoverflow.com/comment/91398074
has comment: http://stackoverflow.com/comment/91395219
has comment: http://stackoverflow.com/comment/91389263
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91397911

http://stackoverflow.com/a/52142670
answers question: http://stackoverflow.com/q/52142376
type: Answer
has body: this seems like an appropriate use case for xml https://www.w3schools.com/xml/xml_tree.asp there are a number of libs that support: https://docs.python.org/2/library/xml.etree.elementtree.html
score: 0

http://stackoverflow.com/a/52215041
has comment: http://stackoverflow.com/comment/91379293
score: 4
accepted answer of: http://stackoverflow.com/q/52214895
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52214895
type: Answer
has body: The reduction function used for reduce should always return an object of the same type as its input object, so that it can continue its reduction operation with the resulting object and the next object from the iterator. Your lambda function currently calls dict.setdefault(), a function that always returns None, so it naturally results in an error when it tries the next reduction operation with a None object. For your purpose you should use the following loop instead of a reduction function: stem_word_dictionary = {} for w, k in word_stem_tuple_list: stem_word_dictionary.setdefault(k, []).append(w)
upvote count: 4
has comment: http://stackoverflow.com/comment/91411404
downvote count: 0
has comment: http://stackoverflow.com/comment/91379253
has comment: http://stackoverflow.com/comment/91379291
has comment: http://stackoverflow.com/comment/91379186

http://stackoverflow.com/comment/137683316
has text: @NilsWerner `np.random.rand((5, 2))` yields an error - do you mean `np.random.rand(5, 2) `?
comment on: http://stackoverflow.com/q/52256932
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52167730
answers question: http://stackoverflow.com/q/52162720
score: 0
has body: I think the example is wrong, the init shoul look like this: def __init__(self, description, weight, price): self.description = description self.__weight = weight # &lt;1&gt; self.__price = price self.__weight and self.__price are the internal attributes hidden in the class by the properties
type: Answer

http://stackoverflow.com/q/52200694
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/52200828
favorite count: 0
tagged with: utf-16
tagged with: python-3.x
tagged with: io
tagged with: python
tagged with: text
has title: Python3 reading mixed text/binary data line-by-line
type: AnsweredQuestion
has body: I need to parse a file which has a UTF-16 text header and followed directly by binary data. To be able to read the binary data, I open the file in "rb" mode, then, for reading the header, wrap it into a io.TextIOWrapper(). The problem is that when I execute the .readline() method of the TextIOWrapper object, the wrapper reads ahead too far (even though I only requested a single line) and then runs into a UTF-16 decoding error when encountering the binary portion: A UnicodeDecodeError is raised. However, I need proper parsing of the text data and cannot simply do a binary read first, then do a data.find(b"\n\0") because it's not guaranteed that this actually matches at an even offset (could be midway in-between characters). I would like to avoid doing UTF-16 parsing myself. Is there an easy way to tell TextIOWrapper to not read ahead?
has answer: http://stackoverflow.com/a/52200828
type: Question
has comment: http://stackoverflow.com/comment/91354793
upvote count: 9
score: 9

http://stackoverflow.com/comment/91356407
has text: You might want to adapt this solution to your problem: https://stackoverflow.com/questions/8804830/python-multiprocessing-pickling-error#answer-24673524
type: Comment
comment on: http://stackoverflow.com/q/52201590
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91479487
type: Comment
comment on: http://stackoverflow.com/q/52249871
has text: I'm not incredibly familiar with SSL, but I would need a certificate for each machine, right? I'm hoping this will be an array of up to 20 machines, but they will be operating on a local network. Does that make the task of obtaining and setting up certificates any easier?
score: 0
type: QuestionComment

http://stackoverflow.com/a/52143702
type: Answer
downvote count: 0
score: 1
has body: There is no variable which gets populated under the hood when you find a match. If you need the match index or the matched substring, you need to ask for it specifically. In any event, "a" or "b" or "c" in x doesn't do what you hope or assume. It checks if "a" is a non-False value (which it is, so the remainder of the alternatives are skipped; but for the record, it would then check if "b" is a non-False value, and then finally if "c" in x returns a non-False value). Depending on what exactly you are looking for, perhaps a regular expression would solve your problem? import re regex = re.compile(r'a|b|c') match = regex.search(x) if match: print('{0} in {1}'.format(match.group(0), x)) The precise behavior might differ from what you desire. This will find the leftmost match on any one of the alternatives in the regular expression. If you want different behavior (perhaps first check if "a" is anywhere in the string?) then perhaps ask a more well-defined question.
answers question: http://stackoverflow.com/q/52143318
upvote count: 1

http://stackoverflow.com/q/52139846
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91254153
tagged with: python
tagged with: shared-libraries
tagged with: c++
score: 4
has comment: http://stackoverflow.com/comment/91310685
downvote count: 1
has comment: http://stackoverflow.com/comment/91277039
has comment: http://stackoverflow.com/comment/91276476
type: Question
tagged with: ctypes
upvote count: 5
has body: I'm getting different results for the same shared library when a function (from the shared library) is executed by a standalone executable and when using Python's ctypes for calling the exact same function. The difference was narrowed down to be the version of libm used by the library. When using the library from a standalone executable we link against openlibm, but when the library is linked by ctypes, it's linked against Ubuntu's libm. How can I make ctypes link my shared library against openlibm? The shared library header (fft.h): extern "C" { void fft(const char* srcPath); }; The shared library implementation (fft.cpp): #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;nlohmann/json.hpp&gt; #include &lt;Eigen/Eigen&gt; #include &lt;unsupported/Eigen/FFT&gt; void fft(const char* srcPath) { std::cout.precision(17); std::ifstream fs(srcPath, std::ofstream::in); // Get length of file fs.seekg(0, std::ifstream::end); auto length = fs.tellg(); fs.seekg(0, std::ifstream::beg); // Read the file auto srcRaw = new char[length]; fs.read(srcRaw, length); // Convert data to vector of doubles nlohmann::json j = nlohmann::json::parse(srcRaw); std::vector&lt;double&gt; srcDoubles = j; int n = 65536; Eigen::VectorXd srcEigen(n); Eigen::VectorXcd dstEigen(n); std::copy(srcDoubles.data(), srcDoubles.data() + srcDoubles.size(), srcEigen.data()); Eigen::FFT&lt;double&gt; fft; fft.fwd(dstEigen, srcEigen); std::vector&lt;std::complex&lt;double&gt;&gt; dstTmp(dstEigen.data(), dstEigen.data() + dstEigen.size()); for (size_t i = 0; i &lt; dstTmp.size(); i++) { std::cout &lt;&lt; "Result[" &lt;&lt; i &lt;&lt; "] = " &lt;&lt; dstTmp[i].real() &lt;&lt; "+i*" &lt;&lt; dstTmp[i].imag() &lt;&lt; std::endl; } delete[] srcRaw; } Using the library from a standalone executable: #include &lt;fft.h&gt; int main(int argc, char** argv) { fft("input_data"); } Using Python's ctypes: from ctypes import c_char_p, CDLL class LibCFft(CDLL): def __init__(self): super(LibCFft, self).__init__("li…
tagged with: clang++
has comment: http://stackoverflow.com/comment/104097012
has title: How to replace libm when using ctypes?
answer count: 1
has comment: http://stackoverflow.com/comment/91277857
favorite count: 0
has answer: http://stackoverflow.com/a/52140614

http://stackoverflow.com/comment/91410019
has text: it looks like this `\x08\xe4\x87\x92\xcf\xe4\x84\x8f\xff\xf3\xa4\xb0\xfe\xff\xc6\xd2\xff\xff\xc6\xd2\xff\x` I'm also sending the information with a header that is x-www-form-urlencoded and sending a json with one of the fields set to `data`
type: Comment
comment on: http://stackoverflow.com/a/52230058
type: AnswerComment
score: 0

http://stackoverflow.com/a/63735210
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52142357
downvote count: 0
has body: def run_process(cmd_args): with subprocess.Popen(cmd_args, stdout=subprocess.PIPE) as p: output = p.stdout.read() return output It worked for the same question.
type: Answer

http://stackoverflow.com/a/52159809
accepted answer of: http://stackoverflow.com/q/52152355
answers question: http://stackoverflow.com/q/52152355
score: 0
type: AcceptedAnswer
type: Answer
has body: Because you are using request.get_host, that is going to resolve to whatever the user typed into the browser. You probably have your DNS records set up to accept the domain either with or without www. Django doesn't care what domain it's serving, except/unless you are using its Sites framework (your sample code does not touch the Sites framework, so I'm guessing you aren't). Therefore, Django responds based on the URL path alone, and ignores the domain. Are you asking if you can have "www" stripped from the inbound request? Sure, you can do that at the web server (apache/nginx etc.) layer with redirects specific to those web servers. Or you can let the request through the web server and intercept it at the app server layer (Django) with custom middleware. Here is an example of that. Note you cannot use the Redirects app built into Django because it only operates on paths, whereas you want to manipulate the incoming domain itself. So, your choice: Tweak your web server, or add a middleware module to your Django project. The ALLOWED_HOSTS setting is unrelated to your question. Aside: Your question is a bit confusing because you first ask about the removed query parameter ?page=3 but then you switch to asking about www in the domain. If you are asking about query params, please edit your question, as that warrants a different answer.

http://stackoverflow.com/comment/91442942
comment on: http://stackoverflow.com/a/52247094
score: 0
type: AnswerComment
has text: Follow up: How about calculating the sum of two cells aligned to the right? I.e. for my example I would get [8, 10, 8, 3, 5, 11, 13, 11, 17, 13, 6, 5] (12 values). I'm not allowed to use a 1d array as 'kernel', and when I try np.array([1,1]).reshape(1,2) get something completely wrong :P
type: Comment

http://stackoverflow.com/comment/91232722
type: AnswerComment
type: Comment
has text: For some reason my output is different. My values are 6, 4, 1, 0, 0. The only thing I changed was read_clipboard to read_csv. Any idea why this is happening? The dataframe has the correct values so it could be the sum that is incorrect?
comment on: http://stackoverflow.com/a/52141144
score: 0

python-import
tags question: http://stackoverflow.com/q/52212063
tags question: http://stackoverflow.com/q/52158448
tags question: http://stackoverflow.com/q/52156258
tag name: python-import
tags question: http://stackoverflow.com/q/52162671
tags question: http://stackoverflow.com/q/52262686
tags question: http://stackoverflow.com/q/52157214
tags question: http://stackoverflow.com/q/52124904
tags question: http://stackoverflow.com/q/52242272
tags question: http://stackoverflow.com/q/52259653
tags question: http://stackoverflow.com/q/52155056
tags question: http://stackoverflow.com/q/52242928
tags question: http://stackoverflow.com/q/52150763
tags question: http://stackoverflow.com/q/52167754
tags question: http://stackoverflow.com/q/52268108
tags question: http://stackoverflow.com/q/52248505
tags question: http://stackoverflow.com/q/52120006
tags question: http://stackoverflow.com/q/52231825
tags question: http://stackoverflow.com/q/52259585
type: Tag
tags question: http://stackoverflow.com/q/52187412
tags question: http://stackoverflow.com/q/52168700
tags question: http://stackoverflow.com/q/52136349
tags question: http://stackoverflow.com/q/52196356
tags question: http://stackoverflow.com/q/52236797
tags question: http://stackoverflow.com/q/52127011

http://stackoverflow.com/comment/91367475
score: 0
has text: @Prune I copy and pasted your code, I just have a comment at the top with my name and description so the line isn't correct sorry! But okay! I tried doing print(in_file.read(8).split() first, and then I tried doing what you suggested. It is printing out the number after the last decimal on a new line. The error says that value int() is an " invalid literal with base 10: '.0' ". I am honestly pretty daft here and I'm not sure what that base 10: '.0' part means.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52208627

http://stackoverflow.com/comment/91456592
comment on: http://stackoverflow.com/q/52219574
score: 0
type: Comment
type: QuestionComment
has text: Thanks a lot @Zharios, im working on it. I also found this qt library https://doc-snapshots.qt.io/qt5-5.11/qml-location5-maps.html, do you think this is suitable?

http://stackoverflow.com/a/52195960
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/91372106
has body: It looks like DataFrame.plot takes an ax argument for a pyplot axis https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html. Try: ax = plt.subplot(1, 2, 1) myDataFrame.plot(kind='scatter' x='xcol', y='ycol', ax=ax)
accepted answer of: http://stackoverflow.com/q/52195838
score: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52195838

wifi
tag name: wifi
type: Tag
tags question: http://stackoverflow.com/q/52114201

http://stackoverflow.com/comment/91270426
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52160224
type: AnswerComment
has text: yes, thank you I was trying with grep but did not know about '-w'

http://stackoverflow.com/comment/91333911
type: AnswerComment
comment on: http://stackoverflow.com/a/52191717
score: 0
type: Comment
has text: The OP wants to know how does the constraint_function impact the results. You could try explaining this with an example.

http://stackoverflow.com/a/52165233
has comment: http://stackoverflow.com/comment/91281003
answers question: http://stackoverflow.com/q/52165037
has comment: http://stackoverflow.com/comment/91280233
has comment: http://stackoverflow.com/comment/91280801
has body: You can extract the color_cycle using rcParams and assign them as the colors for ax1 as (matplotlib version 2.0.2) ax1.set_prop_cycle(marker=['o','s','x','+','*'], color=plt.rcParams['axes.color_cycle']) The colors might be different on your machine but will be consistent in both the plots. EDIT (@ImportanceOfBeingEarnest's suggestion in the comments) in case of depreciation warning ax1.set_prop_cycle(marker=['o','s','x','+','*'], color=plt.rcParams["axes.prop_cycle"].by_key()["color"][:5]) Output
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91281215
has comment: http://stackoverflow.com/comment/91280455
has comment: http://stackoverflow.com/comment/91281094
upvote count: 2
type: Answer

http://stackoverflow.com/comment/91210627
has text: Please provide a **[mcve]**. What is your dataset? Is it a CSV file, Pandas dataframe, or something else? Also show us your latest attempt(s).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52130146

http://stackoverflow.com/a/52260926
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52260838
has comment: http://stackoverflow.com/comment/91469494
answers question: http://stackoverflow.com/q/52260838
has comment: http://stackoverflow.com/comment/91469564
type: Answer
downvote count: 0
score: 1
has body: The issue is that X and y are 2 dimensional: &gt;&gt;&gt; X array([[1.9330627 ], [0.19204405], [0.21168505], [0.65018234], [0.83079548]]) &gt;&gt;&gt; y array([[8.60619212], [6.09210226], [5.33097283], [5.71649684], [5.18771916]]) So corrcoef is thinking Each row of x represents a variable, and each column a single observation of all those variables (quoted from the docs) What you can do is either flatten the two to one dimension: &gt;&gt;&gt; np.corrcoef(X.flatten(),y.flatten()) array([[1. , 0.84196446], [0.84196446, 1. ]]) Or use rowvar=False: &gt;&gt;&gt; np.corrcoef(X,y,rowvar=False) array([[1. , 0.84196446], [0.84196446, 1. ]])
upvote count: 1

http://stackoverflow.com/q/52182048
tagged with: python
has body: I have 2-D data of shape (?, n) where ? may differ from one sample to another. Each sample corresponds to one recording, each recording is of time-length ? and n is the number of features (same for all recordings). I want to apply an operation, that is independent component analysis, on all of samples. ICA is kind of PCA and will reduce my number of features to, let's say m &lt; n. However, of course, this operation has to be done on the overall dataset. But, I don't want to concatenate all my recordings because I need to keep "distinguishing" them. How can I proceed ? Thanks for help !
tagged with: pca
answer count: 0
score: 1
upvote count: 1
type: Question
has title: Apply the same transformation on separated arrays (without concatenating)
downvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/52225235
has comment: http://stackoverflow.com/comment/91404363
has comment: http://stackoverflow.com/comment/91400061
has comment: http://stackoverflow.com/comment/91404278
has comment: http://stackoverflow.com/comment/91403870
score: 2
type: AcceptedAnswer
downvote count: 0
has body: Using regex: import re s = '' print(re.search(r"dp\/([A-Za-z0-9]{10})\/", s)[1]) Output:B01J5FGW66 Explanation: begin at "dp/": dp\/ capture group delimited by () matching 10 (through {10}) small letters(a-z), capital letters(A-Z) and numbers(0-9): ([A-Za-z0-9]{10}) end at "/": \/ using re.search we can search for that expression in your string sand acces the results for the 1st capture group with [1]. Note that you might want to add extra code in case no match is found: m = re.search(r"dp\/([A-Za-z0-9]{10})\/", s) if m is not None: print(m[1]) else: # if nothing is found, search return None print("No match")
answers question: http://stackoverflow.com/q/52225108
type: Answer
has comment: http://stackoverflow.com/comment/91404235
accepted answer of: http://stackoverflow.com/q/52225108
has comment: http://stackoverflow.com/comment/91401935
upvote count: 2
has comment: http://stackoverflow.com/comment/91404103

http://stackoverflow.com/q/52175456
tagged with: brew-doctor
downvote count: 0
answer count: 1
tagged with: macos
favorite count: 0
has title: How to fix missing dependencies for python - Homebrew
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: homebrew
tagged with: python
has answer: http://stackoverflow.com/a/54826340
score: 2
has body: I recently installed Python3.7 from Python.org. Previously I had an installation via brew which I uninstalled because I just could not get some packages to work. Now, python3.7 is working but when I run brew doctor I get a warning message saying I should install python as it is a dependency for vim. Vim is working fine. Shall I ignore this warning? I would rather not and have everything nicely set up. Shall I install a third python version via brew? I would rather just stick to one I recently installed [+ the Apple supplied python2.7]. So, is there a way to let brew know to use the existing python3.7 installation? $ brew doctor Please note that these warnings are just used to help the Homebrew maintainers with debugging if you file an issue. If everything you use Homebrew for is working fine: please don't worry or file an issue; just ignore this. Thanks! Warning: "config" scripts exist outside your system or Homebrew directories. ./configure scripts often look for *-config scripts to determine if software packages are installed, and what additional flags to use when compiling and linking. Having additional scripts in your path can confuse software installed via Homebrew if the config script overrides a system or Homebrew provided script of the same name. We found the following "config" scripts: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7-config /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7m-config /Library/Frameworks/Python.framework/Versions/3.7/bin/python3-config Warning: Some installed formulae are missing dependencies. You should brew install the missing dependencies: brew install python Run brew missing for more details. $ brew missing vim: python $ brew --config ORIGIN: https://github.com/Homebrew/brew HEAD:61ace27006a1cb444552c0be10087fcbc3051643 Last commit: 32 hours ago Core tap ORIGIN: https://github.com/Homebrew/homebrew-core Core tap HEAD: 1e49b74a54bebb907f95b57fb8f4b7b4b0f9a7bf Core tap last commit: 4 hours ago HOM…
type: Question

http://stackoverflow.com/comment/91369826
has text: Yes it is. It would be better if you post another question with sample dataframe for the same.
type: AnswerComment
comment on: http://stackoverflow.com/a/52210156
score: 0
type: Comment

http://stackoverflow.com/comment/91381903
score: 0
has text: Possible duplicate of [How to know if a binary number divides by 3?](https://stackoverflow.com/questions/39385971/how-to-know-if-a-binary-number-divides-by-3)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52216489

http://stackoverflow.com/comment/91299745
type: QuestionComment
has text: Related: [Remove element from JSON list...](https://stackoverflow.com/a/38547020/202229)
score: 0
comment on: http://stackoverflow.com/q/52174334
type: Comment

http://stackoverflow.com/a/52226009
type: Answer
score: 2
downvote count: 0
has body: The basis for the eigenspace associated with an eigenvalue with geometric multiplicity 2 is not unique. So it is not unexpected that two different libraries would return different bases. I don't see anything wrong with the results computed by numpy.linalg.eigh for matrix1. For example, In [47]: E1, V1 = linalg.eigh(matrix1) Verify that E1 and V1 satisfy the eigenvalue problem: In [48]: np.allclose(matrix1 @ V1, V1 @ np.diag(E1)) Out[48]: True Verify that the vectors in V1 are orthonormal: In [49]: np.allclose(V1.T @ V1, np.eye(len(matrix1))) Out[49]: True
upvote count: 2
answers question: http://stackoverflow.com/q/52225659

http://stackoverflow.com/q/52169324
tagged with: python
has comment: http://stackoverflow.com/comment/91305327
answer count: 0
tagged with: placeholder
tagged with: tensorflow
type: Question
has title: Issue while feeding a placeholder with shape (?, n)
has comment: http://stackoverflow.com/comment/91315874
score: 0
has body: I've an issue to feed my placeholder. I have the following error message: InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'NSregex_9/Placeholder' with dtype float and shape [?,30] I feed my placeholder with a np.array of shape [1, 30]: with tf.Session() as session: session.run(tf.global_variables_initializer()) regexp_vector = generate_tf_vector_from_list_regexp(NSinput, regexplist) regexp_vector = np.expand_dims(regexp_vector, axis=0) print("regexp_vector", regexp_vector, type(regexp_vector)) session.run(tf.tables_initializer(), feed_dict={NSregex: regexp_vector}) history = NSmodel.fit(input_train, output_train, validation_data=(input_test, output_test), epochs=100, batch_size=32) the output of generate_tf_vector_from_list_regexp(x, y) is a numpy array of size 30. Therefore I expand it with 1 more dimension to fit with my pleceholder shape. So, I'm struggling to find a solution to feed correctly the placeholder. Every layers of my model have shape of (?, n). The question mark (?) should be assess according to the batch_size ... I don't see where I'm wrong. You could find below the code to give you the overall context: def generate_tf_vector_from_list_regexp(s, listr): ''' input is string tensor listr is a string list of regexp ''' v=[] for regexp in listr: if tf.reshape(tf.strings.regex_full_match(s,tf.convert_to_tensor(regexp, dtype=tf.string)), [])==True: v.append(1.0) else: v.append(0.0) return np.asarray(v) the regexEmbedding lamnda function is just a lambda fonction to create my placeHolder: def RegexEmbedding(x): return = tf.placeholder(tf.float32, shape=[None, nb_classe]) and the model: NSinput = layers.Input(shape=(1,), dtype=tf.string, name='NSinput') NSuse = layers.Lambda(UniversalEmbedding, output_shape=(embed_size,), name="NSuse")(NSinput) NSregex = layers.Lambda(RegexEmbedding, input_shape=(1,), output_shape=(nb_classe,), name="NSregex")(NSinput) NSconcat = layers.concatenate([NSuse, NSregex], axis=1) NSdens…
type: UnansweredQuestion

cassandra-driver
type: Tag
tag name: cassandra-driver
tags question: http://stackoverflow.com/q/52251993

http://stackoverflow.com/comment/91467872
has text: Also what is `sim` in `minval = np.min(Eout[np.nonzero(sim)])`?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52258435

http://stackoverflow.com/comment/91426076
type: QuestionComment
score: 0
has text: No, I used your help to get the update. I configured the users to connect and disconnect. I prescribed routes for them. I opened a new WebSocket in the .js file of the main page, but I did not get it. It seems to me that there is still something to be assigned to the function for getting objects, so that when updating it sends a request to the declared url. But I'm not sure.
comment on: http://stackoverflow.com/q/52191246
type: Comment

http://stackoverflow.com/a/52250277
has body: Somehow, your function need to identify which widget called it; one approach is to pass an argument that refers to the widget. In the following example, an index into a list that contains the widgets is passed when the command is called: import tkinter as tk def colour_change(which_button): if buttons[which_button]['fg'] == 'red': buttons[which_button].configure(fg="blue") else: buttons[which_button].configure(fg="red") root = tk.Tk() button1 = tk.Button(root, text='button 1', fg="red", command=lambda: colour_change(0)) button1.pack() button2 = tk.Button(root, text='button 2', fg="red", command=lambda: colour_change(1)) button2.pack() buttons = [button1, button2] root.mainloop()
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52250125
score: 1

http://stackoverflow.com/a/52113275
has comment: http://stackoverflow.com/comment/91348896
upvote count: 1
has comment: http://stackoverflow.com/comment/91180929
has comment: http://stackoverflow.com/comment/91241291
has comment: http://stackoverflow.com/comment/91319589
has comment: http://stackoverflow.com/comment/91181100
has comment: http://stackoverflow.com/comment/91349054
has comment: http://stackoverflow.com/comment/91241921
has body: First extract values in Medium column by list with Series.str.findall and regex word boundary: L = ['Online','Own'] pat = '|'.join(r"\b{}\b".format(x) for x in L) df['New_Medium'] = df.pop('Medium').str.findall('('+ pat + ')').str.join(', ') #remove rows with empty values df = df[df['New_Medium'].astype(bool)] print (df) Date Investment Type New_Medium 0 1/1/2000 Mutual Fund, Stocks, Fixed Deposit, Real Estate Own, Online 1 1/2/2000 Mutual Fund, Stocks, Real Estate Own 2 1/3/2000 Fixed Deposit Online 4 1/2/2000 Stocks Own, Online Last get all combinations with product and last aggregate join: from itertools import product df1 = pd.DataFrame([j for i in df.apply(lambda x: x.str.split(',\s*')).values for j in product(*i)], columns=df.columns) df = df1.groupby(['Investment Type','New_Medium'])['Date'].agg(', '.join).reset_index() print (df) Investment Type New_Medium Date 0 Fixed Deposit Online 1/1/2000, 1/3/2000 1 Fixed Deposit Own 1/1/2000 2 Mutual Fund Online 1/1/2000 3 Mutual Fund Own 1/1/2000, 1/2/2000 4 Real Estate Online 1/1/2000 5 Real Estate Own 1/1/2000, 1/2/2000 6 Stocks Online 1/1/2000, 1/2/2000 7 Stocks Own 1/1/2000, 1/2/2000, 1/2/2000
has comment: http://stackoverflow.com/comment/91180974
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91181143
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52113097
type: Answer
answers question: http://stackoverflow.com/q/52113097

http://stackoverflow.com/comment/91207803
comment on: http://stackoverflow.com/q/52128440
type: Comment
type: QuestionComment
score: 0
has text: so this is a misunderstanding from my side (i am sorry i fix he question right now ) so if i got 12121221221 i need the 221 as sub string so in that sense i need the longest but indeed when it comes to 12121212 4 times 12 is ok (i am working for and exercise I am sorry for the misunderstanding )

http://stackoverflow.com/comment/91372692
comment on: http://stackoverflow.com/q/52209943
score: 0
type: Comment
type: QuestionComment
has text: I already have a cleanup routine, fixing both common typos as well as stopword and punctuation removal during the tokenization process with spaCy. I am thinking in the end the problem comes from making this list of lists hashable

http://stackoverflow.com/q/52133734
tagged with: web-scraping
has answer: http://stackoverflow.com/a/52133902
tagged with: scrapy
type: AnsweredQuestion
type: Question
has body: I will make this simple. I have a login page. I login. I see the homepage. The homepage has two links. I want to open these two links. Each link has two data. I just want four data from two links which are on the homepage that also comes after logging in. I can scrape upto the link step. I can scrape link but not the data inside the link. How do I do that? Thanks My scrapy code: P.S i just did it on my own intuition, i don't know if it's possible. import scrapy class ClassroomSpider(scrapy.Spider): name = 'classroom' start_urls =['http://classroom.dwit.edu.np/login/index.php'] login_url = 'http://classroom.dwit.edu.np/login/index.php' def parse(self, response): //code to login into the website data = { 'username': mynameisaj 'password': somerandomvalue } yield scrapy.FormRequest(url=self.login_url,formdata = data, callback = self.parse_quotes) def parse_quotes(self,response): Link = response.xpath('//*[@class="event"]/a/@href').extract() //link in the homepage for item in zip(Link): scraped_info = { 'Link':item[0], } yield scraped_info next_page_url = response.xpath('//*[@class="event"]/a/@href').extract() // link in the homepage if next_page_url: yield scrapy.Request(url = next_page_url, callback = self.parse_data) def parse_data(self,response): Data = response.xpath('//*[@class="no-overflow"]/p/text()').extract() //data inside the link in the homepage for item in zip(Data): scraped_info1 = { 'Data':item[0], } yield scraped_info1 UPDATE The html element is : 1) Write a program to print the area and perimeter of a triangle having sides of 3, 4 and 5 units by creating a class named 'Triangle' without any parameter in its constructor. 2) Write a program that would print the information (name, year of joining, salary, address) of three employees by creating a class named 'Employee'. Create properties as needed for Employee class and set values to those properties using constructor with arguments. The output should be as follows: Name Year of joining Address Robert 1994…
has title: Scrape inside link of homepage by logging into the homepage
accepted answer: http://stackoverflow.com/a/52133902
answer count: 1
score: 0
tagged with: python

http://stackoverflow.com/q/52230596
tagged with: tuples
accepted answer: http://stackoverflow.com/a/52230652
tagged with: python
favorite count: 0
tagged with: list
has comment: http://stackoverflow.com/comment/91410900
tagged with: set
upvote count: 1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/480214
score: 1
tagged with: duplicates
has answer: http://stackoverflow.com/a/52230652
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/52230664
has title: Need to remove duplicates from a nested list preserving the order
downvote count: 0
has answer: http://stackoverflow.com/a/52230664
has body: I have a list like below L = [[1,2],[1,3],[1,4],[2,1],[2,5],[3,1],[3,2]] The output should be [[1,2],[1,3],[1,4],[2,5],[3,2]] Please note that the order for the pairs and the elements has to be preserved. In other words, I cannot sort the list because the elements order needs to be preserved for the pairs as well. For example, I need the last element [3,2] to be preserved. If i sort them and remove duplicates this will be changed to [2,3] which I do not want. Also when I say I need to remove duplicates [1,2] or [2,1] is considered to be a duplicate and I want to preserve [1,2] from this.

http://stackoverflow.com/q/52164721
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/52164764
answer count: 5
has answer: http://stackoverflow.com/a/52164797
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52164772
favorite count: 0
tagged with: python-3.x
has title: Fastest way to fill dictionary from list?
has answer: http://stackoverflow.com/a/52164772
type: Question
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52164764
tagged with: list
has body: Here is my list: animallist=["bird","cow","chicken","horse"] I want to create a dictionary, with these animals as keys and values determined by some_funtion. My script: def some_function(eachanimal): #do some stuff with the entry, for example: return eachanimal+"_value" animallist=["bird","cow","chicken","horse"] mydict={} for eachanimal in animallist: mydict[eachanimal]=some_function(eachanimal) This creates mydict, which is: {'bird': 'bird_value', 'cow': 'cow_value', 'chicken': 'chicken_value', 'horse': 'horse_value'} How can I do this faster or more compactly?
has answer: http://stackoverflow.com/a/52164807
score: 0
has answer: http://stackoverflow.com/a/52164778

http://stackoverflow.com/comment/91392622
has text: I added i counter to control the amount of time the loop gets executed. So that it doesn't become infinite loop. There are huge number of comment options in one page so it cant be one, program can just click +add comment dropdown button but can't write text in it so somethin wrong in logic of code. Drop down options just have one image, textfield and submit button.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52220268
score: 0

http://stackoverflow.com/comment/91286360
type: AnswerComment
comment on: http://stackoverflow.com/a/52119344
type: Comment
has text: If this helps with the coding -- The actual data has 9 of the 'Key: Value' pairs I gave in the dummy data. I am guessing that should affect the reshape part???
score: 0

http://stackoverflow.com/a/52237077
upvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52236984
has comment: http://stackoverflow.com/comment/91422693
type: Answer
answers question: http://stackoverflow.com/q/52236984
downvote count: 1
has body: You should add a closing parenthesis to the call to the double_click method: try: actionChains.double_click(driver.find_element_by_xpath("//div[4]/form/div/div")).perform() except NoSuchElementException: actionChains.double_click(driver.find_element_by_xpath("//form/div[2]/div")).perform()
score: -1

http://stackoverflow.com/q/52119217
has body: I am working on a school project where we are supposed to retrieve three color codes (for red, green and blue) from a number between 0-16777215 (because 256x256x256=16777216). I am unable to understand how this number can produce three color codes. The following code was part A of the task, which I have resolved: background = input ('Choose background color:') innersq = input ('Choose color of inner square:') # set up drawing setup(330, 330, 0, 0) screensize(315, 315) goto(-60, 150) # choosing colors bgcolor(background) color(innersq) This code was made so that the user would enter a color green, blue, red etc. The new code is supposed to get the input 0-16777215 and calculate a color code for each of the three main colors. The last part of the code should end up something like this: #choosing colors bgcolor(Rb0-255, Gb0-255, Bb0-255) color (Rb0-255, Gb0-255, Bb0-255)
downvote count: 2
type: Question
score: -2
linked to: http://stackoverflow.com/q/2262100
duplicate of: http://stackoverflow.com/q/2262100
upvote count: 0
answer count: 1
has title: Python: Retrieving color codes from a number input by user
favorite count: 0
tagged with: colors
has answer: http://stackoverflow.com/a/52119292
type: UnansweredQuestion
tagged with: input
tagged with: python
tagged with: calculation
has comment: http://stackoverflow.com/comment/91189325

http://stackoverflow.com/comment/91351052
type: QuestionComment
has text: *"[`issubclass(class, classinfo)`](https://docs.python.org/3/library/functions.html#issubclass) – Return true if `class` is a subclass (direct, indirect or virtual) of `classinfo`. A class is considered a subclass of itself. `classinfo` may be a tuple of class objects, in which case every entry in `classinfo` will be checked."* – I think that's pretty clear. What don't you understand about this behaviour and/or explanation?
score: 4
comment on: http://stackoverflow.com/q/52201028
type: Comment

http://stackoverflow.com/comment/91428748
type: Comment
type: QuestionComment
has text: `setuptools` uses `easy_install` under the hood, and `easy_install` does not distinct between prerelease and release versions. Some day, when `setuptools` drops `easy_install` usage and switched to `pip`, this problem will disappear, but for now the only resort is to explicitly restrict the package version: `install_requires=['mypkg<1.0.10']` etc.
comment on: http://stackoverflow.com/q/52224460
score: 0

http://stackoverflow.com/q/52210619
downvote count: 0
tagged with: neo4j
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52571797
score: 4
type: UnansweredQuestion
tagged with: networkx
type: Question
has title: How to import a networkX graph to neo4j?
has answer: http://stackoverflow.com/a/61731896
upvote count: 4
answer count: 2
has body: I have a graph created with networkX and I am using neonx to import it to neo4j on localhost. I have a networkX type graph called G. Below is the code: data1 = json_graph.node_link_data(G) H = json_graph.node_link_graph(data1) results = neonx.write_to_neo("http://localhost:7474/db/data/", H, 'LINKS_TO') The error I get is: Traceback (most recent call last): File "/Users/aman/venv/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 2961, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-5-0d401e8987b7&gt;", line 31, in &lt;module&gt; results = neonx.write_to_neo("http://localhost:7474/db/data/", H, 'LINKS_TO') File "/Users/aman/venv/lib/python3.7/site-packages/neonx/neo.py", line 86, in write_to_neo batch_url = all_server_urls['batch'] KeyError: 'batch'

http://stackoverflow.com/a/52249373
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52249092
has comment: http://stackoverflow.com/comment/91446915
answers question: http://stackoverflow.com/q/52249092
has body: With the ttk OptionMenu, the first value after the name of the variable is used as the default, which overrides whatever value you had previously set. The simple solution is to provide the default value when creating the widget. Example: loss_option = ttk.OptionMenu(loss_top_win, avgdisc_var, "4.5", *avgdisc_thresh)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91446964
has comment: http://stackoverflow.com/comment/91446959
type: Answer
score: 3

http://stackoverflow.com/a/52191184
accepted answer of: http://stackoverflow.com/q/52190852
type: Answer
answers question: http://stackoverflow.com/q/52190852
has comment: http://stackoverflow.com/comment/91332956
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/91333116
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91333058
has body: Using pd.DataFrame.from_dict pd.DataFrame.from_dict(d,'index').stack().reset_index(level=0) Out[194]: level_0 0 0 a 1.0 1 a 2.0 2 a 3.0 0 b 4.0 1 b 5.0

http://stackoverflow.com/q/52127288
has answer: http://stackoverflow.com/a/52127645
favorite count: 0
score: 0
has answer: http://stackoverflow.com/a/52128623
tagged with: python
has answer: http://stackoverflow.com/a/52127360
has title: Extract index of Non duplicate elements in python list
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/52127389
tagged with: algorithm
has answer: http://stackoverflow.com/a/52127492
has comment: http://stackoverflow.com/comment/91205100
answer count: 6
has answer: http://stackoverflow.com/a/52127622
tagged with: search
upvote count: 2
has body: I have a list: input = ['a','b','c','a','b','d','e','d','g','g'] I want index of all elements except duplicate in a list. output = [0,1,2,5,6,8]
downvote count: 2

http://stackoverflow.com/q/52132703
accepted answer: http://stackoverflow.com/a/52132718
score: 0
type: Question
has body: I am a novice Python user using 3.6 on Python IDLE. I wrote a program for school to calculate distance traveled depending on speed and time. I was able to get the program to display the numerical value of the distance which is great, but I would like it to also show "miles" after the numerical value that way it shows the unit of measurement. Here is my code: def main(): #variable for speed speed = 60 #variables for time time1 = 5 time2 = 8 time3 = 12 #variables for distance distance1 = time1 * speed distance2 = time2 * speed distance3 = time3 * speed #display the distance equations print ("The distance the car will travel in 5 hours is ", distance1 + " miles") print ("The distance the car will travel in 8 hours is ", distance2 + "miles") print ("The distance the car will travel in 12 hours is ", distance3 + "miles") You can see where I tried to concatenate the first string, variable, and the second string. This breaks my code. Any help is appreciated!
has comment: http://stackoverflow.com/comment/91215937
answer count: 1
has answer: http://stackoverflow.com/a/52132718
tagged with: python-3.x
tagged with: python
has title: How can I add string, then a variable, then a string again?
type: AnsweredQuestion

http://stackoverflow.com/q/52213420
favorite count: 0
has comment: http://stackoverflow.com/comment/91376313
tagged with: python-3.x
has body: I'd like to find an efficient way to get all the processes using a particular file. I know I can do psutil.process_iter() and then search process.open_files for the file for each process. This is very inefficient as searching every single process, and every file each process has open, takes a lot of time (10 seconds on my machine). Is there a faster way? Is it possible to just directly get all of the processes using a file, rather than searching every single process?
has comment: http://stackoverflow.com/comment/91377423
type: UnansweredQuestion
tagged with: windows
has comment: http://stackoverflow.com/comment/91376448
tagged with: python
has answer: http://stackoverflow.com/a/74389649
has comment: http://stackoverflow.com/comment/91376341
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91377441
tagged with: psutil
has title: Get all processes using a file in Python
has comment: http://stackoverflow.com/comment/91376379
linked to: http://stackoverflow.com/q/47507578
has comment: http://stackoverflow.com/comment/91376410
has comment: http://stackoverflow.com/comment/91376394
answer count: 1
downvote count: 0
score: 1

http://stackoverflow.com/comment/91311831
type: QuestionComment
score: 0
has text: e.g. `df['A'] = np.where(df.groupby('A')['A'].transform('size') < 3, 1, df['A'])`
comment on: http://stackoverflow.com/q/52180942
type: Comment

http://stackoverflow.com/comment/91301542
comment on: http://stackoverflow.com/a/52156681
score: 0
type: AnswerComment
has text: Anthony Tuininga is the main cx_oracle developer employed by Oracle I believe.
type: Comment

http://stackoverflow.com/a/52201872
has body: You don't have a CSV file, so don't try to treat it as one. CSV specifically means a file consisting of rows of columns, where all rows have the same number of columns and the columns are delimited by a single character (usually a comma or a tab). There is no need to delete the lines from your source file if all you needed was those first 4 values for your code either. Just loop over the lines in the file, split each line by whitespace, and if the resulting list is not empty, take the last value: numbers = [] with open(filename) as inf: for line in inf: data = line.split() if data: numbers.append(data[-1]) str.split() with no arguments splits on arbitrary length whitespace, including tabs, spaces and newlines, with any whitespace at the start and end ignored. When a line is empty the line string will be '\n', and splitting such a line results in an empty list. If there is anything other than whitespace on a line, you get a list of strings for each non-whitespace section: &gt;&gt;&gt; '\n'.split() [] &gt;&gt;&gt; 'P Inst Usage (Bytes): 13322\n'.split() ['P', 'Inst', 'Usage', '(Bytes):', '13322'] Because your file has the numbers you want at the end of each line, taking the last element (with [-1]) gets you all the numbers. If you only need the top four such lines, test the len(numbers) result: numbers = [] with open(filename) as inf: for line in inf: data = line.split() if data: numbers.append(data[-1]) if len(numbers) == 4: break The break stops the for loop, and when you exit the with statement, the file will be closed automatically. If you do ever need to skip blank lines, just test if line.strip() is truthy; str.strip() uses the same arbitrary-width whitespace rules to remove whitespace from the start and end. Empty lines with just a newline separator end up as empty strings, which are considered false when used in a boolean test such as an if ...: condition: if line.strip(): # line is not empty You could then write that to a new file if you so wish, but that's n…
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/52201819
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52201819
type: Answer

http://stackoverflow.com/a/52243145
type: Answer
has comment: http://stackoverflow.com/comment/91434705
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52243000
accepted answer of: http://stackoverflow.com/q/52243000
has body: The object self.z is atf.placeholder. If you execute an operation in your session that depends on this placeholder, than tensorflow needs a value for this placeholder to execute the the real calculations. Lets look into the operations you run: generated_images_real = self.sess.run(generated_images... and self.sess.run([d_optim, self.d_sum] ,... From the definition of self.d_sum we see that it depends on self.z_sum which in turn depends on self.z - our placeholder. Therefore we have to provide a value for this placeholder, if the operation self.d_sum is executed. The operation d_optim might also depend on self.z but its definition is not given here. This explains why we need a value for self.z in the second statement. In the first statement, generated_images depends directly on self.z, as this placeholder is passed to the self.generator function.
has comment: http://stackoverflow.com/comment/91434639

http://stackoverflow.com/comment/91394252
comment on: http://stackoverflow.com/a/52221794
has text: @RichardC Edited.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52262906
tagged with: ironpython
type: Question
has title: Ironpython import in python script
has comment: http://stackoverflow.com/comment/91476497
score: 0
has comment: http://stackoverflow.com/comment/91474622
type: UnansweredQuestion
tagged with: python
has body: When using ironpython in vb.net i am calling a python script. That script needs to import some packages (for example import html2text at the top of the script). On this machine i have python and pip and I have the package installed, but when running this script through ironpython it says it is unable to find it (no module named html2text). So, when using ironpython, where does it look for the packages? how do I install these packages?
tagged with: vb.net
has comment: http://stackoverflow.com/comment/91474393
answer count: 0
has comment: http://stackoverflow.com/comment/91474067

http://stackoverflow.com/a/52245618
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52244667
has comment: http://stackoverflow.com/comment/91441447
upvote count: 1
has body: One approach is via pd.concat, concatenate existing dataframe with new dataframe of desired columns( created by MultiIndex.from_product which gives the combinations of two lists) and your values i.e df first bar baz second one two one two 0 -0.122485 0.943154 1.253930 -0.955231 1 -0.293157 -1.167648 -0.864481 1.251452 values = np.random.randn(2,4) # here goes your values df2 = pd.DataFrame(values, columns=pd.MultiIndex.from_product([['bar','baz'],['third','forth']])) # Column wise concatenation followed by sorting of index for better view ndf = pd.concat([df,df2],axis = 1).sort_index(level='first',axis=1,sort_remaining=False) Output : first bar baz \ second one two third forth one two third 0 -0.122485 0.943154 -0.419076 0.667690 1.253930 -0.955231 -0.858656 1 -0.293157 -1.167648 0.516346 -0.907558 -0.864481 1.251452 0.429894 first second forth 0 0.237544 1 -0.521049

http://stackoverflow.com/comment/91338586
comment on: http://stackoverflow.com/q/52194235
score: 2
has text: @Prune, Note that `Counter` does have a `most_common` method, which means there's no need to manually calculate the max of your values.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52250029
type: UnansweredQuestion
tagged with: machine-learning
tagged with: tensorflow
type: Question
has title: Correct way of scaling data
has comment: http://stackoverflow.com/comment/91449141
has comment: http://stackoverflow.com/comment/91450038
has body: I am using a TensorFlow to create a simple DNN model. When I am training my data I am scaling all the train data the following way: X_scaler = preprocessing.StandardScaler() X_standard = X_scaler.fit_transform(X_train) But when I am using my model checkpoint, I have to scale again the input. Therefore I am scaling the single sample, like this: X_scaler = preprocessing.StandardScaler() X_standard = X_scaler.transform(X_test) But the scaling of the single sample gives me [[0.000000 0.000000 0.000000 0.000000 0.000000 ]] Can someone explain to me what I am doing wrong and how can I scale correctly? My train data is a csv file and inside looks like this: [[11.000000 61.000000 134217728.000000 ... 0.000000 46596.313072 272756.723290] [1.000000 87.000000 134217728.000000 ... 16.449219 13925.136928 289477.942990] [16.000000 73.000000 2097152.000000 ... 19567.666016 50885.644772 305358.707758]] My single test sample is the same but is only one element in the array: [[57.000000 14.000000 2097152.000000 5.000000 3.000000 3.000000 0.000000 262.000000 81788928.000000 1001.000000 527593.000000 349181.000000 182.000000 11.000000 0.349954 0.701496 95.800000 2.280000 1.790000 13141380.000000 3166248.000000 19.420000 25.400000 100.740000 31004.910000 2.000000 1000000000.000000 93.370000 3.030000 3.540000 11483952.000000 3923548.000000 25.470000 40.370000 186.790000 49280.940000 18.000000 3700000000.000000 750.371094 17519.000000 27508.000000 18915.000000 149477.500000 2080774.000000 189943.000000 0.000325 5.376465 350.303954 370104.379128]]
has comment: http://stackoverflow.com/comment/91449095
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/91449272
score: 0
tagged with: scale
tagged with: python
has comment: http://stackoverflow.com/comment/91448850
answer count: 0

http://stackoverflow.com/comment/91489426
type: Comment
comment on: http://stackoverflow.com/a/52268199
score: 0
has text: @Laughingwithu Updated my answer
type: AnswerComment

http://stackoverflow.com/q/52259476
tagged with: resize
has comment: http://stackoverflow.com/comment/91467091
accepted answer: http://stackoverflow.com/a/52281257
has comment: http://stackoverflow.com/comment/91467068
has body: In Python 3.x, I am using PIL to resize images, I know that we can reduce the height or width by subtraction or division by pixels. But, is it possible to resize an image to a desired size, say 200kb and remain its proportions? Assuming the image(s) is larger but the size is unknown.
has title: How to reduce a jpeg size to a 'desired size'?
favorite count: 0
score: 8
tagged with: python
has comment: http://stackoverflow.com/comment/91467340
has comment: http://stackoverflow.com/comment/91467060
linked to: http://stackoverflow.com/q/30192764
downvote count: 1
has answer: http://stackoverflow.com/a/52281257
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91466534
tagged with: python-imaging-library
tagged with: image
type: Question
has comment: http://stackoverflow.com/comment/91484215
upvote count: 9
has comment: http://stackoverflow.com/comment/91469256
answer count: 1

http://stackoverflow.com/a/52169348
score: 9
answers question: http://stackoverflow.com/q/52168971
upvote count: 9
downvote count: 0
has comment: http://stackoverflow.com/comment/91296242
has comment: http://stackoverflow.com/comment/91289176
has comment: http://stackoverflow.com/comment/91295422
has comment: http://stackoverflow.com/comment/91291476
has comment: http://stackoverflow.com/comment/91289263
has body: If you add a print inside FalseInstance.__instancecheck__ you will see that it is not even invoked. However, if you call isinstance('str', Foo) then you'll see that FalseInstance.__instancecheck__ does get invoked. This is due to an optimization in isinstance's implementation that immediately returns True if type(obj) == given_class: int PyObject_IsInstance(PyObject *inst, PyObject *cls) { _Py_IDENTIFIER(__instancecheck__); PyObject *checker; /* Quick test for an exact match */ if (Py_TYPE(inst) == (PyTypeObject *)cls) return 1; . . . } From Python's source code
type: Answer
has comment: http://stackoverflow.com/comment/91297241

http://stackoverflow.com/comment/91412222
has text: save the data to an image and post the image. This is very different than a photo of your computer monitor. It's very unlikely anyone will help you without verifiable test data
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52231121
type: Comment

http://stackoverflow.com/comment/91395150
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52223033
has text: Could you extend a bit on the meaning of `combo1` and `frame3`?

square-root
tags question: http://stackoverflow.com/q/52176199
type: Tag
tag name: square-root

http://stackoverflow.com/a/52412031
type: Answer
answers question: http://stackoverflow.com/q/52138280
has comment: http://stackoverflow.com/comment/107577937
has comment: http://stackoverflow.com/comment/107582403
score: 7
downvote count: 2
upvote count: 9
has body: I found this to work after searching for a while. Here are the steps I followed to install an older python version alongside my standard one: Download the Python3.6 tgz file from the official website (eg. Python-3.6.6.tgz) Unpack it with tar -xvzf Python-3.6.6.tgz cd Python-3.6.6 run ./configure run make altinstall to install it (install vs altinstall explanation here Difference in details between "make install" and "make altinstall") You'll normally find your new python install under /usr/local/bin. Now you can create a new virtualenv specifying the python version to use with: virtualenv --python=python3.6 env3.6 Get into the virtualenv running the command source env3.6/bin/activate. Install tensorflow with the classic pip3 install tensorflow Profit
has comment: http://stackoverflow.com/comment/107580691

http://stackoverflow.com/a/52193236
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52193162
accepted answer of: http://stackoverflow.com/q/52193162
type: Answer
downvote count: 0
score: 1
has body: Encode your string to ASCII, ignoring errors, then decode that back to a string. text = "ƒart" text = text.encode("ascii", "ignore").decode() print(text) # art If you are starting with a byte string in UTF-8, then you just need to decode it: bites = "ƒart".encode("utf8") text = bites.decode("ascii", "ignore") print(text) # art This works specifically with UTF-8 because multi-byte characters always use values outside of the ASCII range, so partial characters are never stripped out. It mightn't work so well with other encodings.
upvote count: 1

http://stackoverflow.com/comment/91374313
type: Comment
has text: Just do masterDF = whatever I wrote
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52211909

http://stackoverflow.com/comment/91349887
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52179406
has text: Sometimes `pip3` does not work correctly in system command line interface, so try to use this code in the jupyter notebook : `!pip3 install --upgrade tensorflow` and for keras `!pip install keras`. And try to run mentioned code.
score: 0

http://stackoverflow.com/comment/91331576
score: 0
type: AnswerComment
has text: @LunchBox I've seen your details and that does not make sense. You need to add what you want as output.
type: Comment
comment on: http://stackoverflow.com/a/52190756

http://stackoverflow.com/comment/91437542
type: QuestionComment
comment on: http://stackoverflow.com/q/52242509
score: 0
has text: @FedericoRubbi thanks for your reply, but i don't think its a local problem, I see the `Only local connections are allowed.` on the server that has the selenium standalone on it. So the 2 servers can comunicate
type: Comment

http://stackoverflow.com/q/52175248
type: Question
has comment: http://stackoverflow.com/comment/91301383
has body: I created a list of dataframes by grouping them on a certain field. I'm performing an operation that drops specific rows in a specific group. Now, I want to overwrite this specific group with the modified group, and then I want to flatten this list of groups into a dataframe and export it to csv. Basically retracing my steps to before the groupby, minus the rows affected post-condition check. How can I achieve this? Here's my code: g = x.groupby(x['field1']) groups = [[field1,df] for field1,df in g] y = groups[0][1] # after a certain condition is met for a specific group... y = y.drop(int(index)) # index is a variable from the condition check and is used to drop that specific index in the df y = y.reset_index(drop=True) df = pd.DataFrame() for ta,group in groups: df = group.unstack() df.to_csv('post_match_{}.csv'.format(session['username'])) I tried using pd.concat(groups) also but it didn't work. Keep getting TypeErrors.
score: 0
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/91301403
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91301430
has comment: http://stackoverflow.com/comment/91301377
has title: How to flatten list of lists of dataframes
has comment: http://stackoverflow.com/comment/91301454
tagged with: list
has comment: http://stackoverflow.com/comment/91301356
has comment: http://stackoverflow.com/comment/91301287
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91301331

http://stackoverflow.com/a/52175617
has body: It depends... and perhaps "both" could be the answer you're looking for. Multiprocess in python uses a standard fork() call in linux to copy the main process. In the case of your minimum program, that's probably not very much data, but depending on how the end program is structured it could be even more data to fork so to speak. In the minimal case the process memory overhead is pretty minimal. Threading will not have this memory overhead problem, but it has has another potential problem other than startup time you may have to worry about... The GIL. The GIL probably won't be a problem if your treads are largely blocked waiting for I/O, but if you're just running a loop like you are in your test, only 2 threads will run at a time.... In other words; even though you got the same time in your test there is a lot going on there under the covers that a simple test like this won't catch. The right answer for a running program probably isn't worrying about the startup time, but it will probably be more dependent on What's each thread, or process going to be doing? What memory and state does it need access to, will locking be a concern? In python, will the GIL be problematic for the workload (are 2 running threads at a time going to be enough for the workload) Is multiplying the process foot print by the number of processes an acceptable amount of memory A basic rule of thumb I follow is that if the thread/process is mainly going to be blocked on I/O (waiting for network traffic or something) use a thread. If you have more computationally heavy requirements and memory isn't a concern use a process. An exception of that rule is how to I want to handle the memory and state of the process or threads. When you start talking large numbers of threads, and processes like this you'll probably have memory access / lock contention to think about... Realistically though, without more data it's hard to make a good suggestion. Concurrent programming is one of those things that many peo…
answers question: http://stackoverflow.com/q/52175375
score: 1
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/91511707
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52231058
has text: @yan without an MCVE I could not help you, so I invite you to post a question

http://stackoverflow.com/comment/91428904
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52239831
has text: See my corrections. I edited the Repl.it and can see the form work. But you need to figure out your URLs better (I assume is work in progress)

http://stackoverflow.com/comment/91621510
type: AnswerComment
type: Comment
has text: @ryan_thomp that works! I'll take a look once changed
comment on: http://stackoverflow.com/a/52171603
score: 0

psycopg2
tags question: http://stackoverflow.com/q/52145452
tags question: http://stackoverflow.com/q/52184847
tags question: http://stackoverflow.com/q/52171348
type: Tag
tags question: http://stackoverflow.com/q/52126169
tags question: http://stackoverflow.com/q/52223789
tags question: http://stackoverflow.com/q/52135914
tags question: http://stackoverflow.com/q/52204311
tags question: http://stackoverflow.com/q/52201470
tags question: http://stackoverflow.com/q/52126270
tags question: http://stackoverflow.com/q/52203781
tags question: http://stackoverflow.com/q/52173763
tags question: http://stackoverflow.com/q/52151156
tag name: psycopg2

http://stackoverflow.com/a/52180287
has comment: http://stackoverflow.com/comment/91310741
answers question: http://stackoverflow.com/q/52179685
type: Answer
has comment: http://stackoverflow.com/comment/91311071
has comment: http://stackoverflow.com/comment/91315363
has comment: http://stackoverflow.com/comment/91318095
has comment: http://stackoverflow.com/comment/91312590
has body: Its really interesting attribute of spark i did not know it before. I think when you use single core, classes are not pickled(pickle is needed to use class in other places). But you can still use functions (i assume you sorted values by first two values): key_func = lambda tup : tup[:2] r1 = sc.parallelize([(1, 2), (2, 2), (2, 3), (2, 1), (1, 3)]) r2 = r1.sortBy(key_func) print(r2.collect())
has comment: http://stackoverflow.com/comment/91311148
has comment: http://stackoverflow.com/comment/91311495
score: 0
has comment: http://stackoverflow.com/comment/91310921

http://stackoverflow.com/comment/91342279
comment on: http://stackoverflow.com/q/52195727
has text: What happens when it does not work? Do you get an error? Bad transcripts? Something else? Is the problem reproducible, or does it work the next time?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52171534
tagged with: rounding
has body: I want to do arithmetic with converted number strings using decimal.Decimal. I want the return to have two decimals regardless of the quantity of decimals the converted number strings have. In this particular case, why does two decimal precision give me one decimal return and why does three decimal precision give me the return I want (2 decimals -&gt; 2.15) from decimal import * getcontext().prec = 2 a = Decimal(x.replace(',','.')) b = Decimal(y.replace(',','.')) print(a), print(b), print(a-b) &gt;&gt;&gt; 2.60 0.45 2.2 getcontext().prec = 3 a = Decimal(x.replace(',','.')) b = Decimal(y.replace(',','.')) print(a, b, a-b) &gt;&gt;&gt; 2.60 0.45 2.15
tagged with: decimal
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52171988
has title: Python decimal.Decimal - getcontext().prec setting and number of decimals in output
tagged with: python
has comment: http://stackoverflow.com/comment/91295501
accepted answer: http://stackoverflow.com/a/52171988
tagged with: precision
score: 2
type: AnsweredQuestion
upvote count: 2
tagged with: floating-point
type: Question

http://stackoverflow.com/comment/91359275
type: QuestionComment
has text: The original line of code is a dictionary comprehension, not a list comprehension, you can tell by the curly braces and the `key:value` pair
comment on: http://stackoverflow.com/q/52205068
score: 1
type: Comment

http://stackoverflow.com/comment/91284151
comment on: http://stackoverflow.com/a/52166162
type: AnswerComment
score: 0
type: Comment
has text: If the server runs, then this should normally work yes.

http://stackoverflow.com/q/52232080
accepted answer: http://stackoverflow.com/a/52232371
type: Question
answer count: 1
downvote count: 0
has title: Scapy sniff the packet multiple times?
favorite count: 0
has answer: http://stackoverflow.com/a/52232371
has body: I am using Scapy to capture packets by using the following code from scapy.all import * def verify(p): p.display() sniff(prn=verify, iface="lo") The sniff function captures every packet multiple times. For example, if I have a DNS query packet, this packet will display two times. How can make The sniff function to capture each packet only single time?
tagged with: scapy
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/52265739
accepted answer of: http://stackoverflow.com/q/52265577
score: 3
has comment: http://stackoverflow.com/comment/91479772
downvote count: 0
upvote count: 3
type: AcceptedAnswer
has body: The line: SOUP = BeautifulSoup('SOURCE', 'lxml') tries to create a soup object from the string 'SOURCE' not from the value stored in the variable SOURCE. You're also looking for the wrong element in the html, you don't want a &lt;div&gt; with class="header", you're actually looking for a &lt;header&gt; element (of which there are multiple on this page). I'd actually suggest looking for the &lt;h2&gt; element with class="entry-title", which you can do like this: import requests from bs4 import BeautifulSoup SOURCE = requests.get('http://coreyms.com/').text SOUP = BeautifulSoup(SOURCE, 'lxml') HEADER = SOUP.find('h2', class_='entry-title') headline_href = HEADER.a['href'] print(headline_href) which prints http://coreyms.com/development/best-sublime-text-features-and-shortcuts
has comment: http://stackoverflow.com/comment/91479687
has comment: http://stackoverflow.com/comment/91480016
answers question: http://stackoverflow.com/q/52265577
type: Answer

http://stackoverflow.com/q/52141535
has title: "Connection aborted" error when using Python Requests
score: 2
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
tagged with: python
tagged with: web-scraping
tagged with: python-requests
has body: I'm trying to scrape price information from Carrefour website with the following code headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36', } link = 'https://www.carrefour.es/extensor-tp-link-rango-75/366506176/p' response = requests.get(link, headers=headers, timeout=60) # Following lines parse response with Beautifulsoup This code ends up with "Connection aborted" error. The error message is sligted different on Linux and Windows When run on AWS (Ubuntu), it always result in error with below message requests.exceptions.ConnectionError: ('Connection aborted.', BadStatusLine("''",)) While run on my PC (Win10), sometimes it works correctly, sometimes error occurs with message below requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)) I guess this is not caused by IP restriction or User-Agent: Although the script result in no connect, I can still visit link using my PC (Win10), with same IP and User-Agent. Am I blocked? What's the possible reason of being blocked?
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/52183788
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52164003
accepted answer of: http://stackoverflow.com/q/52164003
has comment: http://stackoverflow.com/comment/91318834
has comment: http://stackoverflow.com/comment/91319164
has comment: http://stackoverflow.com/comment/91318523
has body: I finally done it, I am able to update the statusbars see the Information below. I have added the following method in each of the frames. The purpose of this method is to check the flag, that holds the Telnet session status (connect), periodically. So I am still using the same threads: the Main GUI thread and another thread which maintains the Telnet session. In order to "activate" this method I start it once a certain frame was raised ("frame_was_raised" method) def update_statusbar(self): '''Poll the Telnet Session Status for the purpose of update''' global connected if connected: self.my_string_var.set('Connected') self.status.config(fg='springgreen3') else: self.my_string_var.set('Disconnected') self.status.config(fg='red2') self.after(2000, self.update_statusbar)
type: AcceptedAnswer

http://stackoverflow.com/comment/91262693
comment on: http://stackoverflow.com/q/52156031
has text: First of you'll need to create your own instance of `random.Random` and to set its seed with `.seed()`, but that probably doesn't guarantee the same generated numbers on different machines, I'm not sure.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52179760
has body: You should use {% include "nav.html" %} inside the {% block content %} tag. Otherwise it won't be shown.
downvote count: 1
answers question: http://stackoverflow.com/q/52179044
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/91310264
type: Answer

http://stackoverflow.com/comment/91230148
type: Comment
comment on: http://stackoverflow.com/q/52140256
score: 0
has text: because you haven't told the if to pass.
type: QuestionComment

http://stackoverflow.com/comment/91216042
type: AnswerComment
comment on: http://stackoverflow.com/a/52132718
type: Comment
has text: This worked perfectly! I used the new formatting you suggested, really nice and simple. Thanks a million zvone.
score: 0

request
tags question: http://stackoverflow.com/q/52156583
tags question: http://stackoverflow.com/q/52183357
tags question: http://stackoverflow.com/q/52209121
tags question: http://stackoverflow.com/q/52117522
tag name: request
type: Tag
tags question: http://stackoverflow.com/q/52129216

http://stackoverflow.com/a/52182801
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91345839
type: Answer
has comment: http://stackoverflow.com/comment/91315481
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91315507
has body: Just convert df['Type'] to Categorical first: df['Type'] = df['Type'].astype('category') This forces Pandas to show every value with pivot_table. It's also good practice to trust Pandas conversion of strings such as 'sum' to optimised functions. Here's a demo: df['Type'] = df['Type'].astype('category') pt = pd.pivot_table(df, values='Value', index=['Cat', 'Type'], columns='Date', aggfunc='sum', fill_value=0) print(pt) Date 01-Jan 02-Jan 04-Jan 05-Jan Cat Type AA F 0 2 0 0 S 1 0 0 2 T 0 0 0 0 BB F 0 0 0 0 S 0 0 0 4 T 0 3 3 0 CC F 0 0 0 0 S 0 0 0 0 T 0 0 0 2 DD F 0 0 0 0 S 0 0 0 4 T 0 0 0 1
has comment: http://stackoverflow.com/comment/91315416
has comment: http://stackoverflow.com/comment/91315438
has comment: http://stackoverflow.com/comment/91348606
answers question: http://stackoverflow.com/q/52182607
has comment: http://stackoverflow.com/comment/91315546
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52182607
has comment: http://stackoverflow.com/comment/91315539

http://stackoverflow.com/q/52228871
has body: I'm developing a dispy script operating on a large number of objects (duh). There are multiple operations to be performed for each object -- only one of them must happen first, the rest use the first job's results and can be done in any order. cluster = dispy.JobCluster( getShift, setup = functools.partial(doLoads, from, to), cluster_status = processed, nodes = Nodes ) The straightforward way, I suppose, is to do two loops of cluster.submit() -- first loop for the first job for each object, and the second loop -- for all others. However, I'd like to begin submitting the subsequent jobs as soon as the primary one is finished for each object -- without waiting for it to be done for all the other objects. What's the right way to do that? In particular, can my processed callback function submit additional jobs to the same cluster?
has answer: http://stackoverflow.com/a/52231532
tagged with: python
type: AnsweredQuestion
tagged with: dispy
has title: Can the cluster_status callback submit new jobs?
score: 0
type: Question
accepted answer: http://stackoverflow.com/a/52231532
answer count: 1

http://stackoverflow.com/q/52162720
possible better answer: http://stackoverflow.com/a/52166657
has comment: http://stackoverflow.com/comment/91275069
has body: I'm reading Fluent Python chapter 19 > A Proper Look at Properties, and I'm confused about the following words: Properties are always class attributes, but they actually manage attribute access in the instances of the class. The example code is: class LineItem: def __init__(self, description, weight, price): self.description = description self.weight = weight # &lt;1&gt; self.price = price def subtotal(self): return self.weight * self.price @property # &lt;2&gt; def weight(self): # &lt;3&gt; return self.__weight # &lt;4&gt; @weight.setter # &lt;5&gt; def weight(self, value): if value &gt; 0: self.__weight = value # &lt;6&gt; else: raise ValueError('value must be &gt; 0') # &lt;7&gt; From my previous experiences, class attributes are belong to the class itself and shared by all the instances. But here, weight, the property, is an instance method and the value returned by it is different between instances. How is it eligible to be a class attribute? Doesn't it that all the class attributes should be the same for any instances? I think I misunderstand something, so I hope to get a correct explanation. Thanks!
tagged with: python
has title: Why are properties class attributes in Python?
score: 8
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52167328
linked to: http://stackoverflow.com/q/17330160
accepted answer: http://stackoverflow.com/a/52196913
type: Question
has answer: http://stackoverflow.com/a/52167730
has answer: http://stackoverflow.com/a/52167161
downvote count: 0
has answer: http://stackoverflow.com/a/52166657
has answer: http://stackoverflow.com/a/52196913
favorite count: 0
upvote count: 8
answer count: 5

http://stackoverflow.com/comment/91353573
comment on: http://stackoverflow.com/q/52146092
score: 0
type: Comment
type: QuestionComment
has text: Maybe, but without that we cant solve your problem. Anyways, which version of sklearn are you using

http://stackoverflow.com/a/52166611
type: Answer
upvote count: 0
has body: Check cfpLoadingBar. It is lovely and flexible. You can even ignore the loading for some particular requests.
answers question: http://stackoverflow.com/q/52166468
score: -1
downvote count: 1

http://stackoverflow.com/q/52217151
has body: I'm planning to provide the test and train datasets explicitly to the algorithm and not to use the train_test_split method for random splitting of the data into test and train respectively. And I want to keep the reviews and labels data in the same file while testing as well as training the model. Can anyone of you please suggest me regarding the same ... My code: from sklearn.preprocessing import MultiLabelBinarizer from sklearn.model_selection import train_test_split from sklearn.svm import LinearSVC from sklearn.metrics import average_precision_score from sklearn.metrics import confusion_matrix with open("/Users/xyz/Desktop/reviews.txt") as f: reviews = f.read().split("\n") with open("/Users/xyz/Desktop/labels.txt") as f: labels = f.read().split("\n") reviews_tokens = [review.split() for review in reviews] onehot_enc = MultiLabelBinarizer() onehot_enc.fit(reviews_tokens) X_train, X_test, y_train, y_test = train_test_split(reviews_tokens, labels, test_size=0.20, random_state=None) lsvm = LinearSVC() lsvm.fit(onehot_enc.transform(X_train), y_train) accuracy_score = lsvm.score(onehot_enc.transform(X_test), y_test) print("Accuracy score of SVM:" , accuracy_score) Test.txt review,label Colors &amp; clarity is superb,positive Sadly the picture is not nearly as clear or bright as my 40 inch Samsung,negative Train.txt: review,label The picture is clear and beautiful,positive Picture is not clear,negative
has title: How can we give explicit test data and train data to SVM instead of using train_test_split function?
tagged with: python
score: -2
type: UnansweredQuestion
downvote count: 2
type: Question
tagged with: svm
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52217683
tagged with: scikit-learn
favorite count: 0

http://stackoverflow.com/a/52257272
answers question: http://stackoverflow.com/q/52256931
score: 1
upvote count: 1
has body: Shouldn't need to means you don't have to worry about that method, the library will work without any special attributes set on the instance. However, that doesn't mean you can't. For example, the BaseHTTPRequestHandler class doesn't define a __init__ method itself, but the SimpleHTTPRequestHandler class in the same module is a direct subclass of BaseHTTPRequestHandler which does define an __init__ method. Your code can define one just fine: class RequestHandler(BaseHTTPRequestHandler): def __init__(self, ...): # do something with arguments and set state on self def do_POST(self): # do some stuff
downvote count: 0
type: Answer

http://stackoverflow.com/a/52277289
has body: Migrating solution from comments to answers. Thanks to @Wen. df=df.apply(pd.to_numeric, errors='coerce')
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52240694
answers question: http://stackoverflow.com/q/52240694
type: Answer
score: 6
downvote count: 0
upvote count: 6

http://stackoverflow.com/q/52184053
upvote count: 1
downvote count: 1
type: Question
tagged with: neural-network
has comment: http://stackoverflow.com/comment/91317878
has title: Why do I have such inconsistent results when training my model?
score: 0
has comment: http://stackoverflow.com/comment/91318039
answer count: 2
tagged with: deep-learning
accepted answer: http://stackoverflow.com/a/52184303
tagged with: keras
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/52184312
type: AnsweredQuestion
has body: I am using Keras to train my model. I have initialised numpy and tensorflow seeds. I have made a 50-iterations loop where I train and test my Keras deep learning architecture (always the same) on the same training, validation and test sets. I get those results : print (np.mean(train_accuracy_vec)) print (np.std(train_accuracy_vec)) print () print (np.mean(valid_accuracy_vec)) print (np.std(valid_accuracy_vec)) print () print (np.mean(test_accuracy_vec)) print (np.std(test_accuracy_vec)) print () I get this : Sometimes it gives an unacceptable false positive rates while sometimes, it works quite well. I used EarlyStopping based on val_acc behaviour. So, what could cause a so great instability ? Also isn't it a bit odd to have validation score far under test score ? Thanks EDIT: Despite @Thomas Pinetz kind answer, I don't get better results at the second time : still high std... To be more precise, here is how my loop is made : # tf, random and numpy seeds... # lots of data reading, preprocessing,...(including split between train, valid and test sets) for k in range (0,50) : print (k) model = Sequential() model.add(Dense(200, activation='elu', input_dim=trainX.shape[1], init=keras.initializers.glorot_uniform(1))) model.add(Dropout(0.3)) # some additional layers... model.compile(loss='binary_crossentropy',metrics=['accuracy'], optimizer='adam') model.fit(trainX, trainY, validation_data=(validX, validY), epochs=100, verbose=0 , callbacks=callbacks_list) train_score = model.evaluate(trainX, trainY) train_accuracy_vec.append (train_score[1]) print(train_score) trainPredict = model.predict(trainX) print(confusion_matrix(trainY, trainPredict.round())) # and the same for valid and test...
has answer: http://stackoverflow.com/a/52184312
has answer: http://stackoverflow.com/a/52184303

http://stackoverflow.com/q/52263561
answer count: 0
score: 1
upvote count: 1
has body: I'm using flask-ask in virtual environment with Ngrok. I keep getting 500 Internal server errors I get the following error: File "C:\Users\laptop\Envs\alexa\lib\site-packages\OpenSSL\crypto.py", line 740, in _subjectAltNameString method = _lib.X509V3_EXT_get(self._extension) AttributeError: module 'lib' has no attribute 'X509V3_EXT_get' I've tried downgrading to older versions of cryptography but they won't install. I get this error. _openssl.c build\temp.win32-3.7\Release\_openssl.c(501): fatal error C1083: Cannot open include file: 'openssl/aes.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.15.26726\\bin\\HostX86\\x86\\cl.exe' failed with exit status 2 I've installed visual studio with C++ thinking it was something to do with compiling but that hasn't worked either. I've also updated setuptools, install OpenSSL and nothing seems to work. My theory is that Flask-Ask is no longer compatible with the version of cryptography, but older versions of cryptography are no long installable because of compiling issues.
type: Question
has title: Flask-ask AttributeError: module 'lib' has no attribute 'X509V3_EXT_get'
has comment: http://stackoverflow.com/comment/94991257
tagged with: flask
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: flask-ask
tagged with: python
tagged with: python-cryptography
has comment: http://stackoverflow.com/comment/95027737

http://stackoverflow.com/comment/91451733
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52252161
score: 1
has text: There is some circular symlink. See https://unix.stackexchange.com/q/141436/226403

http://stackoverflow.com/q/52155791
downvote count: 1
has answer: http://stackoverflow.com/a/52157379
has comment: http://stackoverflow.com/comment/91264912
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52157379
tagged with: methods
type: Question
has comment: http://stackoverflow.com/comment/91265030
has comment: http://stackoverflow.com/comment/91264889
tagged with: class
score: 0
has comment: http://stackoverflow.com/comment/91262027
answer count: 1
tagged with: python
has title: Program keeps putting out weird results
favorite count: 0
has body: I am having a problem with my program where my server receives data that I am NOT sending from my client Connection from: ('192.168.0.17', 58167) data recieved : __UserLogin123__ User Login requested James Green at recieve login James Green in accessCodes 93 {93: ['James', 'Green']} Found User Found 3 data recieved : __QUIT____CHECK_SCORE__ Incorrect code received done Connection from: ('192.168.0.17', 58182) data recieved : __UserLogin123__ User Login requested James Green at recieve login James Green in accessCodes 93 {93: ['James', 'Green']} Found User Found 3 data recieved : __QUIT____CHECK_SCORE__ Incorrect code received the last "data recieved : QUIT___CHECK_SCORE" makes absolutely no sense, I use codes to access methods from classes which will send certain types of data telling the server if i want to (for example) add a user to a database, and it does this by accessing a dictionary storing methods with string keys. Here is the "handler" and "main" from my client: def Main(): global s host = "192.168.0.17" port = 5000 ID = "__UserLogin123__" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.connect((host, port)) s.send(str.encode(ID)) setupCheck = s.recv(2048).decode() time.sleep(1) if setupCheck == "__dataReceived__": username = input("Enter username : ") password = input("Enter password : ") userDetails = (username, password) dataString = pickle.dumps(userDetails) s.send(dataString) access = s.recv(2048).decode() print(access) if access == "__ACCESS_GRANTED__": permissionLvl = s.recv(2048).decode() print(permissionLvl) if permissionLvl == "1": ClientUser = User(username,password) elif permissionLvl == "2": ClientUser = Admin(username,password) elif permissionLvl == "3": ClientUser = HeadAdmin(username,password) else: print("SOMETHING WRONG SOMETHING WROGN") time.sleep(3) handler(ClientUser) else: print("Incorrect details provided") def handler(ClientUser): function_dict = {"__QUIT__": ClientUser.…
tagged with: sockets
upvote count: 1
tagged with: dictionary

http://stackoverflow.com/comment/91406048
has text: This is significantly faster than my approach and appears to give similar results, though not exactly the same (I'll have to test for the best eps value). Can you explain what discr is for?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52217310
type: Comment

http://stackoverflow.com/a/52218055
answers question: http://stackoverflow.com/q/52213170
type: Answer
has body: Generally, this is just a warning. The TensorFlow engine is still a different project from Keras, and Keras will iteratively try to adapt to changes in TensorFlow. Thus, if you are using an older version of TensorFlow, you could run into problems where Keras is already looking for stuff that your current TensorFlow doesn't have yet. Especially with these fast-paced update cycles common for Machine Learning Frameworks like TensorFlow, you don't need to update (although I would heavily recommend it. Furthermore, you can create a stack of versions that fits to your specific needs. As to the "how to install": Note that this is usually a biased answer, and depends on your personal preferences. I personally (!) prefer to use Anaconda Python, since it makes it very easy to integrate a nice stack for Data Science/Machine Learning. Apart from that, if you are using pip (which is totally legitimate, too, and I occasionally use it as well), you can also specify versions. What pip does, though (according to my knowledge), is only specify a specific minimal version. This means that you get some version after the minimal requirement. In your case, you (kind of) require a version range: "Not too old, but also not too new". Since the latest version of TensorFlow is version 1.10, I would in this case still urge you to update the version, like so: pip install tensorflow --upgrade pip install keras --upgrade To make sure that you have a nice compatibility. Additionally, I thought that Keras will also check for the version during installation, so look out for any flags during that.
downvote count: 1
upvote count: 0
score: -1

http://stackoverflow.com/comment/91243499
type: Comment
comment on: http://stackoverflow.com/a/52146838
score: 0
has text: I think you could improve this answer by providing a functional example rather than just presenting two snippets and stating that the combination of the two will give the desired result.
type: AnswerComment

http://stackoverflow.com/comment/91261543
type: Comment
comment on: http://stackoverflow.com/q/52155127
type: QuestionComment
has text: dates_made = driver.find_elements_by_xpath("//div[@class='col-sm-6']/p[1]/date") for date_made in dates_made: print(date_made.text) I think that this should print something like: 1960 1954 1974 1934 etc (just examples)
score: 0

http://stackoverflow.com/a/52989374
type: Answer
accepted answer of: http://stackoverflow.com/q/52146224
answers question: http://stackoverflow.com/q/52146224
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/93002019
downvote count: 0
score: 1
has body: It turned out that I simply didn't build the package from source and thus was not able to access the faster C-based implementation. The steps mentioned here solved the problem for me: The library can also be compiled and/or installed directly from source. Download the source from https://github.com/wannesm/dtaidistance Compile the C extensions: python3 setup.py build_ext --inplace Install into your site-package directory: python3 setup.py install
has comment: http://stackoverflow.com/comment/93018866

http://stackoverflow.com/q/52128440
has comment: http://stackoverflow.com/comment/91207618
tagged with: python
has comment: http://stackoverflow.com/comment/91208204
has comment: http://stackoverflow.com/comment/91208600
has comment: http://stackoverflow.com/comment/91207534
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91208014
has comment: http://stackoverflow.com/comment/91207943
has comment: http://stackoverflow.com/comment/91207447
has title: Finding an unknown pattern in a string python
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/22469997
has answer: http://stackoverflow.com/a/52128948
has comment: http://stackoverflow.com/comment/91207410
linked to: http://stackoverflow.com/q/9369220
answer count: 2
has answer: http://stackoverflow.com/a/52133083
downvote count: 0
has comment: http://stackoverflow.com/comment/91207803
favorite count: 0
has body: I am well aware of following question which also exists on stack overflow String Unknown pattern Matching but the answer there doesn't really work for me. My problem is next. I get a string of characters e.g '1211' and what I need to do is see that 1 is most often repeated and this 2 times in a row. But it can also be "121212112" where 12 is repeated 3 times in a row. But with 12221221 it is 221 that is repeated 2 times rather than 2 that repeats 3 times. here are some results I like to get (the only numbers ever used are 1 and 2's) &gt;&gt;&gt; counter('1211') 1 &gt;&gt;&gt; counter('1212') 2 &gt;&gt;&gt; counter('21212') 2 the outcome I want is how many times it occurs. I have no idea how to even start looking for a pattern since it is not known on forehand and I did some research online and don't find anything similar. Does anyone have any idea how I even start to tackle this problem ? All help is welcome and if you want more information don't hesitate to let me know.

http://stackoverflow.com/q/52173562
has comment: http://stackoverflow.com/comment/91298027
type: Question
has body: Can tuple with list as an element which can be modified at any stage be key in a dictionary?
has answer: http://stackoverflow.com/a/52173669
has title: Can tuple with list as an element be key in a dictionary python?
downvote count: 5
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: -5

http://stackoverflow.com/a/52255079
accepted answer of: http://stackoverflow.com/q/52251582
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52251582
has body: You need to import matplotlib.cm for this to work. import matplotlib.cm cmap = matplotlib.cm.get_cmap('Reds')
type: Answer
score: 16
downvote count: 1
upvote count: 17
has comment: http://stackoverflow.com/comment/139912888

http://stackoverflow.com/comment/91461614
score: 0
comment on: http://stackoverflow.com/q/52248562
type: Comment
type: QuestionComment
has text: The question is updated with the `production.py` and the `wsgi.py`

http://stackoverflow.com/a/52231151
answers question: http://stackoverflow.com/q/52175375
score: 8
upvote count: 8
type: Answer
has body: Your code is not suitable to benchmark start up times between processes and threads. Multithreading Python-code (in CPython) means single core. Any Python-code execution in one thread will exclude proceeding for all other threads in this process for the time this one thread is holding the global interpreter lock (GIL). This means you can only have concurrency with threads and not true parallelism as long it concerns Python bytecode. Your example is mainly benchmarking a specific CPU-bound workload-performance (running a calculation within a tight loop), something you wouldn't use threads for anyway. If you want to measure creation overhead you must strip anything but creation itself from your benchmark (as far possible). TL; DR Starting up a thread (benchmarked on Ubuntu 18.04) is many times cheaper than starting up a process. Compared to thread start-up, process start up with specified start_methods takes: fork: ~33x longer forkserver: ~6693x longer spawn: ~7558x longer Full results at the bottom. Benchmark I recently upgraded to Ubuntu 18.04 and tested start up with a script that hopefully is closer to the truth. Note this code is Python 3. Some utilities for formatting and comparing the test results: # thread_vs_proc_start_up.py import sys import time import pandas as pd from threading import Thread import multiprocessing as mp from multiprocessing import Process, Pipe def format_secs(sec, decimals=2) -&gt; str: """Format subseconds. Example: &gt;&gt;&gt;format_secs(0.000_000_001) # Out: '1.0 ns' """ if sec &lt; 1e-6: return f"{sec * 1e9:.{decimals}f} ns" elif sec &lt; 1e-3: return f"{sec * 1e6:.{decimals}f} µs" elif sec &lt; 1: return f"{sec * 1e3:.{decimals}f} ms" elif sec &gt;= 1: return f"{sec:.{decimals}f} s" def compare(value, base): """Return x-times relation of value and base.""" return f"{(value / base):.2f}x" def display_results(executor, result_series): """Display results for Executor.""" exe_str = str(executor).split(".")[-1].strip('\'&gt;') print(f"\…
downvote count: 0

http://stackoverflow.com/comment/91460141
score: 0
comment on: http://stackoverflow.com/q/52256445
type: Comment
type: QuestionComment
has text: Your first if compares a single day against each list of days, not against the days in the lists. And a day can never be a list of days

http://stackoverflow.com/q/52119711
upvote count: 1
has title: ‘List’ object not callable for dict string: integer
type: Question
has comment: http://stackoverflow.com/comment/91190428
has answer: http://stackoverflow.com/a/52119931
score: -2
has body: I’m encountering this issue where I have a dict: map-x-to-y = {} and fill it with values such as map-x-to-y[some-string] = counter. But afterwards, If i try to call sorted I keep on getting ‘list’ object not callable error. I tried with OrderedDict and with sorted and none of this works. Also, I checked the type of map-x-to-y and it is ‘dict’. My goal is to sort map-x-to-y in a descending order by value.
linked to: http://stackoverflow.com/q/16772071
answer count: 1
has comment: http://stackoverflow.com/comment/91190862
has comment: http://stackoverflow.com/comment/91190402
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91190449
has comment: http://stackoverflow.com/comment/91191244
has comment: http://stackoverflow.com/comment/91190420
downvote count: 3

http://stackoverflow.com/a/52214816
has body: One can click a link without seeing its content simply by using following line of code: browser.find_element_by_xpath("//li[@class='next']/a").click()
type: Answer
answers question: http://stackoverflow.com/q/52179181
score: 0

http://stackoverflow.com/a/52184415
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91318556
answers question: http://stackoverflow.com/q/52184372
has comment: http://stackoverflow.com/comment/91318926
has comment: http://stackoverflow.com/comment/91318467
upvote count: 2
has body: You can use a generator expression with in str.join to remove all uppercase letters, which are enumerated in string.ascii_uppercase from string import ascii_uppercase def remove_capitals(a_string): return ''.join(i for i in a_string if i not in ascii_uppercase) &gt;&gt;&gt; print(remove_capitals("A1B2C3D")) 123 &gt;&gt;&gt; print(remove_capitals("Georgia Institute of Technology")) eorgia nstitute of echnology
type: Answer
has comment: http://stackoverflow.com/comment/91318750
has comment: http://stackoverflow.com/comment/91318475

http://stackoverflow.com/q/52181927
score: 0
answer count: 3
tagged with: python-3.x
tagged with: python
possible better answer: http://stackoverflow.com/a/52182080
type: AnsweredQuestion
has title: How to post to the endpoint: /myproject/notification/{nId}
has answer: http://stackoverflow.com/a/52182105
accepted answer: http://stackoverflow.com/a/52182105
tagged with: post
tagged with: urllib
type: Question
has body: I need to send the notification to the endpoint (websockets configured). This notification should be sent from Python 3: POST /myproject/notification/{nId} I found some examples how to send Json data, but I only need to send the notification id nId import urllib.request import json data = {'ids': [1, 2, 3]} myurl = "localhost" req = urllib.request.Request(myurl) req.add_header('Content-Type', 'application/json; charset=utf-8') jsondata = json.dumps(data) jsondataasbytes = jsondata.encode('utf-8') req.add_header('Content-Length', len(jsondataasbytes)) response = urllib.request.urlopen(req, jsondataasbytes) How can I do the same for POST /myproject/notification/{nId}? I tried this code, but it failed. data = 1 myurl = "localhost/myproject/notification/" req = urllib.request.Request(myurl) req.add_header('Content-Type', 'application/json; charset=utf-8') jsondata = json.dumps(data) I would prefer to use requests library instead of urllib. r = requests.post("localhost/myproject/notification/", data=1) print(r.status_code, r.reason)
has answer: http://stackoverflow.com/a/52182080
has answer: http://stackoverflow.com/a/52182259

http://stackoverflow.com/comment/91261290
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52155522
score: 2
has text: You need Python 2.7 to run this code, not 3.x. The nr of parameters of the translate function has changed.

http://stackoverflow.com/a/69740609
type: Answer
has body: Using the async version of render (called arender) should work for this situation.
score: 0
answers question: http://stackoverflow.com/q/52167670

http://stackoverflow.com/a/52131742
has body: The other answers are correct and provide the best way to do it, but I realized that you wrote: print calls provided as part of an exercise: not my implementation print(same_person(person1, person2)) print(same_person(person1, person3)) The exercise probably wants you to define a function outside the class. You can do that by removing that function from the class and writing it un-indented outside the class (without providing class type too). For example: class Person: def __init__(self, name, age, id): self.name = name self.age = age self.id = id def same_person(lhs, rhs): return lhs.id == rhs.id person1 = Person("David Joyner", 30, 901234567) person2 = Person("D. Joyner", 29, 901234567) person3 = Person("David Joyner", 30, 903987654) print(same_person(person1, person2)) print(same_person(person1, person3))
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91214059
has comment: http://stackoverflow.com/comment/91214007
has comment: http://stackoverflow.com/comment/91213999
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52131569
type: Answer
accepted answer of: http://stackoverflow.com/q/52131569

http://stackoverflow.com/a/52209763
type: Answer
score: 1
upvote count: 1
has body: A nifty way to write the functions you need would be with list comprehension and dict comprehension. See here for how these work : https://www.smallsurething.com/list-dict-and-set-comprehensions-by-example/ The code could look like this : def title_id(the_list): return {id: title for (id, title) in [(i["id"], i["title"]) for i in the_list]} As for your error around list_category, I bet one of the dicts in your list doesn't have that key. To see what's going on, use try-except and print val in the case of a key error.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52209389
accepted answer of: http://stackoverflow.com/q/52209389

binary-tree
tag name: binary-tree
tags question: http://stackoverflow.com/q/52134538
type: Tag
tags question: http://stackoverflow.com/q/52194723

http://stackoverflow.com/q/52171326
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52173851
score: 1
has answer: http://stackoverflow.com/a/52173851
has answer: http://stackoverflow.com/a/52171367
downvote count: 1
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/52171367
has title: Django order by primary key does not work
favorite count: 0
upvote count: 2
tagged with: django
tagged with: python
has body: I have a model as below: class Photos(models.Model): id = models.IntegerField(primary_key=True, default=1) name = models.CharField(max_length=500) size = models.IntegerField() path = models.CharField(max_length=500) date = models.DateField(default=datetime.now) def __str__(self): return self.date.strftime('%Y-%m-%d') class Meta: verbose_name_plural = "Photos" I want to retrieve the last primary key from the database (postgresql) as below: try: last_inserted = Photos.objects.order_by('-id')[0] print(last_inserted) except IndexError: print("No data in the database") but instead of a primary key I always get a date from the date column which is really strange! printing the last_inserted gives me '2018-09-04'. As a test I change the 'id' column to lang (does not exists in table) gives below error message: Cannot resolve keyword 'lang' into field. Choices are: date, id, name, path, size in the above message why date is coming first then id and so on ..! please help!

http://stackoverflow.com/comment/91410178
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52229957
has text: Thank for the precision. I did not think about the differences that might exist between OSes.
type: AnswerComment

http://stackoverflow.com/comment/91265879
comment on: http://stackoverflow.com/q/52157535
type: QuestionComment
has text: Well, you've add a decorator and a `yield` before the await due to how the decorator works. Anyway, some of us prefer the [curio](https://curio.readthedocs.io/en/latest/#the-big-question-why) way. :-)
score: 0
type: Comment

http://stackoverflow.com/comment/91407410
score: 0
has text: Yeah, the design is definitely wrong here, you're right about that. We converted a normal cron to a managed cron without thinking it further, our goal was to catch silent exceptions and it didn't occur to us that we should just do it differently and avoid all this overcomplication. Thanks for your input! (and yes, that's indeed `envoyer_argent` module, simplified)
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52209618

http://stackoverflow.com/a/52133902
answers question: http://stackoverflow.com/q/52133734
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91218833
has comment: http://stackoverflow.com/comment/91218433
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91218774
has body: If you want combined output for your two links you need to use request.meta (not tested): def parse_quotes(self,response): # first you need to get ALL links you want to process your_links = response.xpath('//*[@class="event"]/a/@href').extract() first_link = your_links.pop(0) # and start processing from the very first link yield scrapy.Request(url = first_link, callback = self.parse_data, meta={"links": your_links}) def parse_data(self,response): item = {} # If we already have some Item data we need to continue with it if "item" in response.meta: item = response.meta["item"] # Below you need to parse HTML and update your Item Data = response.xpath('//*[@class="no-overflow"]/p/text()').extract() for item in zip(Data): item = { 'Data':item[0], } # Now we need to check if we need to process other Links if len(response.meta["links"]) &gt; 0: next_link_url = response.meta["links"].pop(0) yield scrapy.Request(url = next_link_url, callback = self.parse_data, meta={"links": response.meta["links"], "item": item}) else: # No more links to process, just save output yield item
has comment: http://stackoverflow.com/comment/91218938
upvote count: 1
has comment: http://stackoverflow.com/comment/91218170
type: Answer
has comment: http://stackoverflow.com/comment/91219098
has comment: http://stackoverflow.com/comment/91218184
accepted answer of: http://stackoverflow.com/q/52133734

http://stackoverflow.com/q/52196509
has comment: http://stackoverflow.com/comment/91343254
favorite count: 0
has comment: http://stackoverflow.com/comment/91344282
tagged with: python
has title: How to convert a 3D numpy array into a 3D sparse matrix in Python?
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/7922487
has answer: http://stackoverflow.com/a/52197622
upvote count: 5
has body: I have a 3D NumPy array that I want to convert to a 3D sparse matrix in Python. I looked up scipy.sparse module and only found 2D sparse matrix implementations. For example, Input: array([[[0], [0], [1], [0], [1], [0], [0]], [[1], [0], [1], [0], [0], [0], [0]]]) Output: (0,0,2) 1 (0,0,4) 1 (0,1,0) 1 (0,1,2) 1 How would do this?
has comment: http://stackoverflow.com/comment/91342263
tagged with: scipy
type: Question
tagged with: numpy
score: 5
has comment: http://stackoverflow.com/comment/91342286
answer count: 1
downvote count: 0

http://stackoverflow.com/q/52265151
type: Question
accepted answer: http://stackoverflow.com/a/52265229
has answer: http://stackoverflow.com/a/52265394
possible better answer: http://stackoverflow.com/a/52265394
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
has body: I have a data set with a date range from January 12th to August 3rd of 2018 with some values: The dimensionality of my_df DataFrame is: my_df.shape (9752, 2) Each row contains half hour frequency The first row begins at 2018-01-12 my_df.iloc[0] Date: 2018-01-12 00:17:28 Value 1 Name: 0, dtype: object And the last row ending at 2018-08-03 my_df.tail(1) Date: Value 9751 2018-08-03 23:44:59 1 My goal is to select the data rows corresponding to each day and export it to a CSV file. To get only the January 12th data and save to readable file, I perform: # Selecting data value of each day my_df_Jan12 = my_df[(my_df['Fecha:']&gt;='2018-01-12 00:00:00') &amp; (my_df['Fecha:']&lt;='2018-01-12 23:59:59') ] my_df_Jan12.to_csv('Data_Jan_12.csv', sep=',', header=True, index=False) From January 12 to August 03 there are 203 days (28 weeks) I don't want to perform this query by each day manually, then I am trying the following basic analysis: I need to generate 203 files (1 file by each day) The day on January starting on 12 (January 12) January is the first month (01) and August is the eighth month(08) Then: I need to iterate over the 203 days totality and is necessary in each date row value check the month and day value date with the order to check the change of each one of them According to the above, I am trying this approach: # Selecting data value of each day (203 days) for i in range(203): for j in range(1,9): # month for k in range(12,32): # days of the month values = my_df[(my_df['Fecha:']&gt;='2018-0{}-{} 00:00:00'.format(j,k)) &amp; (my_df['Fecha:']&lt;='2018-0{}-{} 23:59:59'.format(j,k))] values.to_csv('Values_day_{}.csv'.format(i), sep=',', header=True, index=False) But I have the problem in the sense of when I iterate of range(12,32) in the days of the months, this range(12,32) only apply to first January month, I think so ... Finally, I get 203 empty CSV files, due to something I am doing wrong ... How to can I address this small challenge of the suited way? Any ori…
tagged with: extract
has answer: http://stackoverflow.com/a/52265229
tagged with: python
has title: Extracting data belonging to a day from a given range of dates on a dataset
type: AnsweredQuestion
score: 3
upvote count: 3

http://stackoverflow.com/q/52237276
has title: NoReverseMatch at /ProjektAJ/songs/ Reverse for 'songs' with arguments '('all',)' not found. 1 pattern(s) tried: ['ProjektAJ\\/songs/$']
tagged with: django
has comment: http://stackoverflow.com/comment/91424089
tagged with: python
has comment: http://stackoverflow.com/comment/91423329
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91423828
type: Question
has comment: http://stackoverflow.com/comment/91423663
has body: I would like to return list of all songs in my project from my local sqlite HTML file &lt;li class="{% block songs_active %}{% endblock %}"&gt; &lt;a href="{% url 'ProjektAJ:songs' %}"&gt; &lt;span class="glyphicon glyphicon-music" aria-hidden="true"&gt;&lt;/span&gt;&amp;nbsp; Songs &lt;/a&gt; &lt;/li&gt; urls.py url(r'^songs/$', views.SongsView.as_view(), name='songs'), views.py class SongsView(generic.ListView): template_name = 'ProjektAJ/songs.html' context_object_name = 'all_songs' def get_queryset(self): return Song.objects.all() models.py class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) song_title = models.CharField(max_length=250) is_favorite = models.BooleanField(default=False) def get_absolute_url(self): return reverse('ProjektAJ:index') def __str__(self): return self.song_title I have error like below NoReverseMatch at /ProjektAJ/songs/ Reverse for 'songs' with arguments '('all',)' not found. 1 pattern(s) tried: ['ProjektAJ\\/songs/$'] Request Method: GET Request URL: http://127.0.0.1:8000/ProjektAJ/songs/ Django Version: 2.0.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'songs' with arguments '('all',)' not found. 1 pattern(s) tried: ['ProjektAJ\\/songs/$'] Exception Location: G:\Python\Python36-32\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 636 Python Executable: G:\Python\Python36-32\python.exe Python Version: 3.6.3 Python Path: ['C:\\Users\\Adrian Skibiński\\ProbaDjango\\django_projekt', 'G:\\Python\\Python36-32\\python36.zip', 'G:\\Python\\Python36-32\\DLLs', 'G:\\Python\\Python36-32\\lib', 'G:\\Python\\Python36-32', 'G:\\Python\\Python36-32\\lib\\site-packages'] Server time: Sat, 8 Sep 2018 16:29:51 +0000 Could you tell me what I do wrong in this case?
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52237759
has answer: http://stackoverflow.com/a/52242472

http://stackoverflow.com/comment/91411190
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52230682
has text: @abarnet Interesting. I may try this if nothing else works. I would just add my code at the bottom of this `sets` code or call this code as a module if I can get fancy in WLST/Jython. Thank-you for the cool idea.
score: 0

http://stackoverflow.com/comment/91275578
score: 0
type: AnswerComment
type: Comment
has text: @OkorimiManoury I misspelled the function, see my edit.
comment on: http://stackoverflow.com/a/52158180

http://stackoverflow.com/comment/91300229
comment on: http://stackoverflow.com/a/52171210
type: AnswerComment
score: 0
type: Comment
has text: Ahhh ok here is were I'm having trouble: I want to be able to use this loop on lists of different sizes. when p and b are not the same list size as x and y, I get an index out of range error. for example if p = [[17, 16, 6, 15, 6, 7, 6, 7, 9, 11], [16, 13, 9, 11, 12, 13, 6, 12, 13, 7]] and b = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]]

http://stackoverflow.com/a/52112920
answers question: http://stackoverflow.com/q/52112774
has body: result_dict={} for i in range(0,len(a),2): result_dict[a[i]]=a[i+1] output : {'sam': '25', 'matt': '30', 'jack': '27'}
score: 0
type: Answer

http://stackoverflow.com/a/52266828
downvote count: 0
score: 1
has body: Because . is a regex special character so put '\' front of it then it will be good: Solution: df['column'].str.replace('\.','') Example: df['column']=df['column'].str.replace('\.','') print(df) Output: column 0 Sam M
has comment: http://stackoverflow.com/comment/91481532
has comment: http://stackoverflow.com/comment/91481555
answers question: http://stackoverflow.com/q/52266756
upvote count: 1
has comment: http://stackoverflow.com/comment/91481534
type: Answer

http://stackoverflow.com/comment/91446964
score: 2
type: AnswerComment
type: Comment
has text: @6seven8: not really. The Tkinter `OptionMenu` also takes the default value as the first parameter. In `Tkinter` it's a positional parameter, in ttk it's a keyword parameter.
comment on: http://stackoverflow.com/a/52249373

http://stackoverflow.com/comment/91368443
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52194717
has text: @HenryWoody Not yet, I'm still trying these different methods
score: 0

http://stackoverflow.com/a/52251174
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52251117
downvote count: 0
has body: The problem is that each time you remove an element, you make the list shorter, but keep your position from the loop constant. Essentially you skip over every other element when removing in a loop like this. Consider the example a = [1,2,3]. On the first iteration, you remove 1. So a becomes [2,3] and you move your position to the second element, which is now 3, so you've skipped 2. How you can fix it is by filtering with a list comprehension. Here's an example: a = [2, 3, 4, 5, 10, 12, 13, 17, 1234, 4321, 12345, 13579] filtered = [x for x in a if not any(digit in str(x) for digit in '02468')]
type: Answer

http://stackoverflow.com/comment/91181143
comment on: http://stackoverflow.com/a/52113275
score: 0
type: AnswerComment
has text: @Sid - Yes, I understand. Is not possible first create all combination like my answer and then filtering?
type: Comment

http://stackoverflow.com/a/52159038
answers question: http://stackoverflow.com/q/52158793
has comment: http://stackoverflow.com/comment/91268355
downvote count: 0
has comment: http://stackoverflow.com/comment/91268308
has comment: http://stackoverflow.com/comment/91268613
has comment: http://stackoverflow.com/comment/91269530
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91268627
has comment: http://stackoverflow.com/comment/91268461
has comment: http://stackoverflow.com/comment/91268559
has body: Here you go: d = {'message': [{'name': 'raghav', 'id': 10}, {'name': 'raghav', 'id': 11}]} #loop over outer dictionary for key, value in d.items(): d[key] = [dict([t for k in value for t in k.items()])] print(d) Edit: As per your requirement: d = {'message': [ {'name': 'raghav', 'id': 11}, {'name': 'krish', 'id': 20}, {'name': 'anu', 'id': 30}]} for key, value in d.items(): print [dict((k1,v1)) for k1,v1 in dict([tuple(i.items()) for i in value for val in i.items()]).items()]
score: 1

http://stackoverflow.com/comment/91451778
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52250268
has text: Could you show the full Python code of how you called `CoreNLPParser`? Otherwise there's not enough information to figure why that's happening.

http://stackoverflow.com/q/52230886
has comment: http://stackoverflow.com/comment/91471538
type: Question
has body: I'm looking for a way to easily do a Pandas aggregation across a rolling window. For example, 90-day rolling daily, or 12-month rolling monthly. If I want to calculate a monthly average, I can very easily do something like data.groupby([pd.Grouper(freq='M')]).agg({'value': 'mean', 'count': 'sum'}). However, in this case, I want to calculate the average over all observations in the preceding year period, reported monthly (or 30- or 90-day period, aggregated daily). I don't want to average the averages (e.g., from a resample), as some aggregations like geometric means would not be calculated correctly. Is there a slick, idiomatic way of doing this? Everything I've done so far has been a few dozen lines of code duplicating a section of the data frame for each chunk, and I feel like there has to be something cleaner/faster. Thanks!
has comment: http://stackoverflow.com/comment/91445238
has comment: http://stackoverflow.com/comment/91411317
has comment: http://stackoverflow.com/comment/91480924
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/91480460
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91521965
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Python/Pandas groupby with lookback window
has comment: http://stackoverflow.com/comment/91430651

http://stackoverflow.com/q/52227559
tagged with: selenium
accepted answer: http://stackoverflow.com/a/52227870
has title: How to get labels of elements by their IDs with Selenium Webdriver with Python?
type: Question
has body: I have drop-downs that have assigned IDs and each of them has a name visible in the UI. Below is an example. The ID of the drop-down is Filter_Comparison, its label in the UI is 'Primary Comparison', and the label is described as Primary Comparison . How can I grab the text of that label by the ID that it is assigned to? Sure enough the following is not going to work as it is going to give the text of the option that is currently selected in the drop-down (in this case it is 'Benchmark Focused'): browser.find_element_by_id(`Filter_Comparison`).text
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52227870
tagged with: python
has comment: http://stackoverflow.com/comment/91405084
tagged with: selenium-webdriver
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91404722

eigenvector
tags question: http://stackoverflow.com/q/52225659
tag name: eigenvector
type: Tag

http://stackoverflow.com/a/52119934
upvote count: 0
score: -2
answers question: http://stackoverflow.com/q/52119760
type: Answer
has comment: http://stackoverflow.com/comment/91191089
downvote count: 2
has body: In the first line, you created an empty dictionary and assigned it to “adict”. You need to separate each key-value pair with commas and make sure that your keys do not have quotation Mars. Only the values have quotation marks (if they are strings). adict = { “a”: “apple”, “b”: “balloon” }
has comment: http://stackoverflow.com/comment/91191043

http://stackoverflow.com/comment/91257370
type: Comment
has text: How can i write 'options = [f' {name} ' for index, value in enumerate( months )]' with the use of '%s' operator ? could we please just use a for to create the selection menu? This line is nice but its complex.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52152222

http://stackoverflow.com/comment/91221044
has text: It seems you have not placed the `extras.py`.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52135589

http://stackoverflow.com/comment/91227632
type: QuestionComment
type: Comment
has text: @Cut7er that is not what i'm trying to do. please see edited description. thanks.
comment on: http://stackoverflow.com/q/52138737
score: 0

http://stackoverflow.com/q/52156515
has answer: http://stackoverflow.com/a/65990942
tagged with: python
has answer: http://stackoverflow.com/a/52156954
answer count: 4
tagged with: pythonanywhere
has title: Flask-SQLAlchemy session object not seeing changes to the database?
upvote count: 3
has comment: http://stackoverflow.com/comment/91263951
has comment: http://stackoverflow.com/comment/91263385
has comment: http://stackoverflow.com/comment/91263593
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/91263837
has comment: http://stackoverflow.com/comment/91263934
linked to: http://stackoverflow.com/q/19143345
has answer: http://stackoverflow.com/a/76350860
accepted answer: http://stackoverflow.com/a/52156954
has body: I have a website on PythonAnywhere that uses Flask and Flask-SQLAlchemy connected to a MySQL database. Users can use the website to queue a task that is saved to the database as a record in a table, and then a separate scheduled task (Python program) checks the database and handles every unhandled record. The problem I'm encountering is that the scheduled task's db query seems to only find new records when it runs for the first time, but if I then use the website to add a new task, the still-running scheduled task's recurring db queries (every 5 seconds) don't seem to detect the new record. Any ideas about what could be happening here? Here's the code being run by the bash file: def generate_any_pending_videos(): unfinished_videos = db.session.query(Video)\ .filter(~Video.status.has(VideoStatus.status.in_(['Error', 'Finished', 'Video deleted'])))\ .order_by(Video.datetime_created)\ .all() for video in unfinished_videos: try: logging.info("Attempting to create video for video %d" % video.id) generate_video(video) except Exception as e: logging.error(str(e)) if __name__ == '__main__': while True: generate_any_pending_videos() time.sleep(5)
has comment: http://stackoverflow.com/comment/91263451
tagged with: mysql
has comment: http://stackoverflow.com/comment/91263642
type: Question
possible better answer: http://stackoverflow.com/a/52157442
has comment: http://stackoverflow.com/comment/91263654
has answer: http://stackoverflow.com/a/52157442
has comment: http://stackoverflow.com/comment/91263399
downvote count: 0
has comment: http://stackoverflow.com/comment/91263455
has comment: http://stackoverflow.com/comment/91263667
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
has comment: http://stackoverflow.com/comment/91264012

http://stackoverflow.com/comment/91219452
has text: I am not sure REPL is self-explanatory for a beginner.
score: 0
comment on: http://stackoverflow.com/a/52134409
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/91355584
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52174607
has text: @HarmanThind Please check the code now, I have made a minor fix. It should be able to work well now.
score: 0

reindex
tag name: reindex
tags question: http://stackoverflow.com/q/52242955
type: Tag

http://stackoverflow.com/q/52140247
downvote count: 1
tagged with: scipy
has answer: http://stackoverflow.com/a/52141580
type: Question
score: 3
has body: Currently learning about computer vision and machine learning through the free online course by stanford CS131. Came across some heavy math formulas and was wondering if anyone could explain to me how one would go on about in implementing a naive 4 nested for loops for the convolution algorithm using only knowing the image height, width and kernel height and width. I was able to come up with this solution by researching online. image_padded = np.zeros((image.shape[0] + 2, image.shape[1] + 2)) image_padded[1:-1, 1:-1] = image for x in range(image.shape[1]): # Loop over every pixel of the image for y in range(image.shape[0]): # element-wise multiplication of the kernel and the image out[y, x] = (kernel * image_padded[y:y + 3, x:x + 3]).sum() I was able to understand this based on some website examples using this type of algorithm however, I can't seem to grasp how a 4 nested for loops would do it. And if you could, break down the formula into something more digestible then the given mathematical equation found online. Edit: Just to clarify while the code snippet I left works to a certain degree I'm trying to come up with a solution that's a bit less optimized and a bit more beginner friendly such as what this code is asking: def conv_nested(image, kernel): """A naive implementation of convolution filter. This is a naive implementation of convolution using 4 nested for-loops. This function computes convolution of an image with a kernel and outputs the result that has the same shape as the input image. Args: image: numpy array of shape (Hi, Wi) kernel: numpy array of shape (Hk, Wk) Returns: out: numpy array of shape (Hi, Wi) """ Hi, Wi = image.shape Hk, Wk = kernel.shape out = np.zeros((Hi, Wi)) ### YOUR CODE HERE ### END YOUR CODE return out
has title: Naive Implementation of Convolution algorithm
upvote count: 4
answer count: 1
accepted answer: http://stackoverflow.com/a/52141580
favorite count: 0
tagged with: convolution
tagged with: python
tagged with: computer-vision
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91250681
tagged with: image-processing

http://stackoverflow.com/a/52248384
type: Answer
answers question: http://stackoverflow.com/q/52248287
downvote count: 1
has comment: http://stackoverflow.com/comment/91445007
upvote count: 0
has comment: http://stackoverflow.com/comment/91445380
score: -1
has body: Off the top of my head there are two ways to do this. Say you have the string mystr = 'some text...content:"67588978"'. The first way is just to search for "content:" in the string and use string slicing to take everything after it: num = mystr[mystr.index('content:"') + len('content:"'):-1] Alternatively, as probably a better solution, you could use regular expressions import re nums = re.findall(r'.*?content:\"(\d+)\"') As you haven't provided an example of the dataset you're trying to analyze, there could also be a number of other solutions. If you're trying to parse a JSON or YAML file, there are simple libraries to turn them into python dicts (json is part of the standard library, and PyYaml handles YAML files easily).

http://stackoverflow.com/q/52264767
type: AnsweredQuestion
has title: Jupyterhub Custom Authenticator
type: Question
accepted answer: http://stackoverflow.com/a/52395020
score: 0
answer count: 1
tagged with: authenticator
has body: I am a little stuck with writing a custom authenticator for jupyterhub. Most probably because I do not understand the inner workings of the available REMOTE_USER authenticator. I am not sure if it is applicable in my case... anyhow... this is what I'd like to do: My general idea: I have a server that authenticates a user with his or her institutional login. After logging into the institution server/website, the users' data are encoded -- only some details to identify the user. They are then redirected to a the jupyterhub domain in the following way https://&lt;mydomain&gt;/hub/login?data=&lt;here go the encrypted data&gt; Now, if a request gets sent like this to my jupyterhub-domain, I'd like to decrypt the submitted data, and authenticate the user. My trial: I tried it with the following code. But it seems I am too nooby... :D So please, pedantic comments are welcome :D from tornado import gen from jupyterhub.auth import Authenticator class MyAuthenticator(Authenticator): login_service = "my service" authenticator_login_url="authentication url" @gen.coroutine def authenticate(self,handler,data=None): # some verifications go here # if data is verified the username is returned My first problem... clicking the button on the login page, doesn't redirect me to my Authentication URL... it seems the variable authenticator_login_url from the login template is set somewhere else... Second problem... a request made to .../hub/login?data=... is not evaluated by the authenticator (it seems...) So: Has somebody any hints for me how to go about this? As you see I followed the tutorials here: https://universe-docs.readthedocs.io/en/latest/authenticators.html
has answer: http://stackoverflow.com/a/52395020
tagged with: python
tagged with: jupyterhub

http://stackoverflow.com/comment/91293105
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52171013
has text: @Prune This is NOT about imputing missing data. I've gone to a lot of effort to explain exactly what the issue is. This is a problem faced by many many people, and I think the lack of an obvious solution is what keeps many people stuck in proprietary software like Stata and unable to switch to pandas. If you think an answer to my question is easily findable, I've be very grateful for a link!
score: 0

http://stackoverflow.com/a/52137973
type: Answer
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/52137200
has comment: http://stackoverflow.com/comment/91226032
has comment: http://stackoverflow.com/comment/91226166
has comment: http://stackoverflow.com/comment/91226207
upvote count: 3
has body: You can use a list comprehension with enumerate and zip: res = [a[idx, start: end] for idx, (start, end) in enumerate(zip(start_idx, end_idx))] # [array([2, 3]), array([7, 8])] This is similar to @Bazingaa's solution, but iterates over start_idx / end_idx directly rather than positional list indexing. The performance benefit is marginal and may only become apparent for large arrays. However, you may find the enumerating logic more readable. n = 100000 a = np.array([[1,2,3,4], [5,6,7,8]]*n) start_idx = [1,2] * n end_idx = [3,4] * n def indexing(a, start_idx, end_idx): return [a[i, start_idx[i]:end_idx[i]] for i in range(len(start_idx))] def enumerating(a, start_idx, end_idx): return [a[idx, start: end] for idx, (start, end) in enumerate(zip(start_idx, end_idx))] %timeit indexing(a, start_idx, end_idx) # 140 ms %timeit enumerating(a, start_idx, end_idx) # 124 ms
has comment: http://stackoverflow.com/comment/91225848
has comment: http://stackoverflow.com/comment/91226099

http://stackoverflow.com/a/52230096
score: 5
upvote count: 5
downvote count: 0
has body: Another option is to convert the column to string and use str.match: print(df[df['ID'].astype(str).str.match("\d+")]) # Course ID #0 Test 0 #1 Math 2 Your code does not work, because as stated in the docs for pandas.DataFrame.filter: Note that this routine does not filter a dataframe on its contents. The filter is applied to the labels of the index.
type: Answer
answers question: http://stackoverflow.com/q/52229998

http://stackoverflow.com/comment/91459096
comment on: http://stackoverflow.com/a/52207984
has text: One more question : How to pass a variable from this javascript to python function?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91396261
has text: I think there's a few small omissions, but generally if it doesn't work it should be considered a bug. You should try to get a minimal example to show the issue then submit it to the [Cython issue tracker](https://github.com/cython/cython/issues)
comment on: http://stackoverflow.com/q/52222374
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/91356992
has text: Share some minimal dataframes to reproduce the problem or to find a solution
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52203981
score: 0

http://stackoverflow.com/comment/91643107
type: Comment
type: QuestionComment
has text: You can submit the answer to your own question since you have found the solution.
comment on: http://stackoverflow.com/q/52181099
score: 0

http://stackoverflow.com/q/52240846
has body: I am using Python to scrape through a webpage and then download its table data, elements, and store them in file as JSON. Afterwards, I use PHP to process that data and display it in a table: <?php $file_content = file_get_contents("./file.txt"); $decoded_json = json_decode($file_content); // $decoded_json becomes an array with 72 elements (each of the elements is a string) ?> Each row of the table where I got data from has 24 columns. Basically I have 3 rows now (72 elements in an array). I need to create 3 and 24 for each row - dynamically because each time number of rows I scrape may change. Also, I need to add next to 18th, 21st, and 24th column in my table. Here is what I have so far (it looks at least somewhat close to what I want to achieve): <?php $i = 0; while ($i <= count($decoded_json)) { if ($i % 24 === 0) { echo " $decoded_json[$i] "; $i++; } else { if ($i % 18 === 0 || $i % 21 === 0 || $i % 24 === 0) { echo " $decoded_json[$i] "; echo ' '; // It does not echo checkboxes correctly because of $i. $i++; } else { echo " $decoded_json[$i] "; $i++; } } } ?> Questions: Is this a feasible approach at all? If yes: How can I make sure only 1 row is created for each 24 elements in an array (even if my array consists of thousands of elements)? Right now 1 row is created for each 23 elements, and 1st element of 24 is always left out. How can I add a checkbox next to 18th, 21st, and 24th column of each row? Because I increment $i on every iteration, number is growing, but I guess I have to keep it between 1-24 for every row. If no: Which approach would you recommend to use? I prefer PHP. P.S. I hope I was clear. If not, please ask for clarification. My title may look vague but I did not know how to specify my question in 1 sentence. Edit (replying to @ggorlen comment): Here is the file content: ["first", "768.51", "4,680", "0", "0%", "0", "0", "0%", "0", "0", "0%", "0", "0.00", "0.00%", "2", "0", "0%", "0", "0.00", "0.00%", "1", "768.51", "100.00%", "4,677", "second…
answer count: 1
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/91430827
favorite count: 0
has title: Display different HTML elements based on array's index
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/52241754
score: 2
has comment: http://stackoverflow.com/comment/91430636
upvote count: 2
tagged with: web-scraping
tagged with: php
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52241754
type: Question

http://stackoverflow.com/q/52157372
score: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91265124
type: UnansweredQuestion
tagged with: python
has body: This is my first post so be easy on me :) I have a simple python 2.7 script that creates a window using overrideredirect(1). That all works well and good, the canvas I add works, but when I add a label and apply its height and width, it is severely elongated on both axes. this occurs for both the title bar and quits labels. I want to get them thinner, but I can't use floats. Any ideas what is happening? Here is my code: from Tkinter import * from math import * class Main(): def __init__(self): # Create a basic tkinter window self.root = Tk() self.canvas = Canvas(self.root, width=700, height=500) self.canvas.pack() # Start function that creates labels self.initiate() # Make the window frameless self.root.overrideredirect(1) self.root.mainloop() def initiate(self): # Create a single black bar across the top of the window # My issue is here. I apply the height of 1, and it displays in the tkinter window of a height more like 10-20. # I think it has somthing to do with overrideredirect, but i dont know what it is, i have never used it before. self.titlebar = Label(self.canvas, width=700, height=1, bg='black') self.titlebar.place(x=0, y=0) # This and the other functions make the window move when you drag the titlebar. It is a replacement for the normal title bar i removed with overrideredirect. self.titlebar.bind("&lt;ButtonPress-1&gt;", self.StartMove) self.titlebar.bind("&lt;ButtonRelease-1&gt;", self.StopMove) self.titlebar.bind("&lt;B1-Motion&gt;", self.OnMotion) # Create a quit button in top left corner of window self.quit = Label(self.canvas, width=1, height=1, bg='grey') self.quit.place(x=0, y=0) self.quit.bind("&lt;Button-1&gt;", lambda event: self.root.destroy()) def StartMove(self, event): self.x = event.x self.y = event.y def StopMove(self, event): self.x = None self.y = None def OnMotion(self, event): deltax = event.x - self.x deltay = event.y - self.y x = self.root.winfo_x() + deltax y = self.root.winfo_y() + deltay self.root.geometry("+%s+%s" % (x, y)) Main…
has comment: http://stackoverflow.com/comment/91265493
tagged with: tkinter
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91265289
type: Question
has answer: http://stackoverflow.com/a/52157599
has title: Label is resizing incorrectly tkinter
tagged with: label
tagged with: python-2.7

multithreading
tags question: http://stackoverflow.com/q/52210549
tags question: http://stackoverflow.com/q/52237668
tags question: http://stackoverflow.com/q/52123967
type: Tag
tags question: http://stackoverflow.com/q/52199882
tags question: http://stackoverflow.com/q/52199619
tags question: http://stackoverflow.com/q/52188071
tags question: http://stackoverflow.com/q/52212844
tags question: http://stackoverflow.com/q/52203012
tags question: http://stackoverflow.com/q/52160366
tags question: http://stackoverflow.com/q/52154510
tags question: http://stackoverflow.com/q/52161904
tags question: http://stackoverflow.com/q/52184465
tags question: http://stackoverflow.com/q/52168347
tags question: http://stackoverflow.com/q/52241904
tags question: http://stackoverflow.com/q/52137974
tags question: http://stackoverflow.com/q/52161449
tags question: http://stackoverflow.com/q/52219672
tags question: http://stackoverflow.com/q/52247576
tags question: http://stackoverflow.com/q/52138489
tags question: http://stackoverflow.com/q/52180384
tags question: http://stackoverflow.com/q/52253095
tags question: http://stackoverflow.com/q/52175375
tags question: http://stackoverflow.com/q/52210274
tags question: http://stackoverflow.com/q/52242966
tags question: http://stackoverflow.com/q/52221874
tags question: http://stackoverflow.com/q/52153912
tags question: http://stackoverflow.com/q/52117268
tags question: http://stackoverflow.com/q/52150175
tags question: http://stackoverflow.com/q/52245829
tags question: http://stackoverflow.com/q/52156425
tags question: http://stackoverflow.com/q/52154496
tags question: http://stackoverflow.com/q/52178374
tags question: http://stackoverflow.com/q/52237227
tags question: http://stackoverflow.com/q/52179191
tag name: multithreading
tags question: http://stackoverflow.com/q/52126831

http://stackoverflow.com/a/52117903
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91187692
has comment: http://stackoverflow.com/comment/91188749
answers question: http://stackoverflow.com/q/52117739
downvote count: 0
type: Answer
has body: I have already seen some nice answers here, however, here is also an explanation of why these work. Explanation Lets break this question down, first lets take a look at how we can see if a string contains P -: string_a = 'P - tag1' string_b = 'A - tag2' 'P -' in string_a # yields True 'P -' in string_b # yields False Now we check whether any item in a list contains an item for which P - in item is True. We loop over a list with list comprehension: lst = ['P - tag1', 'A - tag2', 'P - tag2', ' B - tag1', 'P - tag3'] any(['P -' in item for item in lst]) # Yields True because there are items containing 'P -' Next we apply this to all our nested lists and count the number of items in your list using sum() sum(any(['P -' in item for item in lst]) for lst in a)

http://stackoverflow.com/comment/91384022
score: 0
type: AnswerComment
type: Comment
has text: Does it automatically sync files (once run; no need to run again) or Do we have to run each time to sync local and remote ?
comment on: http://stackoverflow.com/a/52217608

http://stackoverflow.com/comment/91417382
type: QuestionComment
score: 0
has text: I have the admin rights. Yet when I tried using conda commands in Anaconda prompt to install packages it fails. The same with pip. The network doesn't allow the installation I believe. When i try it with my personal laptop at home everythiing works fine. It is just the office system that doesn't allow installation using conda and pip
comment on: http://stackoverflow.com/q/52136897
type: Comment

http://stackoverflow.com/comment/91181310
type: QuestionComment
comment on: http://stackoverflow.com/q/52115086
has text: @VineethSai the code works fine
score: 0
type: Comment

http://stackoverflow.com/comment/91221131
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52135589
has text: ok, but where do I place it, I tried putting it in both the `"include_files"` and adding `"include":["extras.py"],`, neither worked`

http://stackoverflow.com/comment/91323144
has text: @Jundiaius ```Updated Now ```
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52186556

http://stackoverflow.com/a/52209835
accepted answer of: http://stackoverflow.com/q/52209563
has body: Better use Popen from the subprocess module. I also included the strategy from How to terminate a python subprocess launched with shell=True to fix issues with killing the process: import os import signal import subprocess import time from subprocess import PIPE, Popen p = Popen("sleep 1; echo 1", shell=True, stdout=PIPE, preexec_fn=os.setsid) WAIT = 0.5 started = time.time() # do some other work for WAIT seconds: while time.time() &lt; started + WAIT: print("do something else") time.sleep(.1) print("kill") try: os.killpg( os.getpgid(p.pid), signal.SIGTERM ) except ProcessLookupError: # process possibly died already pass print(p.stdout.read()) You can set WAIT to 1.5 to let the process complete, in this case you will see the output from echo.
has comment: http://stackoverflow.com/comment/91503911
has comment: http://stackoverflow.com/comment/91501668
has comment: http://stackoverflow.com/comment/91503507
answers question: http://stackoverflow.com/q/52209563
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91501351
score: 2
upvote count: 2

http://stackoverflow.com/comment/91439086
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52245364
has text: can you post sample of two rows

http://stackoverflow.com/a/52181069
accepted answer of: http://stackoverflow.com/q/52175943
answers question: http://stackoverflow.com/q/52175943
has body: You can specify the folder in your python file containing the image like "folder/giftest.gif". Here is a sample: from tkinter import * root = Tk() canvas = Canvas(root, width=500, height=500) canvas.pack() imagetest = PhotoImage(file="folder/subfolder/giftest.gif") #python file is not in "folder" but "folder" is in your python file directory canvas.create_image(250, 250, image=imagetest) root.mainloop()
downvote count: 0
has comment: http://stackoverflow.com/comment/91336885
has comment: http://stackoverflow.com/comment/91355941
has comment: http://stackoverflow.com/comment/91336507
type: AcceptedAnswer
score: 1
type: Answer
upvote count: 1

http://stackoverflow.com/q/52176478
score: 1
type: Question
answer count: 2
tagged with: pandas
has body: I have a dataframe below that contains mapping between french to english df1 french english ksjks an sjk def ssad sdsd And another dataframe columns are in french so need to convert them into english by using df1 df2 ksjks sjk ssad 2 4 6 how can we achieve that? new_cols = [] for col in df2.columns: if col in df1['french']: how to get corresponding english value PS: Have just put random data in for sample
downvote count: 0
has answer: http://stackoverflow.com/a/52176488
favorite count: 0
accepted answer: http://stackoverflow.com/a/52176488
tagged with: python
possible better answer: http://stackoverflow.com/a/52176661
has answer: http://stackoverflow.com/a/52176661
upvote count: 1
has title: How to check if value exists in another dataframe in pandas?
type: AnsweredQuestion

http://stackoverflow.com/q/52159619
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91858100
has comment: http://stackoverflow.com/comment/91427953
answer count: 0
has comment: http://stackoverflow.com/comment/91395818
has comment: http://stackoverflow.com/comment/91685248
type: Question
has title: Train/validation split with a predefined mixture of target variable
tagged with: cross-validation
tagged with: train-test-split
has comment: http://stackoverflow.com/comment/91451820
has comment: http://stackoverflow.com/comment/91355591
score: 0
has comment: http://stackoverflow.com/comment/91429490
has body: I want to be able to make train/validation splits with a user-defined mixture of target variable. StratifiedKFold and StratifiedShuffleSplit from sklearn keep the mixture from the original sample. But on kaggle or in real life we often have a separate test sample that sometimes can have a very different target mixture. Let's imagine that we have a binary classification problem at hand, but the labeled train sample has 50/50 mixture of 0/1 target vvalues, while the test does not have labels, but from one or another source we know that the proportion is rather 90/10. So the question is if there is a method in sklearn to get a split of the original sample with 90/10 mixture, where 90/10 would be an input argument. It does not have to be a complete kfold CV split, but at least a cross-validation index generator ala StratifiedShuffleSplit
has comment: http://stackoverflow.com/comment/91395597
tagged with: scikit-learn

http://stackoverflow.com/comment/91603914
has text: Seems like `cv2.merge` is not compatible with tensorflow tensors. Try to use [`tensorflow.stack`](https://www.tensorflow.org/api_docs/python/tf/stack) instead (or [`keras.backend.stack`](https://www.tensorflow.org/api_docs/python/tf/keras/backend/stack) alternatively).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52212704

http://stackoverflow.com/q/52163309
duplicate of: http://stackoverflow.com/q/14856953
has comment: http://stackoverflow.com/comment/91276116
has body: Here is the code: name1 = input("Please enter a name: ") name1age = int(input("Please enter ", name1, "'s age: ")) name2 = input("Please enter a name: ") name2age = int(input("Please enter ", name2, "'s age: ")) name3 = input("Please enter a name: ") name3age = int(input("Please enter ", name3, "'s age: ")) name4 = input("Please enter a name ") name4age = int(input("Please enter ", name4, "'s age: ")) I want the value given for the name to be part of the new input. Here is the error I'm recieving: Traceback (most recent call last):# File "\\albyn-sch\data\PupilHome\A.Shahrivar\My Documents\Computing Science\Python\Dance Group.py", line 2, in &lt;module&gt; name1age = int(input("Please enter ", name1, "'s age: ")) TypeError: input expected at most 1 arguments, got 3 Any help? Thanks.
score: 0
tagged with: printing
answer count: 2
has answer: http://stackoverflow.com/a/52163335
tagged with: string
possible better answer: http://stackoverflow.com/a/52163510
has answer: http://stackoverflow.com/a/52163510
tagged with: input
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52163335
has title: How to add strings and text into an input in Python?
linked to: http://stackoverflow.com/q/14856953
type: Question

http://stackoverflow.com/a/56169836
downvote count: 0
score: 10
answers question: http://stackoverflow.com/q/52217911
upvote count: 10
has body: I assume that your Dataframe has a DatetimeIndex. If so, I prefer this approach from daily to monthly returns: df.resample('M').agg(lambda x: (x + 1).prod() - 1) But you can also apply for another frequency. For example, for weekly returns last Friday: df.resample('W-FRI').agg(lambda x: (x + 1).prod() - 1)
type: Answer

http://stackoverflow.com/comment/91185671
type: QuestionComment
comment on: http://stackoverflow.com/q/52116711
type: Comment
has text: Check that the xml files in your module are well formed xml. It is hard to answer or comment more because you did not provide much content from your module or the xml data inside module. If the problem persist, please include more information.
score: 0

http://stackoverflow.com/comment/98612567
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52148908
has text: @VictorVal I don't think your problem is same as mine if the response is taking long time, debug your code to find bottlenecks. For me, I did a sort of hack whereby I created a sample fake method in the view and called it externally multiple times so that all the workers are started.
type: Comment

http://stackoverflow.com/q/52165025
has comment: http://stackoverflow.com/comment/91279431
type: Question
has answer: http://stackoverflow.com/a/52165103
has comment: http://stackoverflow.com/comment/91279460
has body: I got a tuple called records records =(['foo', 1]),(['bar', 'hello']) This is the Expected_result expected_result= (['foo','bar'],['1','hello']) I created a For loop for the above and its doing well for i in range(len(records[0])): for k in range(len(records[1])): if i==k: j,v = records print(j[i],v[i]) Is there any better way to do this using minimum code and lines ? Regards
tagged with: tuples
score: 0
answer count: 3
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52165082
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: How to do unpack this nested tuple in better way?
downvote count: 1
tagged with: list
has answer: http://stackoverflow.com/a/52165246

http://stackoverflow.com/a/52239358
has comment: http://stackoverflow.com/comment/91432281
has body: tf.squeeze is a method that removes dimensions of size 1 from the tensor. If the end goal is to have the input shape as [None,64], then put a line similar to inputs = tf.squeeze(inputs) and that would fix your problem.
has comment: http://stackoverflow.com/comment/91441308
has comment: http://stackoverflow.com/comment/91441735
upvote count: 2
has comment: http://stackoverflow.com/comment/91440483
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52168247
has comment: http://stackoverflow.com/comment/91598141
downvote count: 1

http://stackoverflow.com/q/52226310
score: 0
possible better answer: http://stackoverflow.com/a/52227065
answer count: 2
has comment: http://stackoverflow.com/comment/91402499
has body: I know about np.eye which generates identity matrix. This question is about the algorithm rather than about the final result. In Q (kdb+ language) I can generate identity matrix using the following code: `float${x =\: x} til 12000 Python numpy equivalent is more or less this: import numpy as np r=np.arange(12000) np.asarray([i==r for i in r]).astype(float) With Python approach there's an unnecessary data copying during np.asarray to convert Python array back into numpy array. Is there a way to avoid this copying? I.e. I want to perform [i==r for i in r] without getting out of numpy domain.
tagged with: numpy
has title: Algorithm in Python equivalent to Q to manually generate identity matrix
tagged with: array-broadcasting
type: AnsweredQuestion
tagged with: kdb+
type: Question
has answer: http://stackoverflow.com/a/52226560
tagged with: python
has answer: http://stackoverflow.com/a/52227065
has comment: http://stackoverflow.com/comment/91402907
accepted answer: http://stackoverflow.com/a/52226560

http://stackoverflow.com/comment/91315345
score: 0
type: AnswerComment
type: Comment
has text: They're actual processes, not threads, but they behave like this.
comment on: http://stackoverflow.com/a/52179264

http://stackoverflow.com/comment/91244016
comment on: http://stackoverflow.com/a/52126706
type: AnswerComment
score: 0
type: Comment
has text: I saw the documenation https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot

http://stackoverflow.com/a/52188316
upvote count: 2
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91326960
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52188203
has body: One-liner df.loc[df.index.repeat(df.profile_id.str.count(', ') + 1)].assign( profile_id=', '.join(df.profile_id).split(', ')) profile_id user birthday 0 123 test1 day1 0 124 test1 day1 1 131 test2 day2 1 132 test2 day2 Broken down sep = ', ' idx = df.index.repeat(df.profile_id.str.count(sep) + 1) new = sep.join(df.profile_id).split(sep) df.loc[idx].assign(profile_id=new) profile_id user birthday 0 123 test1 day1 0 124 test1 day1 1 131 test2 day2 1 132 test2 day2 Numpy slice instead of loc also get a fresh index sep = ', ' col = 'profile_id' p = df[col] i = np.arange(len(df)).repeat(p.str.count(sep) + 1) pd.DataFrame({ col: sep.join(p).split(sep), **{c: df[c].values[i] for c in df if c != col} }, columns=df.columns) profile_id user birthday 0 123 test1 day1 1 124 test1 day1 2 131 test2 day2 3 132 test2 day2
answers question: http://stackoverflow.com/q/52188203

http://stackoverflow.com/a/52210269
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52209617
has body: You can do it with list comprehensions in one line: myTuple = (u'Columns', [{u'Type': u'string', u'Name': u'recon_c+c'}, {u'Type': u'string', u'Name': u'data'}, {u'Type': u'string', u'Name': u'nui'}, {u'Type': u'bigint', u'Name': u'typ'}]) myList = [ print (x["Name"]+" " + x["Type"]) for x in myTuple[1] ] Output: recon_c+c string data string nui string typ bigint Of course you can format print any way you want.

http://stackoverflow.com/comment/91216741
type: QuestionComment
comment on: http://stackoverflow.com/q/52131612
has text: Side note, never name a variable after a built-in, e.g. use `list_` or `L` instead of `list`.
score: 0
type: Comment

http://stackoverflow.com/comment/91944486
comment on: http://stackoverflow.com/a/52267214
score: 0
type: AnswerComment
type: Comment
has text: @NewNY1990 sorry, less on the site for a while and I forgot to give a try. I think you don't look at the right date, I indeed get -8 for a and b Scen 1 but for April 10, where val for a is 18 and for b is 10, so good figure. When using this method, it seems that `df_res` is sort by date (not sure why like this). I understand why it's confusing though, the sum is the same for both date :)

http://stackoverflow.com/q/52267267
type: Question
has body: import time def classBase(class_name, class_health, class_damage, class_hit_chance): print("You are a " + class_name + "!") def enemyBase(enemy_name, enemy_health, enemy_damage, enemy_hit_chance, enemy_alive): time.sleep(2) print("Out of nowhere, a " + enemy_name + " appears!") enemy_total_health = enemy_health print("Welcome to Blades of Goblonia!") user_name = input("What is your name?") type(user_name) print("Hello, " + user_name + "!") user_class_choice = input("""What class would you like to be? A) Warrior B) Hunter C) Wizard""") if user_class_choice == "A" : user_class = classBase("Warrior", 50, 7, 95) elif user_class_choice == "B" : user_class = classBase("Hunter", 40, 10, 85) elif user_class_choice == "C" : user_class = classBase("Wizard", 35, 12, 80) enemyBase("Goblin", 30, 10 , 60, True) time.sleep(1) user_action_choice = input("""Would you like to A) Hit B) Run C) Heal""") if user_action_choice == "A" : print("Hit") elif user_action_choice == "B" : print("Run") elif user_action_choice == "C" : print("Heal") In my game code, I'm trying to access and alter the health of enemyBase as it changes when I re-create it. To create a damage, effect, I need to change the value of enemy_total_health, but I can not reference the variable. How would I write my code to be able to access the local variables and parameters? Thanks :)
has answer: http://stackoverflow.com/a/52267591
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/52267511
favorite count: 0
tagged with: python-3.x
tagged with: python
has title: Accessing Parameters and Variables Made in a Function Outside of it (Python)
possible better answer: http://stackoverflow.com/a/52267511
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52267440
accepted answer: http://stackoverflow.com/a/52267440

http://stackoverflow.com/a/72263825
has body: If you would like to use SQL and the BigQuery console you can do as follows: 1) Query the INFORMATION_SCHEMA to find all tables that you would like to delete and create a DROP TABLE statement around that, like this: SELECT 'DROP TABLE ' || 'your_project_id.' || table_schema || '.' || table_name || ';' FROM `your_project_id.your_dataset.INFORMATION_SCHEMA.TABLES` WHERE table_name LIKE 'your_table_name_202202%' ORDER BY table_name ASC; 2) The result of this query will look like this: DROP TABLE your_project_id.your_dataset.sales.__am-123; DROP TABLE your_project_id.your_dataset.sales.__am-134; etc etc 3) Now copy the result of this query to the clipboard. 4) Then paste that to a new query and run that to drop all the tables. See also here: Delete BigQuery tables with wildcard
upvote count: 5
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52151185
score: 5

http://stackoverflow.com/comment/91410900
has text: Side note, don't shadow class names, use `lst` or `L` instead of `list`. I've updated the question for you.
comment on: http://stackoverflow.com/q/52230596
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91204203
type: Comment
has text: @zvone: pip is the python package manager.
score: 1
comment on: http://stackoverflow.com/q/52126660
type: QuestionComment

http://stackoverflow.com/comment/91411739
type: Comment
has text: Thanks this pretty much did it! I just changed the last line to: return Data.objects.filter(author__customer_Tag=self.request.user.customer_Tag)
comment on: http://stackoverflow.com/a/52229970
score: 0
type: AnswerComment

http://stackoverflow.com/q/52154496
tagged with: opencv
has comment: http://stackoverflow.com/comment/91259211
upvote count: 5
answer count: 2
score: 5
downvote count: 0
has title: How can I start a thread from a Kivy button?
has answer: http://stackoverflow.com/a/52154788
favorite count: 0
has body: Not sure if anyone can help me with this. I have been unable to find a simple answer to this anywhere. I am building a GUI in Kivy which shows the webcam feed (using openCV) and has two buttons (Button A and B). When I press Button A, it calls a function which does something. However, my screen and GUI freezes as the called function is executing. How to I implement the function called by the button press to run on a different thread in python?
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/52154628
type: UnansweredQuestion
tagged with: multithreading
type: Question

http://stackoverflow.com/a/52206554
upvote count: 2
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91362637
has body: For the nested list example, you can do the following, making use of itertools.permutations and dict.setdefault: from itertools import permutations list3 = [[2, 3], [2, 3, 4]] d = {} for l in list3: for a, b in permutations(l, 2): d[a][b] = d.setdefault(a, {}).setdefault(b, 0) + 1 # {2: {3: 2, 4: 1}, 3: {2: 2, 4: 1}, 4: {2: 1, 3: 1}} For flat lists l, use only the inner loop and omit the outer one
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52206196
answers question: http://stackoverflow.com/q/52206196

vscode-debugger
type: Tag
tags question: http://stackoverflow.com/q/52240227
tags question: http://stackoverflow.com/q/52252269
tag name: vscode-debugger

http://stackoverflow.com/comment/91296636
type: QuestionComment
score: 0
has text: This doesn't directly answer your question but I think you could benefit from some information on nodes: https://www.tutorialspoint.com/python/python_nodes.htm
comment on: http://stackoverflow.com/q/52172821
type: Comment

http://stackoverflow.com/comment/91367664
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52208227
type: AnswerComment
has text: It works!! but is there a better way to append spaces between the index assuming I have 50+ variables I need to append spaces in between?

http://stackoverflow.com/comment/91192285
has text: @roganjosh I don't know what that means
type: Comment
comment on: http://stackoverflow.com/q/52120479
type: QuestionComment
score: 0

http://stackoverflow.com/q/52259473
downvote count: 0
has answer: http://stackoverflow.com/a/52259953
tagged with: oracle-database
has title: ORA-01722: invalid number - Python with cx_Oracle
tagged with: python
favorite count: 0
score: 2
tagged with: python-3.x
upvote count: 2
accepted answer: http://stackoverflow.com/a/52259953
possible better answer: http://stackoverflow.com/a/52259948
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52259948
tagged with: bind-variables
type: Question
answer count: 2
has body: I have the below script inserting into an Oracle database. If I manually put all the passed in values into an INSERT statement and run the hardcoded statement in Python the INSERT works but for some reason when I use the below way it always fails with an ORA-01722: invalid number. I thought it was original the datetime value so I tried TO_DATE(TO_CHAR(:9, 'YYYY-MM-DD HH24:MI:SS'), 'YYYY-MM-DD HH24:MI:SS'), it didn't make any difference. Spent ages trying different suggestions from SO and the internet but no luck as of yet. data = ['NULL', 'NULL', 'NULL', 'NULL', '2', 'Test Text', 'NULL', 'NULL', '2017-06-02 16:00:00', '20180910122315440220.csv'] conn = cx_Oracle.connect(env.DB_USER, env.DB_PASSWORD,cx_Oracle.makedsn(env.DB_HOST, env.DB_PORT, env.DB_NAME)); # Disable auto commit. conn.autocommit = False cursor = conn.cursor() sql = """INSERT INTO TESTDB (TESTDB_ID, TESTDB_ACYR_CODE, TESTDB_SEM_CODE, TESTDB_MODULEID, TESTDB_STU_PIDM, TESTDB_COMPONENT_ID, TESTDB_COMPONENT_NAME, TESTDB_GRADE_MARK, TESTDB_GRADER_PIDM, TESTDB_GRADE_MODIFIED_DATE, TESTDB_CREATION_DATE, TESTDB_FILENAME, TESTDB_ACTIVITY_DATE, TESTDB_USER_ID) VALUES(TESTDB_SEQ.NEXTVAL, :1, :2, :3, :4, :5, :6, :7, :8, TO_DATE(:9, 'YYYY-MM-DD HH24:MI:SS'), SYSDATE, :10, SYSDATE, USER)""" cursor.prepare(sql) cursor.execute(sql, data) conn.commit() cursor.close() # Enable auto commit. conn.autocommit = True conn.close()
tagged with: cx-oracle

http://stackoverflow.com/comment/98247249
comment on: http://stackoverflow.com/q/52209306
has text: Not possible to debug without the whole program, including the constants.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91244322
comment on: http://stackoverflow.com/a/52146662
type: AnswerComment
score: 0
type: Comment
has text: I think it is OK if you have to import something at runtime. If you want something more sophisticated or general, you should consider building your own package (which is a different question :) )

http://stackoverflow.com/a/52167305
upvote count: 2
has body: Because all pokemons are saved in a list which is under keyword results, so you firstly need to get that list and then iterate over it. for result in json_obj['results']: print(result['name'])
type: Answer
answers question: http://stackoverflow.com/q/52167187
score: 2
downvote count: 0

http://stackoverflow.com/q/52215897
has title: Django project reported an error after release with nginx and uwsigi
upvote count: 2
has answer: http://stackoverflow.com/a/52216552
answer count: 1
downvote count: 1
favorite count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 1
has body: After I enter the domain name for access, the browser displays the Internal Server Error,In addition, I checked the log and got the following Error information,I would appreciate it if anyone could give me some advice Thu Sep 6 18:02:36 2018 - unable to load app 0 (mountpoint='') (callable not found or import error) Thu Sep 6 18:02:36 2018 - --- no python application found, check your startup logs for errors --- {address space usage: 180469760 bytes/172MB} {rss usage: 6373376 bytes/6MB} [pid: 9609|app: -1|req: -1/7] 10.8.0.7 () {48 vars in 827 bytes} [Thu Sep 6 18:02:36 2018] GET /favicon.ico =&gt; generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0) My django project directory structure： [root@openvpn conf]# ll /var/www/EWP_OMS total 56 drwxr-xr-x 2 www www 4096 Sep 6 15:24 AUTH drwxr-xr-x 3 www www 4096 Sep 6 15:24 CMDB drwxr-xr-x 3 www www 4096 Sep 6 11:43 COBBER drwxr-xr-x 2 www www 4096 Sep 6 18:01 EWP_OMS -rw-r--r-- 1 www www 250 Jul 22 2016 manage.py drwxr-xr-x 4 www www 4096 Sep 4 15:28 media drwxr-xr-x 4 www www 4096 Sep 6 15:24 pagination -rw-r--r-- 1 www www 7603 Jul 22 2016 README.md -rw-r--r-- 1 www www 34 Sep 4 17:49 requirements.txt drwxr-xr-x 3 www www 4096 Sep 6 15:25 SALT drwxr-xr-x 6 www www 4096 Sep 4 15:28 static drwxr-xr-x 6 www www 4096 Sep 4 15:28 templates drwxr-xr-x 3 www www 4096 Sep 6 15:25 ZABBIX [root@openvpn conf]# ls /var/www/EWP_OMS/EWP_OMS/ config.ini __init__.py __init__.pyc settings.py settings.pyc urls.py urls.pyc wsgi.py wsgi.pyc wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "EWP_OMS.settings") application = get_wsgi_application() uwsgi.ini: [uwsgi] uid = www gid = www socket = 0.0.0.0:9000 master = true pidfile = /usr/local/nginx-1.6.3/uwsgi.pid processes = 8 chdir = /var/www/EWP_OMS/ pythonpath = /var/www/EWP_OMS_ENV profiler = true memory-report = true enable-threads = true logdate = true limit-as = 6048 daemonize = /va…
tagged with: uwsgi
type: Question
accepted answer: http://stackoverflow.com/a/52216552
tagged with: nginx

http://stackoverflow.com/q/52231121
has comment: http://stackoverflow.com/comment/91412211
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91411804
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91412268
tagged with: python
has body: I'd like to plot two profiles through the highest intensity point in a 2D numpy array, which is an image of a blob (i.e. a line through the semi-major axis, and another line through the semi-minor axis). The blob is rotated at an angle theta counterclockwise from the standard x-axis and is asymmetric. It is a 600x600 array with a max intensity of 1 (at only one pixel) that is located right at the center at (300, 300). The angle rotation from the x-axis (which then gives the location of the semi-major axis when rotated by that angle) is theta = 89.54 degrees. I do not want to use scipy.ndimage.rotate because it uses spline interpolation, and I do not want to change any of my pixel values. But I suppose a nearest-neighbor interpolation method would be okay. I tried generating lines corresponding to the major and minor axes across the image, but the result was not right at all (the peak was far less than 1), so maybe I did something wrong. The code for this is below: import numpy as np import matplotlib.pyplot as plt from scipy import ndimage def profiles_at_angle(image, axis, theta): theta = np.deg2rad(theta) if axis == 'major': x_0, y_0 = 0, 300-300*np.tan(theta) x_1, y_1 = 599, 300+300*np.tan(theta) elif axis=='minor': x_0, y_0 = 300-300*np.tan(theta), 599 x_1, y_1 = 300+300*np.tan(theta), -599 num = 600 x, y = np.linspace(x_0, x_1, num), np.linspace(y_0, y_1, num) z = ndimage.map_coordinates(image, np.vstack((x,y))) fig, axes = plt.subplots(nrows=2) axes[0].imshow(image, cmap='gray') axes[0].axis('image') axes[1].plot(z) plt.xlim(250,350) plt.show() profiles_at_angle(image, 'major', theta) Did I do something obviously wrong in my code above? Or how else can I accomplish this? Thank you. Edit: Here are some example images. Sorry for the bad quality; my browser crashed every time I tried uploading them anywhere so I had to take photos of the screen. Figure 1: This is the result of my code above, which is clearly wrong since the peak should be at 1. I'm not sure what …
has comment: http://stackoverflow.com/comment/91412258
has comment: http://stackoverflow.com/comment/91412316
upvote count: 1
tagged with: scipy
has title: Generate profiles through a 2D array at an angle without altering pixels
type: Question
has comment: http://stackoverflow.com/comment/91412382
score: 1
has comment: http://stackoverflow.com/comment/91412302
linked to: http://stackoverflow.com/q/7878398
tagged with: numpy
has comment: http://stackoverflow.com/comment/91411924
has comment: http://stackoverflow.com/comment/91412222
has answer: http://stackoverflow.com/a/52231617
answer count: 1
tagged with: arrays
has comment: http://stackoverflow.com/comment/91412470
downvote count: 0
has comment: http://stackoverflow.com/comment/91411916
favorite count: 0
has comment: http://stackoverflow.com/comment/91411929

http://stackoverflow.com/comment/91475879
type: Comment
type: QuestionComment
has text: `input_data_df=pd.DataFrame(input_data)` This operation is redundant, input_data is already a pandas DataFrame
score: 0
comment on: http://stackoverflow.com/q/52262519

http://stackoverflow.com/comment/91287370
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52168502
has text: Doesn't look like it: https://github.com/python/cpython/blob/09b52471f39ba280d836b945d47719c697af0b45/Lib/xml/etree/ElementTree.py#L934 - why the requirement, as both are valid xml?
score: 0

http://stackoverflow.com/q/52205076
answer count: 1
favorite count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52205090
type: AnsweredQuestion
score: 1
has body: I have a pandas dataframe consiting of one column containing a string seperated by "/" I would like split these seperated strings into new columns denoted by a boolean (if they exist) d = {'col1': ["A/B/C", "B/C", "D/B/A", "C/B"]} dataFrame = pd.DataFrame(data=d) col1 0 A/B/C 1 B/C 2 D/B/A 3 C/B the result would be as following: d = {'A': [1, 0, 1, 0], 'B':[1,1,1,1], 'C':[1,1,0,1], 'D':[0,0,1,0]} dataFrame = pd.DataFrame(data=d) A B C D 0 1 1 1 0 1 0 1 1 0 2 1 1 0 1 3 0 1 1 0 I have attempted with pandas.Series.str.split and pandas.pivot but nothing quite returns the result I am looking for. Any help or nudges in the right direction, would be highly appreciated!
accepted answer: http://stackoverflow.com/a/52205090
has title: Splitting a concatenated string into seperated columns using pandas
type: Question
downvote count: 0
tagged with: pandas

http://stackoverflow.com/q/52148029
tagged with: python
type: AnsweredQuestion
has title: keras ImageDataGenerator Target data
has answer: http://stackoverflow.com/a/52148166
accepted answer: http://stackoverflow.com/a/52148166
type: Question
linked to: http://stackoverflow.com/q/59596784
tagged with: neural-network
score: 0
tagged with: deep-learning
answer count: 1
tagged with: keras
has body: According to this page we can build a generator using the ImageDataGenerator class (and flow_from_directory method) that we can pass to model.fit_generator method in keras; like this: train_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory( 'data/train', target_size=(150, 150), batch_size=32, class_mode='categorical') model.fit_generator( train_generator, steps_per_epoch=2000, epochs=50) But in the flow_from_directory method it only get the images for training from the directory and not the target labels because, while in normal model.fit method you pass the target data as a parameter, model.fit_generator accept only the generator of the training images; so where does it takes the expected output ?

http://stackoverflow.com/q/52267733
accepted answer: http://stackoverflow.com/a/52267758
type: Question
has comment: http://stackoverflow.com/comment/91483100
has body: I am trying to code to shows text that i want. this is the sample of text as follow and it's css file for html5. .table0 { border-spacing:0; } .tr1 { :176.00pt; } .table4 { border-spacing:0; } and this is what i am coding so far as follow. with open("path\\file.css","r", encoding='utf-8') as f : lines = f.readlines() n = 0 for i, line in enumerate(lines[:-1]): table = line.split('.')[-1].split(' {')[0] if table == 'table'+ str(n) : print(table) n = n + 1 this shows only table0 and i don't know why it misses table4. which part is wrong ? Thanks have a great day.
score: -1
has answer: http://stackoverflow.com/a/52267758
answer count: 1
downvote count: 1
has title: Why does this code not recognize next text (list, index)?
tagged with: parsing
favorite count: 0
has comment: http://stackoverflow.com/comment/91483091
tagged with: python
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/q/52138930
has comment: http://stackoverflow.com/comment/91228873
has comment: http://stackoverflow.com/comment/91228688
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91293323
score: -1
has answer: http://stackoverflow.com/a/52139617
upvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/1871524
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has title: writing multiple nested dictionaries on a CSV file
has body: I have a ton of dicts that I have converted from twitter JSON data. Now, I want to turn them into one .csv file. I searched the site but the solutions seem to fit dicts with very few values or dicts that already exist. In my case the number of keys is a little higher, and I also have to go through an iterative process to turn each JSON file to a dict. In other words, I want to write each of my JSON files on my .csv file as soon as I turn them into a dict file in an iterative process. Here's my code so far: json_path = "C://Users//msalj//OneDrive//Desktop//pypr//Tweets" for filename in os.listdir(json_path): with open(filename, 'r') as infh: for data in json_parse(infh): and here is a sample of my converted JSON files: {'actor': {'displayName': 'RIMarkable', 'favoritesCount': 0, 'followersCount': 0, 'friendsCount': 0, 'id': 'id:twitter.com:3847371', 'image': 'Picture_13.png', 'languages': ['en'], 'link': 'ht........ble', 'links': [{'href': 'htt.....m', 'rel': 'me'}], 'listedCount': 0, 'objectType': 'person', 'postedTime': '2007-01-09T02:53:35.000Z', 'preferredUsername': 'RIMarkable', 'statusesCount': 0, 'summary': 'The Official, Unofficial BlackBerry Weblog', 'twitterTimeZone': 'Eastern Time (US &amp; Canada)', 'utcOffset': '0', 'verified': False}, 'body': 'Jim Balsillie To Present At JP Morgan Technology Conference: Research in Motion co-CEO, Jim Balsillie,.. ht...qo', 'generator': {'displayName': 'twitterfeed', 'link': 'htt......om'}, 'gnip': {'matching_rules': [{'tag': None, 'value': '"JP Morgan"'}]}, 'id': 'tag:search.twitter.com,2005:66178882', 'link': 'ht...82', 'object': {'id': 'object:search.twitter.com,2005:66178882', 'link': 'ht.....82', 'objectType': 'note', 'postedTime': '2007-05-16T19:00:24.000Z', 'summary': 'Jim Balsillie To Present At JP Morgan Technology Conference: Research in Motion co-CEO, Jim Balsillie,.. ht......qo'}, 'objectType': 'activity', 'postedTime': '2007-05-16T19:00:24.000Z', 'provider': {'displayName': 'Twitter', 'link': 'ht......m', 'o…
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91293282
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/91228839
tagged with: twitter

http://stackoverflow.com/comment/91184614
comment on: http://stackoverflow.com/a/52116863
type: AnswerComment
has text: Ok, then just add `plt.ylim(min(y), 4)`
score: 0
type: Comment

http://stackoverflow.com/comment/91225786
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52138069
has text: Do you mean on my windows system?

http://stackoverflow.com/comment/91207186
has text: @chepner Right. I totally forgot about it. (My "P" and "O") buttons dont work well
score: 0
comment on: http://stackoverflow.com/q/52128294
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52113834
has title: Conditional removal of duplicates entries in Pandas
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52114505
accepted answer: http://stackoverflow.com/a/52114505
tagged with: python-3.x
linked to: http://stackoverflow.com/q/23667369
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52115051
score: 1
has body: How can I remove the duplicate entries in the Pandas DataFrame given below. a b c d 11216 08-08-2018 2000 SIP 40277 28-08-2018 1000 SIP 44165 02-08-2018 8000 Lump 44165 03-08-2018 5000 Lump 45845 16-08-2018 25000 Lump 45845 18-08-2018 50000 Lump 52730 13-08-2018 10000 Lump 52730 27-08-2018 10000 Lump 53390 20-08-2018 400000 Lump 56180 02-08-2018 1000 Lump 58537 11-07-2018 5000 Lump 58537 22-08-2018 2000 SIP 912813 15-08-2018 160001 Lump 912813 15-08-2018 6000 SIP 85606 16-08-2018 3500 SIP 88327 06-08-2018 5000 SIP 90240 07-08-2018 2000 SIP Desired result: a b c d 11216 08-08-2018 2000 SIP 40277 28-08-2018 1000 SIP 44165 02-08-2018 8000 Lump 45845 16-08-2018 25000 Lump 52730 13-08-2018 10000 Lump 53390 20-08-2018 400000 Lump 58537 11-07-2018 5000 Lump 912813 15-08-2018 160001 Lump 912813 15-08-2018 6000 SIP 85606 16-08-2018 3500 SIP 88327 06-08-2018 5000 SIP 90240 07-08-2018 2000 SIP The condition is: remove if a2==a1 and b2&lt;&gt;b1.
has comment: http://stackoverflow.com/comment/91209418
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91209504
has answer: http://stackoverflow.com/a/52115051
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91180467
answer count: 2
tagged with: pandas

http://stackoverflow.com/comment/91351102
type: AnswerComment
type: Comment
has text: @shivalal are you using https://github.com/slimkrazy/python-google-places
comment on: http://stackoverflow.com/a/52197710
score: 0

http://stackoverflow.com/comment/91437228
comment on: http://stackoverflow.com/q/52244425
type: Comment
has text: No, it's a column of the DataFrame. If I could change the source, I would do it.
score: 0
type: QuestionComment

http://stackoverflow.com/q/52116158
has comment: http://stackoverflow.com/comment/91185206
score: 2
has comment: http://stackoverflow.com/comment/91188199
has comment: http://stackoverflow.com/comment/91188893
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/91185105
type: Question
has answer: http://stackoverflow.com/a/52116226
has comment: http://stackoverflow.com/comment/91187932
has comment: http://stackoverflow.com/comment/91190802
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91185640
has comment: http://stackoverflow.com/comment/91188995
has title: object is added to the database without session.commit()
upvote count: 2
has comment: http://stackoverflow.com/comment/91185144
type: UnansweredQuestion
has body: I run into a weird issue using SQLAlchemy in my Flask API application, an object is inserted into the database even though the commit instruction is commented: try: new_project = model.Projects(project_name, project_desc) session.add(new_project) session.flush() session.refresh(new_project) # session.commit() response = 'OK' return response except Exception as e: logging.error("ERROR :"+str(e)) session.rollback() response = 'ERROR' session.close() return response any explications ? EDIT: here is the class Projects: from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Projects(Base, DictSerializable): __tablename__ = 'projects' id = Column(Integer, primary_key=True) name = Column(String) description = Column(String) def __init__(self, name, description=None): self.name = name self.description = description
has comment: http://stackoverflow.com/comment/91185712
has comment: http://stackoverflow.com/comment/91185138

http://stackoverflow.com/a/52217088
has body: Iterate the list s and check if element in string. Demo: data = """ Automatic Product Title Tagging Aim: To automate the process of product title tagging using manually tagged data. ROUTE OPTIMIZATION – Spring Clean Aim: Minimizing the overall travel time using optimization techniques. CUSTOMER SEGMENTATION: Aim: Develop an engine which segments and provides the score for customers based on their behavior and analyze their purchasing pattern. """ s = ['tagged', 'product title', 'tagging', 'analyze'] data = data.lower() skills = [] for i in s: if i.lower() in data: skills.append(i) print(skills) Or in a single line. skills = [i for i in s if i.lower() in data] Output: ['tagged', 'product title', 'tagging', 'analyze']
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52217036
has comment: http://stackoverflow.com/comment/91383230
has comment: http://stackoverflow.com/comment/91383818
type: Answer
has comment: http://stackoverflow.com/comment/91382795
score: 2
has comment: http://stackoverflow.com/comment/91382846
upvote count: 3
downvote count: 1
accepted answer of: http://stackoverflow.com/q/52217036

http://stackoverflow.com/comment/91300707
comment on: http://stackoverflow.com/a/52172876
has text: Eeeek. This is indeed horrible. I wonder if it is an implementation detail that `isinstance` is fooled by this.
score: 0
type: Comment
type: AnswerComment

fixtures
tags question: http://stackoverflow.com/q/52254079
type: Tag
tag name: fixtures

http://stackoverflow.com/a/75317526
answers question: http://stackoverflow.com/q/52139309
type: Answer
upvote count: 1
has body: Get and install the SYBASE ODBC DRIVER. Configure the DSN on your PC. On Windows, search for the Microsoft ODBC Administrator. Then create a DSN. Python code: using SQLAchemy import sqlalchemy as sa from sqlalchemy import create_engine, event from sqlalchemy.engine.url import URL import urllib params = urllib.parse.quote_plus('DSN=dsn_name;PWD=user_pwd') engine = sa.create_engine("sybase+pyodbc:///?odbc_connect={}".format(params)) with engine.connect() as cursor: cursor.execute(""" SELECT * FROM database """) Using PyODBC import pyodbc conn = pyodbc.connect('DSN=dsn_name;PWD=user_pwd') with conn: cursor = conn.cursor() cursor.execute(""" SELECT * FROM database """)
downvote count: 0
score: 1

http://stackoverflow.com/a/52117009
has comment: http://stackoverflow.com/comment/91203900
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: I'd say probably not, since accessing and storing subscriptions are different opcodes: &gt;&gt;&gt; dis.dis(compile('globalPythonArray[10]', 'a', 'exec')) 1 0 LOAD_NAME 0 (globalPythonArray) 2 LOAD_CONST 0 (10) 4 BINARY_SUBSCR 6 POP_TOP 8 LOAD_CONST 1 (None) 10 RETURN_VALUE &gt;&gt;&gt; dis.dis(compile('globalPythonArray[10] = myValue', 'a', 'exec')) 1 0 LOAD_NAME 0 (myValue) 2 LOAD_NAME 1 (globalPythonArray) 4 LOAD_CONST 0 (10) 6 STORE_SUBSCR 8 LOAD_CONST 1 (None) 10 RETURN_VALUE Also, insert the usual warning about user input and eval() here: globalPythonArray[__import__('os').system('rm -rf /')]
answers question: http://stackoverflow.com/q/52116906

http://stackoverflow.com/comment/91301383
score: 0
type: QuestionComment
type: Comment
has text: After `df = pd.concat(groups)`, returned with the error: " TypeError: cannot concatenate object of type "<class 'list'>"; only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are valid "
comment on: http://stackoverflow.com/q/52175248

http://stackoverflow.com/comment/91227817
comment on: http://stackoverflow.com/a/52138465
type: AnswerComment
score: 0
type: Comment
has text: I don't think this is correct answer. Using `label` raises error that `label` is not defined.

http://stackoverflow.com/q/52211190
score: 7
has comment: http://stackoverflow.com/comment/91375346
type: Question
answer count: 2
has title: Airflow, how do i run .py files via python name.py using BashOperator
tagged with: airflow
downvote count: 0
possible better answer: http://stackoverflow.com/a/52225898
has answer: http://stackoverflow.com/a/52225898
has body: I'm running Airflow using Celery and Redis it's working just fine but I'm having problems in the worker side. I have two docker-compose files, one is the master running in the server and a worker that runs in other pcs. I have dag that run python script.py but always fails because it cannot find the script. It seems like Airflow Base task runner just copies the dag file to tmp folder. my dags folder is like: dags/ test_dag.py test.py test_dag.py from airflow.models import DAG from airflow.operators.bash_operator import BashOperator from datetime import datetime, timedelta default_args = { 'owner': 'airflow', 'start_date': datetime(2018, 9, 3) } dag = DAG('test', default_args=default_args, schedule_interval='*/20 * * * *', catchup=False) curl = BashOperator( task_id='testingbash', bash_command="python test.py", dag=dag) test.py print('it worked') Error: [2018-09-06 22:30:34,832] {base_task_runner.py:107} INFO - Job 4: Subtask testingbash [2018-09-06 22:30:34,832] {cli.py:492} INFO - Running &lt;TaskInstance: test.testingbash 2018-09-06T22:00:00+00:00 [running]&gt; on host e91df5a905de [2018-09-06 22:30:39,066] {bash_operator.py:74} INFO - Tmp dir root location: /tmp [2018-09-06 22:30:39,067] {bash_operator.py:87} INFO - Temporary script location: /tmp/airflowtmprgxtunoa/testingbash_7opnm28 [2018-09-06 22:30:39,067] {bash_operator.py:97} INFO - Running command: python test.py [2018-09-06 22:30:39,079] {bash_operator.py:106} INFO - Output: [2018-09-06 22:30:39,164] {bash_operator.py:110} INFO - python: can't open file 'test.py': [Errno 2] No such file or directory [2018-09-06 22:30:39,165] {bash_operator.py:114} INFO - Command exited with return code 2 [2018-09-06 22:30:40,400] {models.py:1736} ERROR - Bash command failed Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/airflow/models.py", line 1633, in _run_raw_task result = task_copy.execute(context=context) File "/usr/local/lib/python3.6/site-packages/airflow/operators/bash_operator.py…
has answer: http://stackoverflow.com/a/53949877
tagged with: bash
has comment: http://stackoverflow.com/comment/91424739
has comment: http://stackoverflow.com/comment/91374385
favorite count: 0
tagged with: python
upvote count: 7
accepted answer: http://stackoverflow.com/a/53949877
type: AnsweredQuestion

http://stackoverflow.com/q/52175281
possible better answer: http://stackoverflow.com/a/55215503
has answer: http://stackoverflow.com/a/66850242
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91330489
has comment: http://stackoverflow.com/comment/91319386
tagged with: jetbrains-ide
tagged with: monkeyrunner
score: 0
accepted answer: http://stackoverflow.com/a/66850242
tagged with: python
tagged with: pycharm
has comment: http://stackoverflow.com/comment/91303327
has body: I want to create a new Run/Debug Configuration which executes a .bat file that accepts a Python script as a parameter. The program I want to execute is MonkeyRunner (a tool part of Android SDK) which is located in the C:\Users\talha\AppData\Local\Android\Sdk\tools\bin folder. And my PyCharm project is located in C:\Users\talha\Documents\PyCharmProjects folder.
has answer: http://stackoverflow.com/a/55215503
type: AnsweredQuestion
tagged with: monkey
has title: PyCharm - How to create a Run/Debug Configuration that executes a .bat file which uses a Python script as a parameter?

http://stackoverflow.com/comment/91380963
has text: `#!/usr/bin/python3 from cfunc import cfunc with open('v_i_m_utf8.txt', 'rb') as infile: words = 0 words = cfunc(infile) print(words)` I guess that is correct.
type: AnswerComment
comment on: http://stackoverflow.com/a/52209179
type: Comment
score: 0

http://stackoverflow.com/a/52276803
answers question: http://stackoverflow.com/q/52267314
score: 17
upvote count: 17
has comment: http://stackoverflow.com/comment/91502829
has body: I'm getting different output tensor dimensions than expected. This is due to the fact that, by default, slim.conv2d uses same padding whereas tf.layers.conv2d uses valid padding. If you want to reproduce the exact same behavior, here is the correct implementation: x = tf.layers.conv2d(x, 256, 3, padding='same')
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52267314
type: Answer

http://stackoverflow.com/comment/91332561
type: QuestionComment
comment on: http://stackoverflow.com/q/52191323
has text: correct! I want to retrieve all values except the last value of that array. The goal is to create a parent account based on the account value. So in row 68 account = 0.0.4 and parent should be 0.0.
score: 0
type: Comment

http://stackoverflow.com/comment/91398305
type: Comment
comment on: http://stackoverflow.com/a/52223033
has text: @Violatic Try doing FinalHeader1 instead of Premium and see if it works.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91344874
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52197740
has text: i have no idea how to do that as im new to python, and programming sadly

http://stackoverflow.com/comment/91259962
score: 0
type: Comment
type: QuestionComment
has text: I tested it many times on my computer, and it works fine everytime using your code. Could you check your flask and flask-socketio versions, mine are: `Flask==1.0.2 Flask-SocketIO==3.0.1`
comment on: http://stackoverflow.com/q/52154728

http://stackoverflow.com/q/52243118
score: 1
upvote count: 1
type: Question
tagged with: combinations
type: AnsweredQuestion
tagged with: python-itertools
accepted answer: http://stackoverflow.com/a/52243478
has title: Unique combinations from list with "distance limit"
answer count: 1
has body: Given the list a = ['a', 'b', 'c', 'd', 'e'], I would use itertools.combinations to get all unique combos like ['ab', 'ac', ...], as per the classic SO answer How can I limit the unique combinations to items that are not farther away than n spots? Example If I want list items no more than n=2 spots away, I would accept 'ab' and 'ac' as combinations but not 'ae', because the distance between 'a' and 'e' is greater than n=2 Edit - code Below the plain python code solution, which I'd avoid due to the double-for loop, that is not ideal for large lists a = ['a', 'b', 'c', 'd', 'e'] n_items = len(a) n_max_look_forward = 2 unique_combos = [] for i, item in enumerate(a): for j in range(i+1, min(i+n_max_look_forward+1, n_items)): unique_combos.append( item+a[j] ) print(unique_combos)
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/464864
has answer: http://stackoverflow.com/a/52243478
tagged with: python
tagged with: python-3.x

http://stackoverflow.com/comment/91283247
type: Comment
score: 0
type: AnswerComment
has text: @TryingNotToBeDumb: Exactly.
comment on: http://stackoverflow.com/a/52166339

http://stackoverflow.com/q/52197740
type: Question
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/91344796
has comment: http://stackoverflow.com/comment/91377611
has title: Segment out peak to peak of graph to get 1 period python
has comment: http://stackoverflow.com/comment/91345109
type: UnansweredQuestion
tagged with: python
has body: import matplotlib.pyplot as plt import numpy as np import pdb file = open("Data1r2.txt", 'r') lines = file.readlines() file.close() So what i am trying to get is to have the code use the data from the txt file and plot out a graph. what im stuck with is i cant figure out how to have peak detection have for the graph to show the peaks, since i need to calculate the value from 1 peak to another. t = [] z = [] y = [] x = [] for line in lines: parts = line.split(", ") if len(parts) &gt; 3: column1 = parts[3].split(':') column2 = column1[1] column3 = parts[2].split(':') column4 = column3[1] column5 = parts[1].split(':') column6 = column5[1] column7 = parts[0].split(':') column8 = column7[1] T = column2[0:len(column2)] Z = column4[0:len(column4)] Y = column6[0:len(column6)] X = column8[0:len(column8)] To set the trace T1 = float(T) t.append(T1) Z1 = float(Z) z.append(Z1) Y1 = float(Y) y.append(Y1) X1 = float(X) x.append(X1) plotting the graph plt.plot(t,z,label='z') plt.plot(t,y,label='y') plt.plot(t,x,label='x') plt.legend() plt.show() Sample of data i wanna be able to cut out the graphs peak to peak for 1 period
answer count: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91349805
has comment: http://stackoverflow.com/comment/91344874

http://stackoverflow.com/comment/91336296
comment on: http://stackoverflow.com/q/52191695
has text: Due to the edit this does not look much like a question any more. Are you sure that the "edit" should not actually be an answer?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52216806
score: 1
answers question: http://stackoverflow.com/q/52216505
accepted answer of: http://stackoverflow.com/q/52216505
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: If you can create a fixed set of child processes, i.e a set has 3/n processes and you pick a set and forward to all, then, you may consider using one multicast IP/sockets per child process set. Or if child processing overhead is not of much concern you can make all child process listen on the same multicast group, meaning all child processes gets all messages from the main process and check message parameter to decide if the message is intended for it or not. Multicast IP does Layer 2 level broadcast so the packet is sent only once on the wire and all the sockets in the multicast group read the same message at the same time.
downvote count: 0

http://stackoverflow.com/comment/91385898
type: QuestionComment
comment on: http://stackoverflow.com/q/52218538
has text: Your code example produces the second graph. You say you want something "resembling" that second graph but do not describe what you want different.
score: 0
type: Comment

http://stackoverflow.com/q/52141928
tagged with: for-loop
has title: I get the empty set when using the for loop
has answer: http://stackoverflow.com/a/52142081
score: 0
answer count: 3
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52141948
type: UnansweredQuestion
has body: I know this must be something very basic, but I dont know why I keep getting an empty set. What should I do in order to not get an empty set? s=set() for a in [(1,2),(1,3),(1,2)]: b=[] for j in range(len(a)-1): b.append(a) s.union(b) print(s) I get: s=([]) but the result I want is {(1,2),(1,3)} I know there is another way to take the union, but I wish to do so with this for loop.
tagged with: python
has answer: http://stackoverflow.com/a/52141949
tagged with: set
tagged with: loops
type: Question

http://stackoverflow.com/comment/91456189
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52252695
has text: Change `name = Type` to `name = "Type"`. Same thing with `Description` and `Location`. Where do you define the variables `type`, `description`, and `location` that you pass to keyword argument `value`?
type: Comment

cypher
tags question: http://stackoverflow.com/q/52239631
type: Tag
tag name: cypher

http://stackoverflow.com/comment/96263345
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52240106
score: 1
has text: What does one do if not all types are `tf.float32`? For instance, I have a column of type `tf.string` and another of `tf.float32`. How do I appropriately adapt `tf.convert_to_tensor`?

http://stackoverflow.com/a/52238197
accepted answer of: http://stackoverflow.com/q/52237965
type: Answer
has body: According to some sources, one is indeed able to train at least some architectures with varying input sizes. (Quora, Cross Validated) When it comes to generating an array of arrays varying in size, one might simply use a Python list of NumPy arrays, or an ndarray of type object to collect all the image data. Then in the training process, the Quora answer mentioned that only batch size 1 can be used, or one might clump several images together based on the sizes. Even padding with zeros could be used to make the images evenly sized, but I can't say much about the validity of that approach. Best of luck in your research! Example code for illustration: # Generate 10 "images" with different sizes images = [np.zeros((i+5, i+10)) for i in range(10)] images = np.array([np.zeros((i+5, i+10)) for i in range(10)]) # Or an empty array to append to images = np.array([], dtype=object)
answers question: http://stackoverflow.com/q/52237965
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91214880
score: 0
comment on: http://stackoverflow.com/q/52131978
type: Comment
type: QuestionComment
has text: @BallpointBen I *hate* when people on SO ask that. I'm trying to clean up code to make it more Pythonic. I think this is something Python can probably do, but I don't know how.

http://stackoverflow.com/a/52154412
has comment: http://stackoverflow.com/comment/91378810
has comment: http://stackoverflow.com/comment/91320405
has comment: http://stackoverflow.com/comment/91310816
has comment: http://stackoverflow.com/comment/91307494
score: 0
has comment: http://stackoverflow.com/comment/91307925
has comment: http://stackoverflow.com/comment/91389762
type: Answer
has comment: http://stackoverflow.com/comment/91317653
has body: I listed two options. First option is to plot all dataframes in one figure: def assess_rep(dataframe_list): for df in dataframe_list: a = df[df &gt; 1].sum(axis= 0).astype(int).sort_values(ascending = False) ax = a.plot(kind = 'bar') return ax you can save the figure as a png file by: ax = assess_rep(dataframe_list) ax.get_figure().savefig('all_dataframe.png') Second option is to plot every dataframe seperate and save the figure during the process: import matplotlib.pyplot as plt def asses_rep(dataframe_list): ax_list = [] counter = 1 for df in dataframe_list: print(counter) fig = plt.figure(counter) a = df[df &gt; 1].sum(axis= 0).astype(int).sort_values(ascending = False) ax = a.plot(kind='bar', fig=fig) ax_list.append(ax) ax.get_figure().savefig('single_df_%i.png'%counter) counter += 1 return ax_list
answers question: http://stackoverflow.com/q/52149415

http://stackoverflow.com/a/52191989
type: Answer
answers question: http://stackoverflow.com/q/52133437
has body: On a palindrome, the two functions are equivalent: They take same number n steps. If the palindrome breaks early on, 2nd function returns way earlier, while the 1st keeps incrementing the count till the string's last element. Example: "abcdefgh1234554321hgfedcba" -&gt; both take n steps. "bcdefgh1234554321hgfedcba" -&gt; 2nd takes 1 step and return, while 1st takes n steps.
score: 0

http://stackoverflow.com/comment/91355495
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52203186
has text: @DanielMesejo if it results in the order you want to have them, yes.

http://stackoverflow.com/q/52221983
favorite count: 0
tagged with: cpython
tagged with: python
tagged with: read-eval-print-loop
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/52318537
type: Question
score: 3
has answer: http://stackoverflow.com/a/52316109
has body: I have a python script with the following contents: # foo.py __builtins__ = 3 del __builtins__ print(int) # &lt;- this still works Curiously, executing this script with the -i flag prevents only the REPL from accessing builtins: aran-fey@starlight ~&gt; python3 -i foo.py &lt;class 'int'&gt; &gt;&gt;&gt; print(int) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'print' is not defined How come the script can access builtins, but the REPL can't?
has title: Why does deleting a global variable named __builtins__ prevent only the REPL from accessing builtins?
possible better answer: http://stackoverflow.com/a/52316109
tagged with: built-in
answer count: 2
accepted answer: http://stackoverflow.com/a/52318537
downvote count: 0

http://stackoverflow.com/q/52148667
downvote count: 1
has comment: http://stackoverflow.com/comment/91247059
favorite count: 0
has comment: http://stackoverflow.com/comment/91247144
tagged with: defaultdict
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/91247927
possible better answer: http://stackoverflow.com/a/52148826
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91247393
has body: The script needs to read input from a text/csv file but as soon as I try and implement the functionality, everything breaks. Here is my code: from collections import defaultdict #from csv import reader data = """Lions 3, Snakes 3 Tarantulas 1, FC Awesome 0 Lions 1, FC Awesome 1 Tarantulas 3, Snakes 1 Lions 4, Grouches 0""" # with open('sample_input.csv') as data: # csv = reader(data) # list_csv = [line.rstrip('\n') for line in data] data_list = data.splitlines() def splitter(row): left_team, right_team = row.split(',') return { 'left': left_team[:-2].strip(), 'left_score': int(left_team[-2:].strip()), 'right': right_team[:-2].strip(), 'right_score': int(right_team[-2:].strip()) } data_dicts = [splitter(row) for row in data_list] team_scores = defaultdict(int) for game in data_dicts: if game['left_score'] == game['right_score']: team_scores[game['left']] += 1 team_scores[game['right']] += 1 elif game ['left_score'] &gt; game['right_score']: team_scores[game['left']] += 3 else: team_scores[game['right']] += 3 print(team_scores) teams_sorted = sorted(team_scores.items(), key=lambda team: team[1], reverse=True) # for line in teams_sorted: # print(line) Also, the expected output that I need to have is: 1. Tarantulas, 6 pts 2. Lions, 5 pts 3. FC Awesome, 1 pt 3. Snakes, 1 pt 4. Grouches, 0 pts I just can't seem to figure out how to get to this step. I checked most parts of my code with print statements and it seems the dictionary is working correctly but it is not printing the last team and it's score (Grouches, 0 pts). I am currently getting this output: ('Tarantulas', 6) ('Lions', 5) ('Snakes', 1) ('FC Awesome', 1) Any help would be greatly appreciated!
type: Question
has answer: http://stackoverflow.com/a/52149428
has title: Adding keys to defaultdict of int while iterating
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91247258
has answer: http://stackoverflow.com/a/52148826
has answer: http://stackoverflow.com/a/52149029
accepted answer: http://stackoverflow.com/a/52149029
score: 0
answer count: 3
upvote count: 1

http://stackoverflow.com/a/52268135
type: Answer
answers question: http://stackoverflow.com/q/52267850
has body: Only the even (or odd) numbers need to be counted. def odds_evens(lista): even = 0 for i in lista: if i%2==0: even += 1 return (even, len(lista) - even)
score: 0

http://stackoverflow.com/q/52251993
has comment: http://stackoverflow.com/comment/91532008
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91493924
has comment: http://stackoverflow.com/comment/91466637
has answer: http://stackoverflow.com/a/52293596
has body: I have a simple one node Cassandra cluster with basic keyspace configuration that has replication_factor=1 In this keyspace, we have about 230 tables. Each table has roughly 40 columns. The writes we do to these tables are at roughly the rate of 30k writes in five minutes just once a day. I have about 6 python workers scripts that make these writes to any one table at a time and they will all continue making these writes till all 230 tables are written to for the day. The scripts use the python cassandra-driver with a simple session to make these writes. As far as the data being written here, a lot of them are nulls. Effectively, if I am right, this can be thought of as 6 concurrent connection making 30k+ entries in five minutes per day. I understand how cassandra writes and deletes work and am familiar with coordinator nodes etc. I am observing a traceback that occurs intermittently as described below: "cassandra/cluster.py", line 2030, in cassandra.cluster.Session.execute (cassandra/cluster.c:38536) app_nstablebuilder.1.69j772led82k@swarm-worker-gg37 | File "cassandra/cluster.py", line 3844, in cassandra.cluster.ResponseFuture.result (cassandra/cluster.c:80834) app_nstablebuilder.1.69j772led82k@swarm-worker-gg37 | cassandra.WriteTimeout: Error from server: code=1100 [Coordinator node timed out waiting for replica nodes' responses] message="Operation timed out - received only 0 responses." info={'consistency': 'ONE', 'required_responses': 1, 'received_responses': 0} My question has to do with how to approach solving this problem. I am unable to verify whether the problem has come out of my workers' scripts or with the Cassandra cluster itself. Should I be slowing down my workers in doing their writes? Should I run some sort of diagnostic to improve Cassandra performance? All the solutions I have read till now have to do with multinode clusters and I couldn't find one for a single node cluster. I feel like our cluster is unhealthy and that my efforts should be targe…
tagged with: cassandra-driver
tagged with: cassandra
has comment: http://stackoverflow.com/comment/91486974
has comment: http://stackoverflow.com/comment/91534945
has title: Approach to resolve Cassandra Coordinator node timeouts on writes
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52293596
type: Question

http://stackoverflow.com/q/52175020
accepted answer: http://stackoverflow.com/a/52175110
has comment: http://stackoverflow.com/comment/91300996
upvote count: 2
has comment: http://stackoverflow.com/comment/91300960
score: 2
type: AnsweredQuestion
has title: Pandas DataFrame do something if a value is string
tagged with: numbers
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/91300872
has answer: http://stackoverflow.com/a/52175110
downvote count: 0
answer count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/91301010
favorite count: 0
has comment: http://stackoverflow.com/comment/91300965
tagged with: pandas
tagged with: python
has body: I have a table with a column named 'Amount'. The cell values are mixture of numbers such as 1, 100, and 1000, and strings such as '(1000)' and '(999)' which indicates a negative value. How would I change the strings of negative values to numbers, like -1000 and -999? I don't know how to apply conditions on panda dataframes. import pandas as pd ws_actual = pd.read_excel(file_name, sheet_name=0) Project Name Amount a 1000.53 b (-100.2) c 999.83 d 99999.1 e 333.62 f (-10502.30) g (-2036.63) h 25235 i 69103 j 5923 k 6920

http://stackoverflow.com/comment/91176154
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52112847
has text: Use `zip()` instead
score: 0

http://stackoverflow.com/comment/91425532
type: AnswerComment
type: Comment
has text: @DeepSpace Yes it does? `sample` selects without replacement, so we can't end up with more of something than the population has.
comment on: http://stackoverflow.com/a/52238370
score: 1

http://stackoverflow.com/comment/91448828
has text: What is the size of each images you download and prepare to be set as wallpaper ? try to reduce the image size and resolution and test the code.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52250332
type: QuestionComment

http://stackoverflow.com/q/52249985
has comment: http://stackoverflow.com/comment/91448136
score: 9
has body: I have generated a .wav audio file containing some speech with some other interference speech in the background. This code worked for me for a test .wav file: import speech_recognition as sr r = sr.Recognizer() with sr.WavFile(wav_path) as source: audio = r.record(source) text = r.recognize_google(audio) If I use my .wav file, I get the following error: ValueError: Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format The situation slightly improves if I save this .wav file with soundfile: import soundfile as sf wav, samplerate = sf.read(wav_path) sf.write(saved_wav_path, original_wav, fs) and then load the new saved_wav_path back into the first block of code, this time I get: if not isinstance(actual_result, dict) or len(actual_result.get("alternative", [])) == 0: raise UnknownValueError() The audio files were saved as wavfile.write(wav_path, fs, data) where wav_path = 'data.wav'. Any ideas? SOLUTION: Saving the audio data the following way generates the correct .wav files: import wavio wavio.write(wav_path, data, fs ,sampwidth=2)
answer count: 3
has comment: http://stackoverflow.com/comment/96052167
tagged with: speech-recognition
has answer: http://stackoverflow.com/a/74511098
favorite count: 0
has comment: http://stackoverflow.com/comment/91448115
upvote count: 9
has comment: http://stackoverflow.com/comment/91465945
tagged with: google-api
has comment: http://stackoverflow.com/comment/113039696
has answer: http://stackoverflow.com/a/62440265
tagged with: python
has title: Python, speech_recognition tool does not recognize .wav file
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/103135606
type: Question
has comment: http://stackoverflow.com/comment/91477952
has comment: http://stackoverflow.com/comment/114808518
has answer: http://stackoverflow.com/a/52265381
accepted answer: http://stackoverflow.com/a/52265381
possible better answer: http://stackoverflow.com/a/62440265
has comment: http://stackoverflow.com/comment/103169694

http://stackoverflow.com/q/52128610
has body: hi i tried to open some data that i downloaded to my documents using pandas with python 3.7 but it doesnt work this is my code : import pandas as pd users=pd.read_csv("ml-100k/u.user",sep="|",names=["User ID","Age","Gender", "aciation" ,"zipcode"]) user.head() the eror is : FileNotFoundError: File b'ml-100k/u.user' does not exist how can it be that the file doesnt exist if i downloaded it ? thaks:)
tagged with: pandas
has answer: http://stackoverflow.com/a/52129503
answer count: 1
has title: opoening data using pandas in python 3.7
favorite count: 0
accepted answer: http://stackoverflow.com/a/52129503
tagged with: python
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/25389095
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91207734
tagged with: database

http://stackoverflow.com/a/52152086
type: Answer
has body: That doesn't look like PostScript to me, it looks like PDF. Since you are reading a PDF file that's hardly surprising! :-) Since its not PostScript, it won't have a prolog with definitions of the procedures. You can find the operator definitions in the PDF Reference Manual which can be found with a Google search. Don't read the ISO specification (which you shouldn't be able to get anyway, since its copyrighted and has to be paid for), read the Adobe specification instead, its easier. FWIW q is gsave (and Q is grestore) while cm is concat matrix (ie concat). RG is setrgbcolor. w, j and J set entries in the graphics state for linewidth, linecap and linejoin and gs is set an extended graphics state, which doesn't really have a PostScript equivalent.
upvote count: 3
has comment: http://stackoverflow.com/comment/91255920
answers question: http://stackoverflow.com/q/52149750
accepted answer of: http://stackoverflow.com/q/52149750
type: AcceptedAnswer
downvote count: 0
score: 3

http://stackoverflow.com/comment/91270388
type: AnswerComment
has text: i guess using check_call would be better in my situation then because iam dealing with larger amounts of data, though knowing how to have subprocess.pipe output to a text file would be interesting. thanks a lot for the help!
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52151071

http://stackoverflow.com/comment/91447159
type: Comment
type: QuestionComment
has text: Thanks, I didn't see that API page, I could only find the example. I will try that now and update in a minute.
comment on: http://stackoverflow.com/q/52249439
score: 0

http://stackoverflow.com/q/52207241
linked to: http://stackoverflow.com/q/18510403
possible better answer: http://stackoverflow.com/a/52207661
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
has answer: http://stackoverflow.com/a/52207658
accepted answer: http://stackoverflow.com/a/52207658
has title: Python Tkinter buttons don't pass the right argument?
type: Question
duplicate of: http://stackoverflow.com/q/18510403
has comment: http://stackoverflow.com/comment/91364775
has body: I'm trying to make a simple interface with 3 buttons, and each button should trigger an action based on its label. However, even though (I think) I'm passing the correct argument, it always passes the label of the last button. Here's a stripped-down version to show what's happening: import tkinter as tk import random class Application(tk.Frame): def __init__(self, window=None): super().__init__(window) self.labels = ['Washington','London','Paris','Rome','Berlin','Madrid'] self.buttons = [tk.Button(self),tk.Button(self),tk.Button(self)] self.pack() for k,button in enumerate(self.buttons): button.config(width=10) button.grid(row=0, column=k) self.update_buttons() def update_buttons(self): labels = list(random.sample(self.labels,3)) random.shuffle(labels) for label,button in zip(labels,self.buttons): button["text"] = label button["command"] = lambda: self.verify(label) def verify(self, label): print(f'You pressed the button with label {label}') self.update_buttons() window = tk.Tk() app = Application(window=window) app.mainloop() Why?
score: 0
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/52207661
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/52254944
has answer: http://stackoverflow.com/a/52254976
duplicate of: http://stackoverflow.com/q/22937618
has comment: http://stackoverflow.com/comment/91457869
tagged with: python
tagged with: regex
possible better answer: http://stackoverflow.com/a/52254976
type: AnsweredQuestion
has title: How do you use the sub() method with a regular expression that has an optional group?
linked to: http://stackoverflow.com/q/22937618
tagged with: option-type
type: Question
has answer: http://stackoverflow.com/a/52255395
accepted answer: http://stackoverflow.com/a/52255395
has body: I've been working on this file rename program for a few days now. I've learned a lot thanks to all of the "silly" questions those before me have asked on this site and the quality answers they have received. Well, on to my problem. My filenames are in the following format: ACP001.jpg, ACP002.jpg,... ACP010.jpg, ACP011.jpg, ACP012_x.jpg, ACP013.jpg, ACP014_x.jpg pattern = r'(ACP0)(0*)(\d+)(\.jpg)' replace = r'\3\4' So that was working fine for most of them... but then there were some that had the "_x" just before the file extension. I ammended the pattern and replacement pattern as follows pattern = r'(ACP0)(0*)(\d+)(_w)*(\.jpg)' replace = r'\3.jpg' I think I cheated by hardcoding the ".jpg" in the replace string. How would I handle these situations where the match object groups may be of varying sizes? I essentially want the last group and the third group in this example.
has comment: http://stackoverflow.com/comment/91457291
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91465451
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/52254126
favorite count: 0
has comment: http://stackoverflow.com/comment/91458759
has comment: http://stackoverflow.com/comment/109233490
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: machine-learning
has body: It's an old problem about prediction using regression exploring Gapminder data. They used "prediction space" to compute prediction. Q1. Why should I be creating "prediction space"? What is the use of it? Q2. The relation of computing predictions over the "prediction space"? import numpy as np import pandas as pd # Read the CSV file into a DataFrame: df df = pd.read_csv('gapminder.csv') The data seems like this; Country,Year,life,population,income,region Afghanistan,1800,28.211,3280000,603.0,South Asia Slovak Republic,1960,70.47800000000001,4137224,8693.0,Europe &amp; Central Asia # Create arrays for features and target variable y = df.life.values X = df.fertility.values # Reshape X and y y = y.reshape(-1,1) X = X.reshape(-1,1) # Create the regressor: reg reg = LinearRegression() # Create the prediction space prediction_space = np.linspace(min(X_fertility), max(X_fertility)).reshape(-1,1) # Fit the model to the data reg.fit(X_fertility, y) # Compute predictions over the prediction space: y_pred y_pred = reg.predict(prediction_space)
type: Question
score: 3
tagged with: linear-regression
accepted answer: http://stackoverflow.com/a/54607921
has comment: http://stackoverflow.com/comment/91456848
upvote count: 3
answer count: 2
has title: Why "prediction space" is needed?
possible better answer: http://stackoverflow.com/a/70230372
has answer: http://stackoverflow.com/a/54607921
has answer: http://stackoverflow.com/a/70230372
tagged with: scikit-learn

http://stackoverflow.com/comment/91189546
type: Comment
comment on: http://stackoverflow.com/q/52119004
score: 0
type: QuestionComment
has text: Hi... How can I do it? I'm really new with Docker.

http://stackoverflow.com/q/52235389
tagged with: pandas
has answer: http://stackoverflow.com/a/52235777
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52235777
tagged with: matplotlib
has title: Plotting 2 data frames after merging
tagged with: dataframe
type: Question
possible better answer: http://stackoverflow.com/a/52235472
has answer: http://stackoverflow.com/a/52235472
has body: I have 2 different data frames that have the same column called date. Now, I want to plot these data frames where the values on X axis be the date column common to both the data frames and Y axis be the value. Also, I want to do this after concatenating both the data frames into a third frame. Currently here is what I did: df1 = pd.DataFrame({'value': [1,2,3,4,5], 'date': [20,40,60,80,100]}) df2 = pd.DataFrame({'value': [11,21,31,41,51], 'date': [20,40,60,80,100]}) df3 = pd.concat([df1, df2], keys=['df1','df2'], axis=1) df3.plot() plt.show() but the resultant plot is not what I wanted. It generates 4 plots as could be seen from the legend. How could I just have 2 plots with a common X axis and the difference reflected in the Y axis? Please note that I want to do this after concatenating the data frames df1 and df2 and by calling plot on df3
score: 0
answer count: 2

http://stackoverflow.com/q/52222812
score: -4
has answer: http://stackoverflow.com/a/52223004
upvote count: 1
type: Question
downvote count: 5
accepted answer: http://stackoverflow.com/a/52223004
has comment: http://stackoverflow.com/comment/91394496
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91394602
has comment: http://stackoverflow.com/comment/91394324
tagged with: python
has comment: http://stackoverflow.com/comment/91394411
has title: List index out of bound
type: AnsweredQuestion
has body: There is a single unique element in the list. There are n similar numbers in the list. The list index out of bound appears when i'm trying to run a while loop. There is a single unique element in the list. while (arr[0]==arr[1]): IndexError: list index out of range n=int(input()) arr=[int(x) for x in input().split()] arr.sort() while (arr[0]==arr[1]): for i in range(n): arr.pop(0) print(arr[0]) Input The first line consists of an integer n, is the size of each group. The second line contains the unordered elements of the room number list. 5 1 2 3 6 5 4 4 2 5 3 6 1 6 5 3 2 4 1 2 5 1 4 3 6 8 4 3 1 5 6 2 output 8

http://stackoverflow.com/comment/91295861
score: 0
comment on: http://stackoverflow.com/q/52172395
has text: Yes, either that, or `google.com:80`. IIRC, the port is optional if it’s the default for the scheme, and the whole thing is optional in HTTP/1.0 (unless you’re talking to a virtual server, in which case it’s obviously necessary) but required in 1.1, but you might want to check the specs or MDN docs on that part.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52249753
score: -2
answer count: 1
has title: Python How to modify regex to not extract phone number
accepted answer: http://stackoverflow.com/a/52250184
tagged with: python
has comment: http://stackoverflow.com/comment/91448391
tagged with: regex
favorite count: 0
has comment: http://stackoverflow.com/comment/91447934
upvote count: 1
has comment: http://stackoverflow.com/comment/91448047
has comment: http://stackoverflow.com/comment/91448023
has comment: http://stackoverflow.com/comment/91448395
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91448256
downvote count: 3
has answer: http://stackoverflow.com/a/52250184
has comment: http://stackoverflow.com/comment/91448308
has body: My code is: import re mid = '(?:\s+|(?:-|))' pattern = '\(?(\d{3})\)?' + mid + '(\d{3})' + mid + '(\d{4})' string = "1234567890" res = re.findall(pattern, string) print "res: ", res for item in res: phone = '%s-%s-%s' % item print "phone:", phone The print results: res: [('123', '456', '7890')] phone: 123-456-7890 How to modify the regex to avoid extracting phone number from "1234567890"? Updated: the problem is solved by removing the last '|' in the mid.
type: Question

http://stackoverflow.com/a/52212174
type: Answer
accepted answer of: http://stackoverflow.com/q/52211898
score: 0
answers question: http://stackoverflow.com/q/52211898
type: AcceptedAnswer
has body: index_list = df.index[df['A'] == 'index'].tolist() # create a list of the index where df['A']=='index' new_df = [] # empty list for dataframes for i in index_list: # for loop try: new_df.append(df.iloc[i-1:i+2]) except: pass this creates a list of dataframes you can call them by new_df[0] new_df[1] or use a loop to print them out: for i in range(len(new_df)): print(f'{new_df[i]}\n') A B C 1 a 6 6 2 index 5 8 3 b 3 1 A B C 4 b 5 6 5 index 6 7 6 e 2 3 A B C 7 c 5 6 8 index 5 8

http://stackoverflow.com/comment/91465045
comment on: http://stackoverflow.com/q/52258797
has text: The Django docs show that import was only available in 1.8.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52141936
answer count: 1
has title: How can I use np.multiply with functools.partial
favorite count: 0
has body: I'm having trouble using functools.partial with np.multiply and I'm don't understand why I'm getting this error. I'm just learning how partial works so it's possible I'm just making a silly error. The error is Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_umd.py", line 194, in runfile pydev_imports.execfile(filename, global_vars, local_vars) # execute the script File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "/Users/shilo/PycharmProjects/Video/testing/test_functools.py", line 7, in &lt;module&gt; f(x1=image,x2=2.0) ValueError: invalid number of arguments The code that I'm attempting to use is below: from functools import partial import cv2 import numpy as np path = '/Users/shilo/Desktop/Goliath_preview.jpg' image = cv2.imread(path) f = partial(np.multiply,x1=image,x2=2.0) f() The np.multiply function definition looks like this: def multiply(x1, x2, *args, **kwargs) I assumed that I only needed to supply x1 and x2 but it doesn't seem to work even when I include args/kwargs I've also tried including all of the kwargs listed in the docstring but still got the same invalid number of arguments error. multiply(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
linked to: http://stackoverflow.com/q/24735311
tagged with: python-3.7
duplicate of: http://stackoverflow.com/q/24735311
has answer: http://stackoverflow.com/a/52141979
downvote count: 2
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91233884
accepted answer: http://stackoverflow.com/a/52141979
type: Question
tagged with: numpy
upvote count: 0
score: -2

http://stackoverflow.com/comment/91390323
type: AnswerComment
has text: line 23, in main fh = io.BytesIO() NameError: name 'io' is not defined , there was spelling mistake rfile_id , i changed to file_id
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52218379

http://stackoverflow.com/a/52149227
has body: Your problem has no solution. You have the constraints [0, 0, 0.4, 0, 0, 0] * x = 0.8 and x[2] &lt;= 1 but x[2] has to be 2 to fulfil the first constraint. Here is an example: ''' min [1, 1, 1, 1, 1, 1] * x with [ 0 0 0 0 0 0 ] [ 0 ] [ 0 0 0.4 0 0 0 ] * x = [ 0.4 ] [ 0 0 0 0.5 0 0 ] [ 0.25 ] and [ 0 0 0 0 0 0 ] [ 0 ] [ 0 0 0 0 0.4 0 ] * x = [ 0.04 ] [ 0 0 0 0 0 0.5 ] [ 0.125 ] and 0 &lt;= x[i] &lt;= 1, for 0 &lt;= i &lt; 6 ''' import scipy.optimize as opt import numpy as np k = 6 n = 3 W1 = np.zeros((n, k)) W1[1, 2] = 0.4 W1[2, 3] = 0.5 b1 = np.zeros([n, 1]) b1[1] = 0.4 b1[2] = 0.25 W3 = np.zeros((n, k)) W3[1, 4] = 0.4 W3[2, 5] = 0.5 b3 = np.zeros([n, 1]) b3[1] = 0.04 b3[2] = 0.125 c = np.array([1] * k) A_eq = np.vstack([W1, W3]) b_eq = np.vstack([b1, b3]) bounds = np.array([(0, 1)] * k) options = {"disp": True} result = opt.linprog(c=c, A_eq=A_eq, b_eq=b_eq, bounds=bounds, options=options) print(result.x) I fixed the dimensions of the vectors and matrices. Also I changed the entries of matrices and vectors, so that a solution can be found. Here is the output: Optimization terminated successfully. Current function value: 1.850000 Iterations: 4 [0. 0. 1. 0.5 0.1 0.25] I didn't try quadprog but if your quadprog function finds a solution, then I'm sure that the problems are not equivalent as there is no solution for the original problem. Here is another example with other values: import scipy.optimize as opt import numpy as np k = 6 n = 3 W1 = np.array([[0.35855621, 0, 0, 0, 0.85993925, 0 ], [0, 0.35855621, 0.05538291, 0, 0, 0 ], [0, 0, 0, 0.05538291, 0, 0.85993925]]) b1 = np.array([[0.35855621], [0.05538291], [0.85993925]]) c = np.array([1] * k) A_eq = W1 b_eq = b1 bounds = np.array([(0, 1)] * k) options = {"disp": True} result = opt.linprog(c=c, A_eq=A_eq, b_eq=b_eq, bounds=bounds, options=options) print(result.x) The output is: Optimization terminated successfully. Current function value: 1.571416 Iterations: 3 [0. 0.15446089 0. 0. 0.41695528 1. ]
type: Answer
has comment: http://stackoverflow.com/comment/91250147
has comment: http://stackoverflow.com/comment/91284759
has comment: http://stackoverflow.com/comment/91250377
has comment: http://stackoverflow.com/comment/91250116
answers question: http://stackoverflow.com/q/52146416
accepted answer of: http://stackoverflow.com/q/52146416
has comment: http://stackoverflow.com/comment/91250666
score: 4
has comment: http://stackoverflow.com/comment/91250843
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91455170
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52253787
has text: are the rows with fewer than 4 features have the same corresponding features. Have you tried increasing the value of k

http://stackoverflow.com/comment/91252894
score: 1
has text: @Denziloe There's a paragraph or two about strings having to be valid python identifiers in order to be interned.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52151233

http://stackoverflow.com/q/52180514
score: 0
has answer: http://stackoverflow.com/a/52180658
has comment: http://stackoverflow.com/comment/91311049
answer count: 1
has title: Create Database - PostgreSQL - Tom Aratyn's book
has body: I am reading the Tom Aratyn Book - Building Django 2.0 web application. I am on a basic level. Before migrating my app to the database, he asks to create a database for our Django project. I didn't understand very well how to create this database, he didn't detailed the process. Follow what he says: " Now that we have a model, we will need to create a table in our database that matches it. We will use Django to generate a migration for us and then run the migration to create a table for our movie model. While Django can create and run migrations for our Django apps, it will not create the database and database user for our Django project. To create the database and user, we have to connect to the server using an administrator's account. Once we've connected we can create the database and user by executing the following SQL:" CREATE DATABASE mymdb; CREATE USER mymdb; GRANT ALL ON DATABASE mymdb to "mymdb"; ALTER USER mymdb PASSWORD 'development'; ALTER USER mymdb CREATEDB; I don't know where to type this line of code. Shell? I know his book uses the PostgreSQL database. Thank you,
tagged with: postgresql
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91311069
has comment: http://stackoverflow.com/comment/91311241
type: Question
tagged with: database

http://stackoverflow.com/a/52237853
score: 1
has body: If you look at the log output of the spider, the problem becomes obvious. Traceback (most recent call last): File "c:\program files\python37\lib\site-packages\scrapy\utils\defer.py", line 102, in iter_errback yield next(it) File "c:\program files\python37\lib\site-packages\scrapy\spidermiddlewares\offsite.py", line 30, in process_spider_output for x in result: File "c:\program files\python37\lib\site-packages\scrapy\spidermiddlewares\referer.py", line 339, in &lt;genexpr&gt; return (_set_referer(r) for r in result or ()) File "c:\program files\python37\lib\site-packages\scrapy\spidermiddlewares\urllength.py", line 37, in &lt;genexpr&gt; return (r for r in result or () if _filter(r)) File "c:\program files\python37\lib\site-packages\scrapy\spidermiddlewares\depth.py", line 58, in &lt;genexpr&gt; return (r for r in result or () if _filter(r)) File "D:\Users\Ivan\Documents\Python\a.py", line 18, in parse 'response_rate': products.xpath('.//i[@class="ui2-icon ui2-icon-skip"]/text()').extract_first().strip(), AttributeError: 'NoneType' object has no attribute 'strip' 2018-09-08 19:40:36 [scrapy.core.engine] INFO: Closing spider (finished) 2018-09-08 19:40:36 [scrapy.statscollectors] INFO: Dumping Scrapy stats: {'downloader/request_bytes': 262, 'downloader/request_count': 1, 'downloader/request_method_count/GET': 1, 'downloader/response_bytes': 50753, 'downloader/response_count': 1, 'downloader/response_status_count/200': 1, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2018, 9, 8, 17, 40, 36, 231107), 'item_scraped_count': 9, 'log_count/DEBUG': 11, 'log_count/ERROR': 1, 'log_count/INFO': 7, 'response_received_count': 1, 'scheduler/dequeued': 1, 'scheduler/dequeued/memory': 1, 'scheduler/enqueued': 1, 'scheduler/enqueued/memory': 1, 'spider_exceptions/AttributeError': 1, 'start_time': datetime.datetime(2018, 9, 8, 17, 40, 33, 668475)} As you can see, an exception (AttributeError) is being raised, because not all of your items have a price and/or response r…
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52237252

http://stackoverflow.com/comment/91447718
has text: @ user2357112 ，thanks a lot .I have modify my python3.sublime_build and it works.but I dont know why remove the -OO flag ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52242859

http://stackoverflow.com/a/52141155
downvote count: 0
has comment: http://stackoverflow.com/comment/91232689
type: Answer
score: 4
has body: Closed form First of all, know that the sum of squares has a closed form. Here is the formula shifted to sum up to n - 1. def sum_square(n): if n &lt; 0: raise ValueError('n must be positive') return n*(n-1)*(2*n-1)//6 Actually, all sums of powers have a known closed form. About your code You cannot call iter(n) on an integer, you probably meant range(n). def sum_square(n): result = 0 if n &gt; 0: for i in range(n): result += i * i return result elif n &lt;= 0: raise ValueError("n should be positive") Although the above could be simplified using sum. def sum_square(n): return sum(x**2 for x in range(n))
has comment: http://stackoverflow.com/comment/91232228
answers question: http://stackoverflow.com/q/52141147
upvote count: 4
accepted answer of: http://stackoverflow.com/q/52141147
type: AcceptedAnswer

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/52247576
tags question: http://stackoverflow.com/q/52253095
tags question: http://stackoverflow.com/q/52166160
tags question: http://stackoverflow.com/q/52117268
tags question: http://stackoverflow.com/q/52210274
tags question: http://stackoverflow.com/q/52158549
tags question: http://stackoverflow.com/q/52196010
type: Tag

http://stackoverflow.com/comment/91262865
has text: It worked on my original problem, so your answer is good. Nice job ! Thank you !
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52156150

http://stackoverflow.com/comment/91440387
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52244707
type: Comment
has text: Can you show the entire stacktrace? Aditionally, are you sure the module hasn't been removed (even though it gave an error)? Try to `import fastai` in a python script and see if it still works.

http://stackoverflow.com/q/52267782
downvote count: 0
has answer: http://stackoverflow.com/a/56225535
tagged with: python
linked to: http://stackoverflow.com/q/23359083
favorite count: 0
has body: I have been using selenium to automatic printing documents and I am stuck on the print screen. As far as I know, selenium does not interact with the print screen so I am looking for an alternate situation that I can use with selenium. My code so far is down below, and all I need is code that will let me choose a new printer and then print. Also I want to change that printer to Save as PDF and then save the pdf to a file, so if that gives me a shortcut that would help a lot. from selenium import webdriver from selenium import * from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys driver = webdriver.Remote( command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME) #This is because I am using remote web driver for my Mac, but it is the same as regular web driver driver.execute("window.print()") #Need code here
type: UnansweredQuestion
tagged with: selenium
upvote count: 1
tagged with: web-scraping
linked to: http://stackoverflow.com/q/11537103
has title: How to interact with a print box using python
score: 1
type: Question
has answer: http://stackoverflow.com/a/52270329
answer count: 2
tagged with: printing
tagged with: automation

http://stackoverflow.com/comment/91229830
comment on: http://stackoverflow.com/q/52135293
type: Comment
has text: Also note that the `drive.file` scope means there are special rules about file access. Namely, the user must "pick" your app to open a file with (or create the file with the app) in order for your app to gain permissions to use that file.
type: QuestionComment
score: 1

http://stackoverflow.com/a/52259455
has comment: http://stackoverflow.com/comment/91522317
accepted answer of: http://stackoverflow.com/q/52254343
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52254343
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91472297
has body: dis3 is not a dependency of pyinstaller. You must install it via pip install dis3. This is needed only if you're trying to "pyinstall" a bunch of code written in python 2.7
has comment: http://stackoverflow.com/comment/91488710

http://stackoverflow.com/comment/91474100
type: Comment
comment on: http://stackoverflow.com/q/52263102
score: 1
has text: `df['count'] = df.sort_values(['prop','ord']).groupby(['id','chi']).cumcount()`
type: QuestionComment

http://stackoverflow.com/comment/91207056
type: Comment
type: QuestionComment
has text: @WillemVanOnsem I removed it and changed the code, but still face the same issue
comment on: http://stackoverflow.com/q/52127980
score: 0

http://stackoverflow.com/a/52208900
type: Answer
has body: Not sure if I understood your question. This is my approach without using libraries, just simple code: a=1 b=2 c=3 d=4 e=5 list = [a,b,c,d,e] for index, i in enumerate(list): list2=list[index+1:] for j in list2: print i, j Output: 1 2 1 3 1 4 1 5 2 3 2 4 2 5 3 4 3 5 4 5 Instead of 'print', you can use your function to compare the variables For sure, the code can be optimized (more pythonic), but this is one approach
score: 0
answers question: http://stackoverflow.com/q/52208726
has comment: http://stackoverflow.com/comment/91367098

http://stackoverflow.com/comment/91459742
has text: You want to move those static lists to a dictionary instead.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52256242
type: QuestionComment

sql-server
tags question: http://stackoverflow.com/q/52164037
tags question: http://stackoverflow.com/q/52189483
tags question: http://stackoverflow.com/q/52214089
tags question: http://stackoverflow.com/q/52168083
tags question: http://stackoverflow.com/q/52224945
tags question: http://stackoverflow.com/q/52137523
tags question: http://stackoverflow.com/q/52192233
type: Tag
tags question: http://stackoverflow.com/q/52160018
tag name: sql-server
tags question: http://stackoverflow.com/q/52261375
tags question: http://stackoverflow.com/q/52216979
tags question: http://stackoverflow.com/q/52124222

http://stackoverflow.com/comment/91326155
has text: You mean like [so](https://gist.github.com/Dobiasd/d8af7cab7eef852f5562bdeab511833f)?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52186874

http://stackoverflow.com/comment/91242491
score: 0
has text: The sounds like the [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Why don't you use a serialization format that understands theses types? JSON or pickle would both work here.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52146321

http://stackoverflow.com/q/52258451
downvote count: 0
has comment: http://stackoverflow.com/comment/91464237
favorite count: 0
tagged with: http://stackoverflow.com/tag/zip
has body: With a CSV file of format Name X Y L W alpha 100 200 50 20 beta 200 250 30 40 ... How can we convert the CSV into format Name X Y L W Name X Y L W alpha 100 200 50 20 beta 200 250 30 40 The maximum number of rows(excluding header) are 4. Could anybody guide how to build the dynamic dictionary for such scenario and zip to obtain the result in the format described above using python?
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/52259386
tagged with: python
has answer: http://stackoverflow.com/a/52258528
tagged with: dictionary
score: 2
has comment: http://stackoverflow.com/comment/91464291
upvote count: 2
tagged with: dynamic
type: Question
has title: Writing different rows of csv into columns keeping the same header? - Python
has comment: http://stackoverflow.com/comment/91504086
answer count: 2

http://stackoverflow.com/comment/91438083
type: Comment
has text: What if I only want to display the first amount in a line i.e only USD 2,000.00.I will be reading a file line by line.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52243904

http://stackoverflow.com/comment/91250879
has text: Yes, you can map temperatures with color strings in a dictionary: for instance `colors = {10: '#00ce00', 11: '#0015d3', etc...}`, and access them like this: `fill=colors[temperature]`
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52149119

http://stackoverflow.com/q/52144847
has body: Trying to convert a text file to csv but in the converted file I am getting square brackets at the start and end of each line and single quotes surrounding each character. in the 1st step, I am trying to remove the single quotes, but this seems to be not working the code is given below: with open('New-file_0.csv','w') as p3: with open ('New-file_1','r') as p2: for line in p2: if not line.isspace(): print(line.split(),file = p3) with open ('final-file_1.csv','w') as p2: with open('New-file_0.csv','r') as p3: for line in p3: line=line.replace("'","") print(line.split(),file = p2)
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/52144949
downvote count: 0
has comment: http://stackoverflow.com/comment/91243505
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91239427
possible better answer: http://stackoverflow.com/a/52145083
has answer: http://stackoverflow.com/a/52145083
has title: Python : unable to convert text to csv properly
upvote count: 1
has answer: http://stackoverflow.com/a/52144949
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/52127771
tagged with: physics-engine
score: 1
has title: What's causing these objects to fly to the left with pymunk?
type: Question
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52135241
tagged with: pymunk
favorite count: 0
has body: Recently I've been trying to make a simple game with pymunk. My goal (at the moment) is for the boxes to be affected by gravity, and to 'jump' when they have their up() function called. Here is my code. import pygame from pygame.locals import * from pygame.color import * import pymunk import pymunk.pygame_util #constants WALL_BOUNCINESS = 0 FLOOR_FRICTION = 1 accuracy=1 WALL_PADDING=5 #pygame initiation stuff pygame.init() width,height=1500,750 screen = pygame.display.set_mode((width, height)) #main loop initialisations clock = pygame.time.Clock() running = True #physics things space=pymunk.Space() space.gravity=(0,-900) #where the magic happens draw_options = pymunk.pygame_util.DrawOptions(screen) #boundaries wall_body = space.static_body walls = [pymunk.Segment(wall_body, (WALL_PADDING,height-WALL_PADDING), (width-WALL_PADDING,height-WALL_PADDING),1), pymunk.Segment(wall_body, (WALL_PADDING,height-WALL_PADDING), (WALL_PADDING,WALL_PADDING), 1), pymunk.Segment(wall_body, (WALL_PADDING,WALL_PADDING), (width-WALL_PADDING,WALL_PADDING), 1), pymunk.Segment(wall_body, (width-WALL_PADDING,WALL_PADDING), (width-WALL_PADDING,height-WALL_PADDING),1)] for wall in walls: wall.elasticity = WALL_BOUNCINESS wall.friction = FLOOR_FRICTION space.add(walls) #keybindings keybindings={} #adding objects class player(): #using a class for neatness, not instantiation purposes def __init__(self, starting_coords, keyset_LUR=None): x,y=starting_coords[0], starting_coords[1] mass=10 inertia = pymunk.moment_for_box(mass, (100,100)) self.body = pymunk.Body(mass, inertia) self.shape = pymunk.Poly(self.body,((x,y),(x+100,y),(x+100,y+100),(x,y+100))) self.shape.elasticity = 0 self.shape.friction = 0.5 space.add(self.body, self.shape) if keyset_LUR: funcs=iter((self.left, self.up, self.right)) for key in keyset_LUR: keybindings[key]=next(funcs) def left(self):... def right(self):... def up(self): self.body.apply_impulse_at_local_point((0,100)) p1=player((100,100),(K_a,K_w,K_d)) p2=player((1300,10…
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52135241
upvote count: 1
tagged with: python
tagged with: game-physics
type: AnsweredQuestion

http://stackoverflow.com/q/52155705
has title: How to calculate total cost of BOM of a product in Odoo using a one2many field named 'bom_line_ids'?
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have created a custom field in the model mrp.BOM structure as below to compute the total cost of BOM for a product:- Field Name:- x_bom_total Field Label:- Total BOM Field Type:- Float ReadOnly:- True Dependency:- bom_line_ids Dependent Field name 'bom_line_ids' is the field which display all the materials used in the product. It refernces to the model 'mrp.bom.line' in a one2many relationship model. So now in the computation part how to calculate the Total BOM for the product something like this:- for record in self: for each_object in record.bom_line_ids: record['x_bom_total'] += record.bom_line_ids.qty * record.bom_line_ids.list_price I am using odoo v11. Does anyone have an idea?
has answer: http://stackoverflow.com/a/52169715
score: 1
upvote count: 1
type: Question
tagged with: odoo

http://stackoverflow.com/q/52252961
score: 0
tagged with: pandas
tagged with: datetime
has comment: http://stackoverflow.com/comment/91453457
has comment: http://stackoverflow.com/comment/91458373
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91453348
has comment: http://stackoverflow.com/comment/91453439
has comment: http://stackoverflow.com/comment/91453878
duplicate of: http://stackoverflow.com/q/52027033
tagged with: python
has comment: http://stackoverflow.com/comment/91453921
has comment: http://stackoverflow.com/comment/91453712
answer count: 0
has comment: http://stackoverflow.com/comment/91453594
has comment: http://stackoverflow.com/comment/91453242
has comment: http://stackoverflow.com/comment/91453520
type: Question
has body: I have this column dat: That looks like this: dat 0 2018-06-18 1 2018-06-24 2 2018-06-26 3 2018-06-27 4 2018-06-29 5 2018-12-07 6 2018-07-31 7 2018-01-08 8 2018-06-08 9 2018-07-08 10 2018-08-08 11 2018-08-27 12 2018-08-31 I want the date to look like '%d/%m/%Y' b['dat']=pd.to_datetime(b['dat'],dayfirst= 1) #either this or b['dat']=pd.to_datetime(b['dat'],dayfirst= 0) or even yearfirst =True or False looks the same and nothing changes. I know I can do this: b['dat'] = b['dat'].dt.strftime('%d/%m/%Y') but it changes the datetime to object data type. While with the other approach doesn't.
has title: Changing what appears first in datetime in pandas
has comment: http://stackoverflow.com/comment/91453495
linked to: http://stackoverflow.com/q/52027033

http://stackoverflow.com/q/52185229
favorite count: 0
has body: Good morning everyone, I am taking a Python class right now and we havent covered what I am about to ask. So any help would be great. I have a Python Script that parses emails out of document, but it only allows me to do one document at a time. I have roughly 500 gigs of documents and most of them contain email addresses. I was wondering if there is a way to change this script to read all subfolders and documents and skip over any errors if there are any. I understand there are some file types it may not be able to read. Some of the common file types are .txt, .csv, .sql, .xlsx. Here is the script I found and it works very well for one file at a time. As always thanks everyone for the help. #!/usr/bin/env python # # Extracts email addresses from one or more plain text files. # # Notes: # - Does not save to file (pipe the output to a file if you want it saved). # - Does not check for duplicates (which can easily be done in the terminal). # from optparse import OptionParser import os.path import re regex = re.compile(("([a-z0-9!#$%&amp;'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&amp;'*+\/=?^_`" "{|}~-]+)*(@|\sat\s)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(\.|" "\sdot\s))+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)")) def file_to_str(filename): """Returns the contents of filename as a string.""" with open(filename) as f: return f.read().lower() # Case is lowered to prevent regex mismatches. def get_emails(s): """Returns an iterator of matched emails found in string s.""" # Removing lines that start with '//' because the regular expression # mistakenly matches patterns like 'http://foo@bar.com' as '//foo@bar.com'. return (email[0] for email in re.findall(regex, s) if not email[0].startswith('//')) if __name__ == '__main__': parser = OptionParser(usage="Usage: python %prog [FILE]...") # No options added yet. Add them here if you ever need them. options, args = parser.parse_args() if not args: parser.print_usage() exit(1) for arg in args: if os.path.isfile(arg): for email in get_emails(file_to_str(a…
has answer: http://stackoverflow.com/a/52185645
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/52185637
has answer: http://stackoverflow.com/a/52185637
accepted answer: http://stackoverflow.com/a/52185645
answer count: 2
type: AnsweredQuestion
downvote count: 0
has title: Python Script - Email Parser
type: Question
has comment: http://stackoverflow.com/comment/91320789
score: 1

http://stackoverflow.com/q/52167595
tagged with: python
has answer: http://stackoverflow.com/a/52189815
type: Question
answer count: 2
has title: PyCharm unable to resolve dynamic references for multiprocessing module
score: 5
has body: This is perfectly valid code: globals().update({"variable": "val"}) variable # do-something-with-variable However, PyCharm is not able to recognise the variable: I don't want to disable the marking of unresolved references; it is a very useful feature. I want PyCharm to recognise my variable. How can I do this? (even if it is a dirty trick for development that I will later erase in production) Explanation I would not care about globals().update if it were not for that Python's multiprocessing module from version 3.4 incorporates dynamic creation of variables through a context class instead of defining them in the __init__.py file (see this link) For this reason, PyCharm does not recognise the module's attributes at all, so I have to be looking up docs constantly instead of making use of PyCharm's introspective features for this package, let alone not getting the unresolved reference error that makes me doubt constantly of whether I am getting the code right or not. Basically like writing code in Windows' notepad ;-)
downvote count: 0
has answer: http://stackoverflow.com/a/52189868
has comment: http://stackoverflow.com/comment/91394300
has comment: http://stackoverflow.com/comment/91330280
favorite count: 0
upvote count: 5
tagged with: pycharm
type: UnansweredQuestion

http://stackoverflow.com/q/52130635
type: Question
tagged with: random-forest
has body: I used Orange GUI and trained a RandomForest model that i later saved using the SaveModel widget. Orange saves its models with pickle, therefore I went and wrote the following python script: import Orange, pickle model = pickle.load(open('model', 'rb')) The problem is, I extensively searched the web yesterday. And couldn't find any example to make a prediction with my data (which is the same format as the data I used in the Orange GUI) or sufficient documentation on how to use the model. Upon later research I found that I could supposedly evaluate a pre-trained model that was unpickled with the following code results = Orange.evaluation.testing.TestOnTestData(data, test, [lambda testdata: model]) The thing is to load data I'm supposed to do: data = Orange.data.Table('trainingData.csv'); test = Orange.data.Table('testData.csv'); And I haven't been able to find documentation regarding how to differentiate between the target and the features in these *.csv files. Appart from that even if I'm able create this files. I would have to do some gimmick where testData.csv would need to be only one line long (the line I want to predict) with a target value of 1. And I would see what the model predicted by checking if the score was 100% or 0% So I know my questions are multiple but I could really use some help on the follwing points: How to define in a *.csv file what is the target among the features for the Orange.data.Table() function How to use a pickled Orange RandomForest model to make a prediction instead of using a gimmicked evaluation to make a prediction. (So that i could predict more than one item at a time..) Thank you very much for your time
tagged with: python-3.6
tagged with: orange
upvote count: 2
downvote count: 0
answer count: 1
favorite count: 0
tagged with: pickle
tagged with: python
accepted answer: http://stackoverflow.com/a/52182456
score: 2
type: AnsweredQuestion
has title: How to make predictions using a saved RandomForest model from Orange GUI
has answer: http://stackoverflow.com/a/52182456

http://stackoverflow.com/a/52189764
has comment: http://stackoverflow.com/comment/91344541
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52189218
answers question: http://stackoverflow.com/q/52189218
type: Answer
score: 3
downvote count: 0
has body: This line: &lt;div&gt;&lt;img src="{{ post.main_image.url }}"&gt;&lt;/div&gt; should be: &lt;div&gt;&lt;img src="{{ post.main_image.picture.url }}"&gt;&lt;/div&gt; The reason is your model Image does not have an url method. The method belongs to the ImageField, in this case picture.
upvote count: 3

http://stackoverflow.com/comment/91341213
type: Comment
has text: Thanks @TimBiegeleisen - Edited to reflect this.
comment on: http://stackoverflow.com/a/52195715
score: 0
type: AnswerComment

http://stackoverflow.com/q/52160524
has title: Scraping page with BeautifulSoup gives strange results (multiple at the end). Why?
score: 0
answer count: 1
has body: I'm trying to scrape a page with BeautifulSoup. I would like to keep tags to later store the content in .xml files, divided into paragraphs, headers, etc. Unfortunately, the result is a bit surprising to me. Here is how it lookslike: Why is so many at the end? I got used to the structure that looks rather like this: some paragraph... next paragraph... Not like this: some paragraph... next paragraph... When I examine the HTML structure in Chrome, everything looks fine: Why is this happening? Here is my code: import os import requests from bs4 import BeautifulSoup payload = { 'username': os.environ['POLITYKA_USERNAME'], 'password': os.environ['POLITYKA_PASSWORD'], 'login_success': 'http://archiwum.polityka.pl', 'login_error': 'https://archiwum.polityka.pl/art/grypa-nam niestraszna,378836.html' } login_url = 'https://www.polityka.pl/sso/login' base_url = 'http://archiwum.polityka.pl' example_url = 'https://archiwum.polityka.pl/art/sciganie- wnbsp;organach,378798.html' with requests.Session() as session: session.headers={'User-Agent' : 'Mozilla/5.0'} post = session.post(login_url, data=payload) request = session.get(example_url) soup = BeautifulSoup(request.content, 'html.parser') box = soup.find('div', {'id' : 'container'}).find('div', {'class' : 'middle'}).find('div', {'class', 'right'}).find('div', {'class' : 'box'}) content = box.find('p', {'class' : 'box_text'}).find_next_sibling() print(content)
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52160790
tagged with: web-scraping
tagged with: python
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/52160790

http://stackoverflow.com/comment/91181637
comment on: http://stackoverflow.com/q/52115244
score: 0
type: Comment
has text: Thanks... Apologies of course ```;``` works... I must be tired. Thanks.
type: QuestionComment

http://stackoverflow.com/comment/91230077
score: 0
comment on: http://stackoverflow.com/q/52140219
has text: Python 2 and Python 3 are different languages. Are you certain that the packages you want to install have support for Python 3?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91390167
has text: @Dennis It's a warning in the editor, got this if I run the code `ModuleNotFoundError: No module named 'plotly'`
comment on: http://stackoverflow.com/q/52220670
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91463712
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52258055
has text: most poeple just use underscores to emphatise that it shoud be a space, and then just lives with it being an underscore
score: 0

http://stackoverflow.com/a/52201411
has body: We yourstring.strip() for string to finish spaces from start and end. You can use join() on your string to format string according to your need. Hope this helps you.
score: 0
answers question: http://stackoverflow.com/q/52201340
type: Answer

http://stackoverflow.com/comment/91251866
has text: you untar then list the directory and if any file is still tar you call the same function? should be quite easy with recursion
type: Comment
comment on: http://stackoverflow.com/q/52150602
type: QuestionComment
score: 0

datetime
tags question: http://stackoverflow.com/q/52112783
tags question: http://stackoverflow.com/q/52212631
tags question: http://stackoverflow.com/q/52135580
tags question: http://stackoverflow.com/q/52195107
tags question: http://stackoverflow.com/q/52268068
tags question: http://stackoverflow.com/q/52213564
tags question: http://stackoverflow.com/q/52149257
tags question: http://stackoverflow.com/q/52146501
tags question: http://stackoverflow.com/q/52264904
tags question: http://stackoverflow.com/q/52149781
tags question: http://stackoverflow.com/q/52208205
tags question: http://stackoverflow.com/q/52146981
tags question: http://stackoverflow.com/q/52116495
tags question: http://stackoverflow.com/q/52226280
tags question: http://stackoverflow.com/q/52145678
tags question: http://stackoverflow.com/q/52266076
tags question: http://stackoverflow.com/q/52138714
tags question: http://stackoverflow.com/q/52251023
tags question: http://stackoverflow.com/q/52170288
tags question: http://stackoverflow.com/q/52133438
tags question: http://stackoverflow.com/q/52263225
tags question: http://stackoverflow.com/q/52268531
tags question: http://stackoverflow.com/q/52210375
tags question: http://stackoverflow.com/q/52175603
tags question: http://stackoverflow.com/q/52250710
tags question: http://stackoverflow.com/q/52261675
tags question: http://stackoverflow.com/q/52201424
tags question: http://stackoverflow.com/q/52203246
tags question: http://stackoverflow.com/q/52246036
tags question: http://stackoverflow.com/q/52225765
tags question: http://stackoverflow.com/q/52205256
tag name: datetime
tags question: http://stackoverflow.com/q/52136980
tags question: http://stackoverflow.com/q/52124181
tags question: http://stackoverflow.com/q/52162681
tags question: http://stackoverflow.com/q/52118182
tags question: http://stackoverflow.com/q/52211443
tags question: http://stackoverflow.com/q/52243276
tags question: http://stackoverflow.com/q/52163830
tags question: http://stackoverflow.com/q/52234285
type: Tag
tags question: http://stackoverflow.com/q/52216737
tags question: http://stackoverflow.com/q/52242418
tags question: http://stackoverflow.com/q/52132977
tags question: http://stackoverflow.com/q/52129993
tags question: http://stackoverflow.com/q/52123263
tags question: http://stackoverflow.com/q/52252961
tags question: http://stackoverflow.com/q/52197487
tags question: http://stackoverflow.com/q/52152162
tags question: http://stackoverflow.com/q/52209410
tags question: http://stackoverflow.com/q/52176900
tags question: http://stackoverflow.com/q/52230218

http://stackoverflow.com/comment/91362637
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/52206554
has text: this is simply beautiful +1. For flat lists one can nest them to leave the code intact. like `lst = [lst] if not isinstance(lst[0], list) else lst`.
type: Comment

http://stackoverflow.com/q/52245231
type: UnansweredQuestion
has body: I am working on a project where I am using cv2 for multi-object detection and tracking. I was able to detect objects in a live feed and I was also able to track them with in the frame. For example: Two Persons got detected in the frame and we assigned two trackers for each one of them say Person0, Person1 Till here it is working fine. Challenge is when first person leaves, corresponding tracker gets deleted and second person tracker ID gets changed to Person 0, But I dont want that to be chnaged to Person 0, it should be Person1 Below is the code I've tried: from imutils.video import VideoStream from imutils.video import FPS import numpy as np import argparse import imutils import time import cv2 from math import floor # initialize the list of class labels MobileNet SSD was trained to # detect, then generate a set of bounding box colors for each class CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"] COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3)) # load our serialized model from disk print("[INFO] loading model...") net = cv2.dnn.readNetFromCaffe('./models/MobileNetSSD_deploy.prototxt.txt', './models/MobileNetSSD_deploy.caffemodel') # initialize the video stream, allow the cammera sensor to warmup, # and initialize the FPS counter print("[INFO] starting video stream...") vs = VideoStream(src=1).start() time.sleep(2.0) fps = FPS().start() init_once = [] oklist = [] tracker_lst = [] newbox = [] # loop over the frames from the video stream while True: # grab the frame from the threaded video stream and resize it # to have a maximum width of 400 pixels frame = vs.read() frame = imutils.resize(frame, width=900,height = 600) (h, w) = frame.shape[:2] blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)),0.007843, (300, 300), 127.5) net.setInput(blob) detections = net.forward() bounding_box…
tagged with: python
tagged with: computer-vision
tagged with: opencv
score: 3
answer count: 0
upvote count: 3
type: Question
downvote count: 0
has title: Multi-Object Tracking using Opencv Python: Delete trackers for the objects that moved out of frame
tagged with: object-detection
favorite count: 0
has comment: http://stackoverflow.com/comment/91443819

http://stackoverflow.com/comment/91208529
comment on: http://stackoverflow.com/q/52128846
score: 0
has text: @roganjosh m extremely sorry for not following the norms to post in the stackoverflow as I was unaware of it. I will keep this in mind from next time onwards.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52163092
answers question: http://stackoverflow.com/q/52162681
downvote count: 0
has comment: http://stackoverflow.com/comment/91286409
has comment: http://stackoverflow.com/comment/91285019
has comment: http://stackoverflow.com/comment/91286122
has comment: http://stackoverflow.com/comment/91285493
type: Answer
has comment: http://stackoverflow.com/comment/91276643
has comment: http://stackoverflow.com/comment/91287854
has comment: http://stackoverflow.com/comment/91284488
score: 1
upvote count: 1
has body: the example you are giving is missing : which does not make it match the iso8601 format 2018-09-04T00:00:00+0100 should be 2018-09-04T00:00:00+01:00 - minor detail but significant. If you read the docs, the only format provided by the serializer is 'iso-8601' All the formats you mentioned above are not part of the input formats. Make sure you have the right format in your input_formats list in your serializers.DateTimeField Signature: DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None) input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATETIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601']. Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style datetimes should be used. (eg '2013-01-29T12:34:56.000000Z')
has comment: http://stackoverflow.com/comment/91286162

http://stackoverflow.com/comment/91357375
type: QuestionComment
has text: I think there is problem with duplicated columns names in some DataFrame.
score: 1
comment on: http://stackoverflow.com/q/52204115
type: Comment

http://stackoverflow.com/comment/91410996
comment on: http://stackoverflow.com/a/52230563
score: 1
type: AnswerComment
type: Comment
has text: @SamirTendulkar, Yep, you need to trim it to a **minimal** [mcve]. I advise you roll back while you work that out.

http://stackoverflow.com/comment/91234549
comment on: http://stackoverflow.com/q/52142349
has text: The error is way too long to be useful, but I tell some parts of what is in the error message.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52220764
answers question: http://stackoverflow.com/q/52208363
has comment: http://stackoverflow.com/comment/115763478
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/115792596
score: 8
has comment: http://stackoverflow.com/comment/115763886
accepted answer of: http://stackoverflow.com/q/52208363
type: AcceptedAnswer
downvote count: 0
has body: As discussed here (thanks @"Welcome to Stack Overflow" for the comment directing me there), the problem is indeed that the gradient routine doesn't respect the bounds. I wrote a new one that does the job: import math import numpy as np from scipy.optimize import minimize def gradient_respecting_bounds(bounds, fun, eps=1e-8): """bounds: list of tuples (lower, upper)""" def gradient(x): fx = fun(x) grad = np.zeros(len(x)) for k in range(len(x)): d = np.zeros(len(x)) d[k] = eps if x[k] + eps &lt;= bounds[k][1] else -eps grad[k] = (fun(x + d) - fx) / d[k] return grad return gradient bounds = ((-1, 1), (-1, 1)) def fun(x): print(x) return -math.exp(-np.dot(x,x)) result = minimize(fun, [-1, -1], bounds=bounds, jac=gradient_respecting_bounds(bounds, fun)) Note that this can be a bit less efficient, because fun(x) now gets evaluated twice at each point. This seems to be unavoidable, relevant snippet from _minimize_lbfgsb in lbfgsb.py: if jac is None: def func_and_grad(x): f = fun(x, *args) g = _approx_fprime_helper(x, fun, epsilon, args=args, f0=f) return f, g else: def func_and_grad(x): f = fun(x, *args) g = jac(x, *args) return f, g As you can see, the value of f can only be reused by the internal _approx_fprime_helper function.

http://stackoverflow.com/a/52211393
upvote count: 1
has comment: http://stackoverflow.com/comment/91474712
accepted answer of: http://stackoverflow.com/q/52210861
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91475633
downvote count: 0
has body: You are correct. wx does not allow you to change the size of the buttons, only the window they are in. From the documentation: size (wx.Size) – Window size. If wx.DefaultSize is specified then a default size is chosen. Maybe try tkinter? It also doesn't allow you to control the size of the button itself, but you can make the entire contents into a button using indicatoron=0 which you can control the size of. Hope that helps. from tkinter import * root=Tk() var=IntVar() R1=Radiobutton(root, text='Off', variable=var, value=1, height=10, width=20 indicatoron=0) R1.pack( anchor = W ) R2=Radiobutton(root, text='On', variable=var, value=2, height=10, width=20 indicatoron=0) R2.pack( anchor = W ) label=Label(root) label.pack() root.mainloop()
score: 1
answers question: http://stackoverflow.com/q/52210861
type: Answer

http://stackoverflow.com/q/52168027
accepted answer: http://stackoverflow.com/a/52178182
has comment: http://stackoverflow.com/comment/91295911
tagged with: apache
downvote count: 0
answer count: 1
favorite count: 0
has title: Django: "argument of type 'int' is not iterable" in oracle/base.py in _rowfactory
has body: I'm trying to connect my Django app to Oracle DB but making a query results in exception: TypeError: argument of type 'int' is not iterable Exception Location: /opt/isep/venv/lib/python3.4/site-packages/django/db/backends/oracle/base.py in _rowfactory, line 560 def _rowfactory(row, cursor): # Cast numeric values as the appropriate Python type based upon the # cursor description, and convert strings to unicode. casted = [] for value, desc in zip(row, cursor.description): if value is not None and desc[1] is Database.NUMBER: precision = desc[4] or 0 scale = desc[5] or 0 if scale == -127: if precision == 0: # NUMBER column: decimal-precision floating point # This will normally be an integer from a sequence, # but it could be a decimal value. if '.' in value: value = decimal.Decimal(value) else: value = int(value) else: # FLOAT column: binary-precision floating point. # This comes from FloatField columns. value = float(value) elif precision &gt; 0: # NUMBER(p,s) column: decimal-precision fixed point. # This comes from IntField and DecimalField columns. if scale == 0: value = int(value) else: value = decimal.Decimal(value) elif '.' in value: # No type information. This normally comes from a # mathematical expression in the SELECT list. Guess int # or Decimal based on whether it has a decimal point. value = decimal.Decimal(value) else: value = int(value) elif desc[1] in (Database.STRING, Database.FIXED_CHAR, Database.LONG_STRING): value = to_unicode(value) casted.append(value) return tuple(casted) Error occurs in line: if '.' in value: because value = 0. I'm using: Python 3.4, Django 1.11, cx_Oracle 6.0. How can I solve this?
tagged with: oracle-database
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91286263
type: Question
has answer: http://stackoverflow.com/a/52178182

http://stackoverflow.com/q/52153056
tagged with: saprfc
answer count: 1
downvote count: 0
favorite count: 0
has title: Set query parameters of RFC_READ_TABLE using win32com module?
type: UnansweredQuestion
has body: I'm trying to port to Python a SAP table download script, that already works on Excel VBA, but I want a command line version and I would prefer to avoid VBScript for a number of reasons that go beyond the goal of this post. I'm stuck at the moment in which I need to fill the values in a table from win32com.client import Dispatch Functions = Dispatch("SAP.Functions") Functions.Connection.Client = "400" Functions.Connection.ApplicationServer = "myserver" Functions.Connection.Language = "EN" Functions.Connection.User = "myuser" Functions.Connection.Password = "mypwd" Functions.Connection.SystemNumber = "00" Functions.Connection.UseSAPLogonIni = False if (Functions.Connection.Logon (0,True) == True): print("Logon OK") RFC = Functions.Add("RFC_READ_TABLE") RFC.exports("QUERY_TABLE").Value = "USR02" RFC.exports("DELIMITER").Value = "~" #RFC.exports("ROWSKIPS").Value = 2000 #RFC.exports("ROWCOUNT").Value = 10 tblOptions = RFC.Tables("OPTIONS") #RETURNED DATA tblData = RFC.Tables("DATA") tblFields = RFC.Tables("FIELDS") tblFields.AppendRow () print(tblFields.RowCount) print(tblFields(1,"FIELDNAME")) # the 2 lines above print 1 and an empty string, so the row in the table exists Until here it is basically copied from VBA adapting the syntax. In VBA at this point I'm able to do tblFields(1,"FIELDNAME") = "BNAME" if I do the same I get an error because the left part is a function and written that way it returns a string. In VBA it is probably a bi-dimensional array. I unsuccessfully tried various approaches like tblFields.setValue([{"FIELDNAME":"BNAME"}]) tblFields(1,"FIELDNAME").Value = "BNAME" tblFields(1,"FIELDNAME").setValue("BNAME") tblFields.FieldName = "BNAME" ##kinda desperate The script works, without setting the FIELDS table, for outputs that produce rows shorter than 500 chars. This is a SAP limit in the function. I know that this is not the best way, but I can't use the SAPNWRFC library and I can't use librfc32.dll. I must be able to solve this way, or revert to th…
tagged with: python
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/56661990
tagged with: win32com

http://stackoverflow.com/q/52261082
type: UnansweredQuestion
has body: I was using snakemake to implement a new tool in a pipeline and i had some trouble with those lines: resources: # Samtools sort requires by default 768M per threads # Here, be set the maximum amount of memory are 1.5Go per threads mem_mb = ( lambda wildcards, attempt, threads: min( attempt * 250 + threads * 768, 1536 * threads) ) the error is : TypeError: &lt;lambda&gt;() missing 1 required positional argument: 'threads' Wildcards: sample=test_GATK genome=fakefile To make those lines i used the documentation on this page : snakemake documentation To fix this issue i use this code instead: resources: # Samtools sort requires by default 768M per threads # Here, be set the maximum amount of memory are 1.5Go per threads mem_mb = ( lambda wildcards, attempt: min( attempt * 250 + config["threads"] * 768, 1536 * config["threads"]) ) I don't know why the previous one is not working, can you help me figure it out ? Thanks for the help :)
has answer: http://stackoverflow.com/a/52265298
tagged with: python
has title: Snakemake, trouble with "lambda wildcards, attempt, threads"
tagged with: snakemake
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91478416
answer count: 1
has comment: http://stackoverflow.com/comment/91470003

http://stackoverflow.com/a/52267781
answers question: http://stackoverflow.com/q/52267712
type: Answer
has body: How about rsplit()? s = 'ABCD 1NAME 123456' print(s.rsplit(' ', 1)[1]) # 123456
score: 0

http://stackoverflow.com/comment/91200483
has text: @SarthakNegi `chromedriver` is in the same folder where my script is there....
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52121506

http://stackoverflow.com/comment/91199279
has text: Wow, thank you so much for this really comprehensive answer! I still have so much more to learn. :)
score: 0
comment on: http://stackoverflow.com/a/52123986
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52167649
has body: I created an executable file (.exe file) of a python script. I lost the folder with the original python script (also no backups), due to disk formatting. By chance I got its executable file on the drive. Can I re-convert it to the python script?
has comment: http://stackoverflow.com/comment/91285745
has comment: http://stackoverflow.com/comment/91294714
answer count: 1
has comment: http://stackoverflow.com/comment/91286671
favorite count: 0
has comment: http://stackoverflow.com/comment/91287705
accepted answer: http://stackoverflow.com/a/52167691
tagged with: python
has title: Is it possible to convert a .exe file to .py?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91285215
downvote count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91285988
tagged with: executable
upvote count: 5
has answer: http://stackoverflow.com/a/52167691
score: 4

http://stackoverflow.com/comment/91298027
comment on: http://stackoverflow.com/q/52173562
has text: Just try if it works. One of the benefits is the REPL which allows playing with the language.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91444498
has text: Please provide code that is a [Minimal, Complete, and Verifiable](https://stackoverflow.com/help/mcve) example of the question you are trying to ask
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52248287

http://stackoverflow.com/comment/91351464
score: 0
comment on: http://stackoverflow.com/q/52196292
type: Comment
type: QuestionComment
has text: Matplotlib 2.2.3 definitely provides the `matplotlib.cm` within pyplot, hence `plt.cm.rainbow` will be available. If it doesn't work for you, maybe you have unintentionally overwritten something.

http://stackoverflow.com/comment/91407993
comment on: http://stackoverflow.com/q/52220794
score: 0
has text: OK I see. But do you need to append the rows to a list and then save at the very end? If you write each row as you iterate through the rows returned (and not store rows in list), then the Python interpreter can reclaim the memory used by each row when they are no longer referenced.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91345974
type: QuestionComment
comment on: http://stackoverflow.com/q/52198273
has text: @VictorWong I don't think it's rendering different views.
score: 0
type: Comment

http://stackoverflow.com/comment/91308698
score: 0
type: AnswerComment
has text: I have refresh question
type: Comment
comment on: http://stackoverflow.com/a/52178631

http://stackoverflow.com/comment/91403342
has text: `install` installs a new package, `update` updates a previously installed package to the newest version, no?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52226942
score: 3

http://stackoverflow.com/comment/91249277
has text: @LiamHealy: Ok, now I have this error: `TypeError: get_support() missing 1 required positional argument: 'self'`
type: QuestionComment
comment on: http://stackoverflow.com/q/52149376
type: Comment
score: 0

http://stackoverflow.com/comment/91303550
comment on: http://stackoverflow.com/q/52176575
has text: Why not just use `shuffle`?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52179761
tagged with: python-3.x
tagged with: cpython
tagged with: python-extensions
tagged with: python
has answer: http://stackoverflow.com/a/52183767
accepted answer: http://stackoverflow.com/a/52183767
has body: I have a function foo in a Python Extension Module that should return a tuple of ints to Python. This can be easily done using Py_BuildValue: static PyObject* foo(PyObject* self, PyObject* args) { int a = 0; int b = 0; /* calculations and stuff */ PyObject* out = Py_BuildValue("(iii)", a, b, a+b); Py_INCREF(out); return out; } Instead of Py_BuildValue, I want to use PyTuple_Pack, which ensures that the return value is indeed a tuple. The Python C API documentation says that PyTuple_Pack(3, a, b, a+b) is equivalent to Py_BuildValue("(iii)", a, b, a+b). Both functions return a new reference of type PyPbject*. Hence, given the code above, static PyObject* foo(PyObject* self, PyObject* args) { /* ... */ PyObject* out = PyTuple_Pack(3, a, b, a+b); Py_INCREF(out); return out; } should do the trick, which is does not. Instead I get a segfault. What am I missing here?
type: AnsweredQuestion
score: 7
upvote count: 7
type: Question
has title: `PyTuple_Pack` segfault
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/91435836
has text: No error appears on the screen. print() function does not print anything. There is no output produced. For the pdf files, whose PDF version is 1.5 and above, the output appears. You can reproduce the situation by taking two pdf files, one with version less than 1.5 and other with more than or equal to 1.5. The Version number can be checked by opening the pfd and clicking on File menu>properties.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52224440

http://stackoverflow.com/a/52219297
type: Answer
upvote count: 1
has body: Creating dynamic variables is a bad idea, so you can try like this : f = open("log.txt", "r") ids = [] for i in f.readlines(): sub_id = list(map(int,i.split(","))) ids.append(sub_id) print(ids) # [[20, 110, 60, 140],[10, 210, 80, 24]] or : f = open("log.txt", "r") ids = {} for j,i in enumerate(f.readlines()): sub_id = list(map(int,i.split(","))) ids['id'+str(j)] = sub_id print(ids) # {'id1': [10, 210, 80, 24], 'id0': [20, 110, 60, 140]}
score: 1
answers question: http://stackoverflow.com/q/52219149
accepted answer of: http://stackoverflow.com/q/52219149
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91388437
has comment: http://stackoverflow.com/comment/91388555

http://stackoverflow.com/comment/91327127
type: QuestionComment
type: Comment
score: 1
has text: Question was edited
comment on: http://stackoverflow.com/q/52188435

http://stackoverflow.com/q/52217422
has title: Setting custom loss causes RuntimeError: Variable data has to be a tensor, but got Variable in Pytorch
has answer: http://stackoverflow.com/a/52217824
accepted answer: http://stackoverflow.com/a/52217824
tagged with: runtime-error
score: 0
tagged with: deep-learning
tagged with: python
tagged with: pytorch
has body: I have custom class for the net definition: class PyTorchUNet(Model): .... def set_loss(self): if self.activation_func == 'softmax': #this is working example loss_function = partial(mixed_dice_cross_entropy_loss, dice_loss=multiclass_dice_loss, cross_entropy_loss=nn.CrossEntropyLoss(), dice_activation='softmax', dice_weight=self.architecture_config['model_params']['dice_weight'], cross_entropy_weight=self.architecture_config['model_params']['bce_weight'] ) elif self.activation_func == 'sigmoid': loss_function = designed_loss #setting will cause error on validation else: raise Exception('Only softmax and sigmoid activations are allowed') self.loss_function = [('mask', loss_function, 1.0)] def designed_loss(output, target): target = target.long() # this should make variable to tensor return lovasz_hinge(output, target) # this is just as it from github def lovasz_hinge(logits, labels, per_image=True, ignore=None): """ Binary Lovasz hinge loss logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty) labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) per_image: compute the loss per image instead of per batch ignore: void class id """ if per_image: loss = mean(lovasz_hinge_flat(*flatten_binary_scores(log.unsqueeze(0), lab.unsqueeze(0), ignore)) for log, lab in zip(logits, labels)) else: loss = lovasz_hinge_flat(*flatten_binary_scores(logits, labels, ignore)) return loss def lovasz_hinge_flat(logits, labels): """ Binary Lovasz hinge loss logits: [P] Variable, logits at each prediction (between -\infty and +\infty) labels: [P] Tensor, binary ground truth labels (0 or 1) ignore: label to ignore """ if len(labels) == 0: # only void pixels, the gradients should be 0 return logits.sum() * 0. signs = 2. * labels.float() - 1. errors = (1. - logits * Variable(signs)) errors_sorted, perm = torch.sort(errors, dim=0, descending=True) perm = perm.data gt_sorted = labels[perm] grad = lovasz_grad(gt_sorted) loss = torch.dot(F.elu(errors_sorted), Variable(…
has comment: http://stackoverflow.com/comment/91384140
has comment: http://stackoverflow.com/comment/91384098
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91384179
type: Question
answer count: 1

http://stackoverflow.com/a/52132062
has comment: http://stackoverflow.com/comment/91214687
downvote count: 0
has comment: http://stackoverflow.com/comment/91214629
score: 1
has body: How about something as simple as this: class TupleWithName(tuple): pass t = TupleWithName((1, 2, 3)) t.name = 'tuple one' print(t) # (1, 2, 3) print(t.name) # 'tuple one'
upvote count: 1
answers question: http://stackoverflow.com/q/52131978
type: Answer

http://stackoverflow.com/comment/91353444
score: 0
has text: I've updated the question to more appropriately reflect what I was trying to ask. I apologize about the confusion.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52189260

http://stackoverflow.com/comment/91397231
has text: Thank you: the solution works correctly. Unfortunately, in pandas, operations like `mask[t2.index] = True` are very slow. My impression is that internally they are not vectorized. Too bad, since I find myself in need to do those very frequently.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52176749

http://stackoverflow.com/q/52255112
tagged with: scrapy
answer count: 1
has body: I'm trying to obtain every single link (and no other data) from a website using Scrapy. I want to do this by starting at the homepage, scraping all the links from there, then for each link found, follow the link and scrape all (unique) links from that page, and do this for all links found until there are no more to follow. I also have to enter a username and password to get into each page on the site, so I've included a basic authentication component to my start_requests. So far I have a spider which gives me the links on the homepage only, however I can't seem to figure out why it's not following the links and scraping other pages. Here is my spider: from examplesite.items import ExamplesiteItem import scrapy from scrapy.linkextractor import LinkExtractor from scrapy.spiders import Rule, CrawlSpider from scrapy import Request from w3lib.http import basic_auth_header from scrapy.crawler import CrawlerProcess class ExampleSpider(CrawlSpider): #name of crawler name = "examplesite" #only scrape on pages within the example.co.uk domain allowed_domains = ["example.co.uk"] #start scraping on the site homepage once credentials have been authenticated def start_requests(self): url = str("https://example.co.uk") username = "*********" password = "*********" auth = basic_auth_header(username, password) yield scrapy.Request(url=url,headers={'Authorization': auth}) #rules for recursively scraping the URLS found rules = [ Rule( LinkExtractor( canonicalize=True, unique=True ), follow=True, callback="parse" ) ] #method to identify hyperlinks by xpath and extract hyperlinks as scrapy items def parse(self, response): for element in response.xpath('//a'): item = ExamplesiteItem() oglink = element.xpath('@href').extract() #need to add on prefix as some hrefs are not full https URLs and thus cannot be followed for scraping if "http" not in str(oglink): item['link'] = "https://example.co.uk" + oglink[0] else: item['link'] = oglink yield item Here is my items class: from scrapy import Fi…
type: UnansweredQuestion
score: 2
has title: How to recursively scrape every link from a site using Scrapy?
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/101601472
type: Question
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52261383
tagged with: web-scraping

http://stackoverflow.com/comment/91345554
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52173847
type: Comment
has text: by any chance, could you let me know you, by using this emoji code `\U0001f604` have them display, as my one display only text without forward slash???

http://stackoverflow.com/a/52268442
score: 1
has body: Use pandas, specifically the replace function. You can pass it a dictionary of multiple values to replace, where the keys in the dictionary get replaced by the values. df['demo'].replace({20:30, 30:20}, inplace=True) Example: &gt;&gt;&gt; df = pd.DataFrame({'demo':[20,30,40,50,20,30,30,20]}) &gt;&gt;&gt; df demo 0 20 1 30 2 40 3 50 4 20 5 30 6 30 7 20 &gt;&gt;&gt; df['demo'].replace({20:30, 30:20}, inplace=True) &gt;&gt;&gt; df demo 0 30 1 20 2 40 3 50 4 30 5 20 6 20 7 30
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52268430
answers question: http://stackoverflow.com/q/52268430
type: Answer
downvote count: 0

equality
tags question: http://stackoverflow.com/q/52131569
tag name: equality
type: Tag

http://stackoverflow.com/q/52201819
tagged with: python
has answer: http://stackoverflow.com/a/52201872
tagged with: python-3.x
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/91352563
has body: I am trying to read a file using : as delimiter and contains blank lines. My CSV file looks likes- P Data Usage (Bytes): 640 P Inst Usage (Bytes): 13322 P Local Patch Match: 105 P Global Patch Match: 20 V Data Usage (Bytes): 312 V Inst Usage (Bytes): 972 V Local Patch Match: 24 V Global Patch Match: 1 U UOP Usage: 352 U Patch Match: 51 I want to remove blank lines from this file and I want to store it in the same file. I want to use all the values after : for updating Excel table. How to remove blank lines from the file because if I am trying to read the file it is reading only top 4 lines and not reading any further line. I want to store every integer value in each row in a list like - a = ['640', '13322', '105', '20', '312', '972', '24', ..., '51']
has title: How to delete blank lines from CSV file?
accepted answer: http://stackoverflow.com/a/52201872
possible better answer: http://stackoverflow.com/a/52202034
has answer: http://stackoverflow.com/a/52202034
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52202059
type: Question

http://stackoverflow.com/comment/91412028
comment on: http://stackoverflow.com/a/52227936
type: AnswerComment
has text: Thank you for the answer! Idon't think I phrased my question very well... I am trying to make the background color of the box( in this example, white and yellow) to be a uniform color without the brighter and darker regions while still keeping the texts and logos clear. I don't think a simple filter will be the solution, as shown in the results the dark, uniform color still exists on all the filtered images.
score: 0
type: Comment

http://stackoverflow.com/q/52189407
tagged with: python
answer count: 1
tagged with: bokeh
accepted answer: http://stackoverflow.com/a/52189998
upvote count: 5
type: AnsweredQuestion
downvote count: 0
has title: Is there a way to use text based X values with Bokeh?
favorite count: 0
has body: I am trying to plot a simple chart with Bokeh but it fails to display anything when the x values are text based: x=['-', 'AF', 'AS', 'EU', 'NA', 'OC', 'SA'] y=[8, 7621750, 33785311, 31486697, 38006434, 7312002, 7284879] p = figure(plot_width=480, plot_height=300,title='test') p.vbar(x=x, width=0.5, bottom=0, top=y, color="navy", alpha=0.5) p.toolbar.logo = None p.toolbar_location = None v = gridplot(p) show(v) I am wondering if this is a bug. Version: 0.13.0 After applying the suggested fix it works: for i in range(4): ind=i+offset rez[ind].sort(key=lambda tup: tup[0]) x = [x[0] for x in rez[ind]] y = [x[1] for x in rez[ind]] if type(x[0]) == str: charts[i] = figure( plot_width=480, plot_height=300, title=columns_being_investigated[ind], x_range=x) else: charts[i] = figure( plot_width=480, plot_height=300, title=columns_being_investigated[ind]) charts[i].vbar(x=x, width=0.5, bottom=0, top=y, color="navy", alpha=0.5) charts[i].toolbar.logo = None charts[i].toolbar_location = None p = gridplot([[charts[0], charts[1]], [charts[2], charts[3]]]) show(p)
type: Question
score: 5
has answer: http://stackoverflow.com/a/52189998

http://stackoverflow.com/q/52236636
score: 2
has title: How to troubleshoot a Python Requests POST failure when the same POST is working fine in Postman?
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/20658572
favorite count: 0
has comment: http://stackoverflow.com/comment/91421819
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has body: I continue to get a very generic, unhelpful error message from python requests when making a POST request that works fine in Postman. No matter what I try, I continue to receive one of two error messages. And note that the calling python script does not have a line 155, nor does the payload contain the letter "u": {"error":{"detail":"SyntaxError: Unexpected token: u (sys_script_include.d2426c9ec0a8016501958bf2ac79c775.script; line 155)","message":"Unexpected token: u"},"status":"failure"} {"error":{"message":"Unexpected token: u","detail":"SyntaxError: Unexpected token: u (sys_script_include.d2426c9ec0a8016501958bf2ac79c775.script; line 155)"},"status":"failure"} In Postman, the parameters are correctly interpreted and then appended to the url such as: https://areallylongurl?params={"catalogItem": "Req Name"} In Python Requests I have tried various combinations of things without luck. payload = {"params": '{"catalogItem": "Req Name"}'} response = requests.post(url, headers=headers, json=payload, verify=False) response = requests.post(url, headers=headers, json=json.dumps(payload), verify=False) response = requests.post(url, headers=headers, data=payload, verify=False) response = requests.post(url, headers=headers, data=json.dumps(payload), verify=False) By using this very helpful SO answer, I was able to further analyze how the Requests library interpreted my provided payload but I am still not sure exactly how to interpret this generic error message, or what the cause may be. Does anyone have thoughts as to what the underlying issue could be? And note that I can GET from this API without issue from Requests, it's only the POST that's problematic.
has answer: http://stackoverflow.com/a/52236727
tagged with: python
tagged with: python-requests
type: Question

http://stackoverflow.com/comment/91417986
score: 0
type: Comment
has text: if your samples with `nan` are a few, try to drop. (esay way). But if you want, you can use more statical ways like `average`,`mean` and other.
comment on: http://stackoverflow.com/a/52234688
type: AnswerComment

http://stackoverflow.com/a/52240241
accepted answer of: http://stackoverflow.com/q/52240080
answers question: http://stackoverflow.com/q/52240080
type: Answer
has comment: http://stackoverflow.com/comment/91429352
score: 2
downvote count: 0
has body: csv.reader Given your desired output, you do not need to use dict or, consequently, csv.DictReader. Instead, just use csv.reader, which returns an iterator. Then use next and list to extract headers and data respectively: from io import StringIO import csv x = StringIO("""play,weather,temperature yes,sunny,77 no,rainy,60 yes,windy,70""") # replace x with open('file.csv', 'r') with x as fin: reader = csv.reader(fin) headers = next(reader) # get headers from first row data = list(reader) # exhaust iterator from second row onwards The result is a list of headers, and a list of lists for data: print(headers) ['play', 'weather', 'temperature'] print(data) [['yes', 'sunny', '77'], ['no', 'rainy', '60'], ['yes', 'windy', '70']] pandas If you are willing to use a 3rd party library, Pandas may be a better option as it handles type conversion and indexing more conveniently: import pandas as pd df = pd.read_csv('file.csv') The result is a pd.DataFrame object: print(df) play weather temperature 0 yes sunny 77 1 no rainy 60 2 yes windy 70 print(type(df)) &lt;class 'pandas.core.frame.DataFrame'&gt;
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/91407426
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52211764
score: 0
has text: @Ywapom could you possibly point me in the right direction?

vgg-net
tags question: http://stackoverflow.com/q/52213726
tag name: vgg-net
type: Tag
tags question: http://stackoverflow.com/q/52230874
tags question: http://stackoverflow.com/q/52268048

http://stackoverflow.com/a/52142282
type: Answer
upvote count: 6
has body: You're right. Most stemmers only stem suffixes. In fact the original paper from Martin Porter is titled: Porter, M. "An algorithm for suffix stripping." Program 14.3 (1980): 130-137. And possibly the only stemmers that has prefix stemming in NLTK are the arabic stemmers: https://github.com/nltk/nltk/blob/develop/nltk/stem/arlstem.py#L115 https://github.com/nltk/nltk/blob/develop/nltk/stem/snowball.py#L372 But if we take a look at this prefix_replace function, it simply removes the old prefix and substitute it with the new prefix. def prefix_replace(original, old, new): """ Replaces the old prefix of the original string by a new suffix :param original: string :param old: string :param new: string :return: string """ return new + original[len(old):] But we can do better! First, do you have a fixed list of prefix and substitutions for the language you need to process? Lets go with the (unfortunately) de facto language, English, and do some linguistics work to find out prefixes in English: https://dictionary.cambridge.org/grammar/british-grammar/word-formation/prefixes Without much work, you can write a prefix stemming function before the suffix stemming from NLTK, e.g. import re from nltk.stem import PorterStemmer # From https://dictionary.cambridge.org/grammar/british-grammar/word-formation/prefixes english_prefixes = { "anti": "", # e.g. anti-goverment, anti-racist, anti-war "auto": "", # e.g. autobiography, automobile "de": "", # e.g. de-classify, decontaminate, demotivate "dis": "", # e.g. disagree, displeasure, disqualify "down": "", # e.g. downgrade, downhearted "extra": "", # e.g. extraordinary, extraterrestrial "hyper": "", # e.g. hyperactive, hypertension "il": "", # e.g. illegal "im": "", # e.g. impossible "in": "", # e.g. insecure "ir": "", # e.g. irregular "inter": "", # e.g. interactive, international "mega": "", # e.g. megabyte, mega-deal, megaton "mid": "", # e.g. midday, midnight, mid-October "mis": "", # e.g. misaligned, mislead, misspelt "non": "", # …
score: 6
has comment: http://stackoverflow.com/comment/91451146
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52140526
answers question: http://stackoverflow.com/q/52140526

http://stackoverflow.com/q/52194039
score: 0
has body: I am experimenting with Keras variable to build a custom loss function and I stumbled in a strange behavior. Let's take this elementwise operation in np.arrays np_yt = np.arange(10)/10 np_yw = np.arange(10) np_yt * np_yw The output is array([0. , 0.1, 0.4, 0.9, 1.6, 2.5, 3.6, 4.9, 6.4, 8.1]) I try to do the same with Keras variables yt = K.variable(np.arange(10)/10) yw = K.variable(np.arange(10)) K.eval( yt*yw ) The output is array([0. , 0.1 , 0.4 , 0.90000004, 1.6 , 2.5 , 3.6000001 , 4.9 , 6.4 , 8.099999 ], dtype=float32) There is apparently a significant rounding error. My question is: is this expected, like e.g. explained in Is floating point math broken? ? But if so, why this happens with Keras and not in plain numpy? Is floating point binary representation different in the two cases?
tagged with: precision
has comment: http://stackoverflow.com/comment/91337956
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/588004
tagged with: python
has title: Keras elementwise variable multiplication error?
tagged with: math
has comment: http://stackoverflow.com/comment/91338717
tagged with: floating-point
type: Question
tagged with: keras

http://stackoverflow.com/comment/91483952
has text: @Gimhani same thing.
comment on: http://stackoverflow.com/q/52268036
score: 0
type: Comment
type: QuestionComment

sympy
tags question: http://stackoverflow.com/q/52258040
tags question: http://stackoverflow.com/q/52176055
tag name: sympy
tags question: http://stackoverflow.com/q/52194981
tags question: http://stackoverflow.com/q/52243320
tags question: http://stackoverflow.com/q/52161391
tags question: http://stackoverflow.com/q/52155213
tags question: http://stackoverflow.com/q/52173852
tags question: http://stackoverflow.com/q/52176354
tags question: http://stackoverflow.com/q/52121121
type: Tag
tags question: http://stackoverflow.com/q/52213328
tags question: http://stackoverflow.com/q/52142507

http://stackoverflow.com/q/52118574
has body: I have built an interactive dictionary: the programm requires an input from the user(a word) and as an output it gives a definition of the input word: For this I have a dictionary, where keys are words and values are their definitions. Here is my code: import json import re data = json.load(open('C:\\Users\\yefida\\Desktop\\Study_folder\\Online_Courses\\python mega course\\Project1 - Interactive Dictionary\\data.json')) def interactive_dict(input_user): input_user = input_user.lower() for key in data.keys(): my_regex = r'^[a-z0-9_]*' + key + '[a-z0-9_]*$' if input_user == key: for values in data[key]: print(values) break elif bool(re.match(my_regex,input_user)): check = input('Do you mean {}? If yes type "y", if no type "n":'.format(key)) if check == 'y': for values in data[key]: print(values) break interactive_dict('dain') In most cases it works good, but: For example, I provided as an input the word "dain" (which doesn't exist) and it starts checking in the dictionary(based on regex code) the following words: "a", 'in" , which of course are far away from the truth. When the word isn't contained in the dctionary, the programm returns me an error: "error: bad character range o-K at position 14" Can you help me to solve this two issues? Any further improvments of the code are higly appreciated as well. Dictionary can be found here: https://github.com/adambom/dictionary
has title: Interactive dictionary programm in python
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91188074
favorite count: 0
has comment: http://stackoverflow.com/comment/91188426
tagged with: python
tagged with: dictionary
tagged with: regex
type: UnansweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/52119281
has answer: http://stackoverflow.com/a/52119079
type: Question

http://stackoverflow.com/q/52160472
tagged with: indexing
has answer: http://stackoverflow.com/a/52160522
upvote count: 1
tagged with: slice
answer count: 1
has body: Actually I thougth this should be very easy. I have a pandas data frame with lets say 100 colums and I want a subset containing colums 0:30 and 77:99. What I've done so far is: df_1 = df.iloc[:,0:30] df_2 = df.iloc[:,77:99] df2 = pd.concat([df_1 , df_2], axis=1, join_axes=[df_1 .index]) Is there an easier way?
type: UnansweredQuestion
tagged with: dataframe
tagged with: pandas
downvote count: 0
score: 1
favorite count: 0
has title: Slicing Pandas data frame into two parts
type: Question
tagged with: python

http://stackoverflow.com/a/52139618
has comment: http://stackoverflow.com/comment/91236283
has comment: http://stackoverflow.com/comment/91230908
score: 12
has comment: http://stackoverflow.com/comment/91231210
has comment: http://stackoverflow.com/comment/91229915
upvote count: 12
downvote count: 0
has comment: http://stackoverflow.com/comment/91231108
has comment: http://stackoverflow.com/comment/91230164
type: Answer
has comment: http://stackoverflow.com/comment/91231418
has body: The distinction one-to-one, one-to-many, many-to-one, many-to-many is only existent in case of RNN / LSTM or networks that work on sequential ( temporal ) data, CNNs work on spatial data there this distinction does not exist. So many always involves multiple timesteps / a sequence The different species describe the shape of input and output and its classification. For the input one means a single input quantity is classified as a closed quantity and many means a sequence of quantities ( i.e. sequence of images, sequence of words) is classified as a closed quantity. For the output one means the output is a scalar ( binary classification i.e. is a bird or is not a bird ) 0 or 1, many means output is a one-hot encoded vector with one dimension for each class ( multiclass classification i.e. is a sparrow, is a robin, ... ), for i.e. three classes 001, 010, 100 : In the following example images and sequences of images are used as quantity that shall be classified, alternatively you could use words or ... and sequences of words ( sentences ) or ... : one-to-one : single images ( or words,... ) are classified in single class ( binary classification ) i.e. is this a bird or not one-to-many : single images ( or words,... ) are classified in multiple classes many-to-one : sequence of images ( or words, ... ) is classified in single class ( binary classification of a sequence ) many-to-many : sequence of images ( or words, ... ) is classified in multiple classes cf https://www.quora.com/How-can-I-choose-between-one-to-one-one-to-many-many-to-one-many-to-one-and-many-to-many-in-long-short-term-memory-LSTM one-to-one ( activation=sigmoid ( default ) loss=mean_squared_error ) from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM # prepare sequence length = 5 seq = array([i/float(length) for i in range(length)]) X = seq.reshape(len(seq), 1, 1) y = seq.reshape(len(seq), 1) # define LSTM configuration n_neurons = length n_batch = length n_e…
answers question: http://stackoverflow.com/q/52138290
has comment: http://stackoverflow.com/comment/91231015

file
type: Tag
tags question: http://stackoverflow.com/q/52183096
tags question: http://stackoverflow.com/q/52167324
tags question: http://stackoverflow.com/q/52128164
tags question: http://stackoverflow.com/q/52147871
tags question: http://stackoverflow.com/q/52199185
tags question: http://stackoverflow.com/q/52148524
tags question: http://stackoverflow.com/q/52187121
tag name: file
tags question: http://stackoverflow.com/q/52257639
tags question: http://stackoverflow.com/q/52157755
tags question: http://stackoverflow.com/q/52195658
tags question: http://stackoverflow.com/q/52137505
tags question: http://stackoverflow.com/q/52200409
tags question: http://stackoverflow.com/q/52259924
tags question: http://stackoverflow.com/q/52209124
tags question: http://stackoverflow.com/q/52240014
tags question: http://stackoverflow.com/q/52246869
tags question: http://stackoverflow.com/q/52152286
tags question: http://stackoverflow.com/q/52250266
tags question: http://stackoverflow.com/q/52183357
tags question: http://stackoverflow.com/q/52195903
tags question: http://stackoverflow.com/q/52113222
tags question: http://stackoverflow.com/q/52261986
tags question: http://stackoverflow.com/q/52130385
tags question: http://stackoverflow.com/q/52176999
tags question: http://stackoverflow.com/q/52173729
tags question: http://stackoverflow.com/q/52209456
tags question: http://stackoverflow.com/q/52239783
tags question: http://stackoverflow.com/q/52117156
tags question: http://stackoverflow.com/q/52269397

http://stackoverflow.com/q/52127766
type: UnansweredQuestion
tagged with: dataframe
type: Question
score: 0
has answer: http://stackoverflow.com/a/52127828
has title: pandas dataframe dealing with 'list' elements in a nice way
answer count: 1
has body: Update: @AntonvBR 's answer worked. Thank you very much! Besides, since here I'm dealing with each element in one tea's column, so indeed it's a Series rather than a DataFrame. Thus I guess .apply() works the same as .map(). Original question: I'm sorry for not knowing how to express my better, but here is this question: Say there're two DataFrames, STUDENT and TEACHER. The STUDENT DataFrame has two columns: ID and home(which city does she or he come from). Of course, the IDs are unique. On the other hand, the TEACHER DataFrame also has two columns: ID and the list of the students' ids (in their class). The two are like this: In [72]: stu Out[72]: ID home 0 1 XA 1 2 BJ 2 3 TJ 3 4 JN 4 5 CQ 5 6 SH 6 7 GZ 7 8 BJ 8 9 TJ 9 10 BJ In [75]: tea Out[75]: ID stu 0 1 [1, 2, 3] 1 2 [2, 7, 8, 9] 2 3 [4, 5, 6, 10] And now I want to add a third column on TEACHER, which also contains a list of the teachers' students' 'home', and there should be no duplicate in each list. So I wonder how can I do this in a pandas way, which looks neat and clean? I'm new to pandas and SQL, and the only way I come up with is to iterate on each row, and iterate on each list, and fetch the value from another DataFrame and append them one by one... Please give me some advice or hints. Thank you very much.
tagged with: pandas
tagged with: python

http://stackoverflow.com/q/52220609
tagged with: python
tagged with: opencv
has comment: http://stackoverflow.com/comment/91411755
has comment: http://stackoverflow.com/comment/91426796
has answer: http://stackoverflow.com/a/58094730
has body: For some reason, the stitcher bindings seem to be missing from my opencv python bindings. For example, this code: import cv2 stitcher = cv2.createStitcher(False) foo = cv2.imread("foo.png") bar = cv2.imread("bar.png") result = stitcher.stitch((foo,bar)) cv2.imwrite("result.jpg", result[1]) results in this error: AttributeError: 'module' object has no attribute 'createStitcher' Running a help(cv2) within the python interpreter also shows that the function simply is not there.
type: Question
has answer: http://stackoverflow.com/a/54259311
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91429177
type: UnansweredQuestion
has title: Stitcher API seems to be missing from my python opencv bindings

http://stackoverflow.com/comment/91482164
comment on: http://stackoverflow.com/a/52252552
type: AnswerComment
score: 0
has text: But, I'm getting same score for accuracy, precision and recall. Is this possible ?
type: Comment

http://stackoverflow.com/comment/115095417
score: 0
comment on: http://stackoverflow.com/q/52112783
type: Comment
type: QuestionComment
has text: @brunodesthuilliers No the link doesn't contain what the OP has asked. Read more **carefully**. OP wants to detect if a substring of a larger string is a date or note. What the other question does is, it does not check for a substring but check whether the whole string is a date or not.

http://stackoverflow.com/q/52161751
has comment: http://stackoverflow.com/comment/109451024
upvote count: 1
tagged with: model-mommy
tagged with: django
has title: Creating reverse relationship objects with Model Mommy
has comment: http://stackoverflow.com/comment/98295555
has body: I use Model Mommy for creating test data and it's working fine so far. Now I have a Django model named Invoice and a related model named InvoiceItem. class Invoice(models.Model): created_by = models.ForeignKey(users.User) class InvoiceItem(models.Model): invoice = models.ForeignKey(Invoice, related_name='items') I've created two simple Mommy recipes for these models: InvoiceRecipe = Recipe( Invoice, created_by=foreign_key(UserRecipe), ) InvoiceItemRecipe = Recipe( InvoiceItem, invoice=foreign_key(InvoiceRecipe), ) Now I'd like InvoiceRecipe.make() to automatically add a varying number of InvoiceItem objects to the invoice that is created. Currently, I'm doing it like this, but I'd like it to automatically happen: invoice = InvoiceRecipe.make(created_by=contractor) invoice.items.add(InvoiceItemRecipe.make()) invoice.items.add(InvoiceItemRecipe.make())
score: 1
has comment: http://stackoverflow.com/comment/98163924
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/98291948
tagged with: python
favorite count: 0
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52141785
tagged with: performance
has answer: http://stackoverflow.com/a/52142700
upvote count: 13
tagged with: sorting
has answer: http://stackoverflow.com/a/68811771
has answer: http://stackoverflow.com/a/52141806
has comment: http://stackoverflow.com/comment/91233463
has comment: http://stackoverflow.com/comment/91233485
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/77797116
answer count: 5
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/52141806
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/9001509
downvote count: 0
has title: Sort Dict by Values in Python 3.6+
score: 13
accepted answer: http://stackoverflow.com/a/68811771
has body: I was looking for a method to sort a dictionary in Python with its values, after a few attempts, is what it comes: a = {&lt;populated dict...&gt;} a = {v: k for k, v in a.items()} a = {v: k for k, v in sorted(a.items())} This code seems to work, but I think it's poor for performance, is there a better way?
has answer: http://stackoverflow.com/a/59009606
type: Question

http://stackoverflow.com/a/52956868
downvote count: 0
has body: I've been following the same programming tutorial as you and I got everything working using Python 3.7. The only difference is that I'm using Linux and you're using MacOS. The problem here is not Python 3.7. Instead, the problem is indicated by this snippet: Library not loaded: @rpath/libmysqlclient.21.dylib Referenced from: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/_mysql.cpython-37m-darwin.so Reason: image not found** The problem is that the MySQL package can't find the dynamic library _mysql.cpython-37m-darwin.so as discussed in another thread. The dynamic library should be available in the /usr/local/mysql/lib directory. If it is in that directory, then you just need to modify the $DYLD_LIBRARY_PATH variable with the following command: export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/:$DYLD_LIBRARY_PATH.
type: Answer
has comment: http://stackoverflow.com/comment/96862412
answers question: http://stackoverflow.com/q/52261686
score: 7
upvote count: 7

http://stackoverflow.com/a/52199219
answers question: http://stackoverflow.com/q/52198924
upvote count: 1
has body: If you want to avoid the extra spaces, you can filter out items that aren't 'truthy': test = "BigMart has collected 2013 sales data for 1559 products across 10 stores in different cities. The aim is to build a predictive model and find out the sales of each product at a store." words = [word for word in test.split(' ') if word] for word in words: print(word)
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/52170449
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52170059
accepted answer of: http://stackoverflow.com/q/52170059
type: Answer
has comment: http://stackoverflow.com/comment/91300989
has body: if delimit by tab '\t' doesn't work use : df = pd.read_table(filename,delim_whitespace=True,skiprows = 'number_of_rows_before_the_headers_start') this is similar to using delimiter=r"\s+" but i feel the above method is faster than the regex.

http://stackoverflow.com/comment/91363587
type: Comment
comment on: http://stackoverflow.com/q/52207120
type: QuestionComment
has text: Could you point me to one of the previous answers?
score: 0

http://stackoverflow.com/q/52264355
tagged with: python-3.7
tagged with: sqlite
answer count: 1
downvote count: 0
has body: I have a script that I built following the blueprint in the book Learning Python for Forensics. The script will go through a directory specified by the user and collect the metadata for each file in the directory. The results are saved to a sqlite database and also written to a CSV or HTML file. The script was originally written in Python 2.7.15. I am trying to update the code for Python 3.7. However, there is one line in the ingest directory function that is giving me issues. The ingestDirectory function looks like this: def ingestDirectory(cur, source, custodian_id): count = 0 for root, folders, files in os.walk(source): for file_name in files: meta_data = dict() try: meta_data['file_name'] = file_name meta_data['file_path'] = os.path.join(root, file_name) meta_data['extension'] = os.path.splitext(file_name)[-1] file_stats = os.stat(meta_data['file_path']) meta_data['mode'] = oct(file_stats.st_mode) meta_data['inode'] = int(file_stats.st_ino) meta_data['file_size'] = int(file_stats.st_size) meta_data['atime'] = formatTimestamp(file_stats.st_atime) meta_data['mtime'] = formatTimestamp(file_stats.st_mtime) meta_data['ctime'] = formatTimestamp(file_stats.st_ctime) except Exception as e: logging.error('Could not gather data for file: ' + meta_data['file_path'] + e.__str__()) meta_data['custodian'] = custodian_id columns = '","'.join(meta_data.keys()) values = '","'.join(str(x).encode('string_escape') for x in meta_data.values()) sql = 'INSERT INTO Files ("' + columns + '") VALUES ("' + values + '")' cur.execute(sql) count += 1 The line that is giving me errors is this: values = '","'.join(str(x).encode('string_escape') for x in meta_data.values()) This line is meant to handle any string escape characters found in metadata.values before writing the data to the database. When I tried to run this code in Python 3 I got an error about an unrecognized codec. I did some research hear on Stack Overflow and found that string_escape has been replaced with unicode-escape in Pyt…
favorite count: 0
has comment: http://stackoverflow.com/comment/91476762
tagged with: unicode-escapes
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52264549
has comment: http://stackoverflow.com/comment/91476992
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91476807
has title: Python 3 unicode-escape
type: Question
accepted answer: http://stackoverflow.com/a/52264549
has comment: http://stackoverflow.com/comment/91477565
has comment: http://stackoverflow.com/comment/91476719

http://stackoverflow.com/a/52223944
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52223784
score: 3
has comment: http://stackoverflow.com/comment/138281311
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52223784
has body: You can create your own error handler which will capture standard error. For example like this; import sys import traceback from matplotlib.backends.qt_compat import QtWidgets from initial import InitialWindow def error_handler(etype, value, tb): error_msg = ''.join(traceback.format_exception(etype, value, tb)) # do something with the error message, for example print it if __name__ == '__main__': sys.excepthook = error_handler # redirect std error app = QtWidgets.QApplication([]) ex = InitialWindow() ex.show() app.exec_()
has comment: http://stackoverflow.com/comment/91398175
type: Answer

http://stackoverflow.com/comment/91409494
has text: Do you have a cut-n-paste error or is that a syntax error with the extra single quote right before the first vertical bar: `.*$'|/inv` right in there.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52229785

http://stackoverflow.com/comment/91369456
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52209977
score: 0
has text: if your problem is scrolling the list so the last number come first you can you write outa = list[-1]+list[:-1]

http://stackoverflow.com/a/52134123
downvote count: 0
answers question: http://stackoverflow.com/q/52133815
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52133815
has body: I have to assume you mean the maximum integer value. You have mixed types str and int. So start with converting everything to strings. Then you find the maximum of the comma separated strings using int as the key Convert to integers df.assign( maxA= df['a'].astype(str).apply(lambda x: max(x.split(','), key=int)).astype(int) ) a maxA 0 1,2 2 1 3 3 2 -1 -1 3 8,9,1 9 4 21,111 111 Take note of row labeled 4. 21,111 returns a maximum of 111 Setup df=pd.DataFrame({'a':['1,2',3,-1,'8,9,1','21,111']})
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/52141920
has title: transfering data from txt file to an array (list index out of range)
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/91233669
has body: I am have issues witch transfering data from my text file into my array. As when i try to put data from the text file into the array it comes up with a list index out of range error. I just need a simple way of transfering a username and password into 2 different arrays. username = [] password = [] lr = open("login.txt","r") loginr = "temp" while loginr!="": loginr = lr.readline() field = loginr.split(",") username.append(field[0]) password.append(field[1]) print(username+password) lr.close() The text file is layed out as simple,123, legit,scary, smite,Oxygen31,
has comment: http://stackoverflow.com/comment/91233806
has comment: http://stackoverflow.com/comment/91233681
type: Question
has comment: http://stackoverflow.com/comment/91233830
has answer: http://stackoverflow.com/a/52142002
accepted answer: http://stackoverflow.com/a/52142002
score: -1
answer count: 1
downvote count: 1
tagged with: arrays
favorite count: 0

http://stackoverflow.com/a/52181694
type: Answer
score: 2
upvote count: 2
has body: You have to change the QImage that is stored in the image attribute of ImageWidget; maybe add an update method like this: def update(self, surface) self.data=surface.get_buffer().raw self.image=QtGui.QImage(self.data,w,h,QtGui.QImage.Format_RGB32) (or store the surface in an attribute)
downvote count: 0
answers question: http://stackoverflow.com/q/52174384

http://stackoverflow.com/q/52232742
score: 21
upvote count: 21
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91414775
has comment: http://stackoverflow.com/comment/91414643
has answer: http://stackoverflow.com/a/56842372
downvote count: 0
has comment: http://stackoverflow.com/comment/91414681
tagged with: tuples
has comment: http://stackoverflow.com/comment/91414778
tagged with: pandas
has answer: http://stackoverflow.com/a/52232833
favorite count: 0
type: UnansweredQuestion
has body: I have a dataframe with a column containing a tuple data as a string. Eg. '(5,6)'. I need to convert this to a tuple structure. One way of doing it is using the ast.literal_eval(). I am using it in this way. df['Column'] = df['Column'].apply(ast.literal_eval) Unfortunately, my data in this column contains empty strings also. The ast.literal_eval() is not able to handle this. I get this error. SyntaxError: unexpected EOF while parsing I am unsure if this is because it is unable to handle such a character. Based on my reading, I found that ast.literal_eval() works only in cases when a list, dict or tuple is there inside a string structure. To overcome this I tried to create my own function and return an empty string if it raises an exception. def literal_return(val): try: return ast.literal_eval(val) except ValueError: return (val) df['Column2'] = df['Column'].apply(literal_return) Even in this case, the same error pops up. How do we handle this. It would be great even if there is a way to ignore certain rows to apply the function and apply on the rest. Any help is appreciated.
tagged with: python
has title: How to use ast.literal_eval in a pandas dataframe and handle exceptions

http://stackoverflow.com/comment/91339209
comment on: http://stackoverflow.com/q/52194750
has text: Sorry, in my mind I was thinking of dicts as objects, and I was assuming the same syntax for setting dict attributes was the same as setting object attribute. Would the sytax dict[attrib] = 1 work for dicts only then?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/52248986
has comment: http://stackoverflow.com/comment/91446293
has comment: http://stackoverflow.com/comment/91446422
type: Answer
has comment: http://stackoverflow.com/comment/91446427
has body: Use below command for installing pip on Mac: easy_install pip If you need admin privileges to run this, try: sudo easy_install pip Use below command for installing pyserial: pip install pyserial I hope this helps.
has comment: http://stackoverflow.com/comment/91446460
answers question: http://stackoverflow.com/q/52248950
has comment: http://stackoverflow.com/comment/91446168
has comment: http://stackoverflow.com/comment/91446420
score: 0
has comment: http://stackoverflow.com/comment/91446304
has comment: http://stackoverflow.com/comment/91446110

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/52244474
tags question: http://stackoverflow.com/q/52125807
type: Tag
tags question: http://stackoverflow.com/q/52196721
tags question: http://stackoverflow.com/q/52227540
tags question: http://stackoverflow.com/q/52255858
tags question: http://stackoverflow.com/q/52149781
tags question: http://stackoverflow.com/q/52128113
tags question: http://stackoverflow.com/q/52134716
tags question: http://stackoverflow.com/q/52219249
tags question: http://stackoverflow.com/q/52258451
tags question: http://stackoverflow.com/q/52250266
tag name: csv
tags question: http://stackoverflow.com/q/52145678
tags question: http://stackoverflow.com/q/52240428
tags question: http://stackoverflow.com/q/52256085
tags question: http://stackoverflow.com/q/52160584
tags question: http://stackoverflow.com/q/52152512
tags question: http://stackoverflow.com/q/52184125
tags question: http://stackoverflow.com/q/52154312
tags question: http://stackoverflow.com/q/52218891
tags question: http://stackoverflow.com/q/52169497
tags question: http://stackoverflow.com/q/52152365
tags question: http://stackoverflow.com/q/52207930
tags question: http://stackoverflow.com/q/52138930
tags question: http://stackoverflow.com/q/52170500
tags question: http://stackoverflow.com/q/52122119
tags question: http://stackoverflow.com/q/52210456
tags question: http://stackoverflow.com/q/52224725
tags question: http://stackoverflow.com/q/52251107
tags question: http://stackoverflow.com/q/52155946
tags question: http://stackoverflow.com/q/52148667
tags question: http://stackoverflow.com/q/52197107
tags question: http://stackoverflow.com/q/52245335
tags question: http://stackoverflow.com/q/52155189
tags question: http://stackoverflow.com/q/52145057
tags question: http://stackoverflow.com/q/52199952
tags question: http://stackoverflow.com/q/52186556
tags question: http://stackoverflow.com/q/52120651
tags question: http://stackoverflow.com/q/52251517
tags question: http://stackoverflow.com/q/52235221
tags question: http://stackoverflow.com/q/52130073
tags question: http://stackoverflow.com/q/52139859
tags question: http://stackoverflow.com/q/52128407
tags question: http://stackoverflow.com/q/52259148
tags question: http://stackoverflow.com/q/52261698
tags question: http://stackoverflow.com/q/52138964
tags question: http://stackoverflow.com/q/52139037
tags question: http://stackoverflow.com/q/52247428
tags question: http://stackoverflow.com/q/52230639
tags question: http://stackoverflow.com/q/52244801
tags question: http://stackoverflow.com/q/52172346
tags question: http://stackoverflow.com/q/52174767
tags question: http://stackoverflow.com/q/52263399
tags question: http://stackoverflow.com/q/52165826
tags question: http://stackoverflow.com/q/52122146
tags question: http://stackoverflow.com/q/52142814
tags question: http://stackoverflow.com/q/52166302
tags question: http://stackoverflow.com/q/52177034
tags question: http://stackoverflow.com/q/52174371
tags question: http://stackoverflow.com/q/52260968
tags question: http://stackoverflow.com/q/52215155
tags question: http://stackoverflow.com/q/52167284
tags question: http://stackoverflow.com/q/52270815
tags question: http://stackoverflow.com/q/52240080
tags question: http://stackoverflow.com/q/52186560
tags question: http://stackoverflow.com/q/52228651
tags question: http://stackoverflow.com/q/52181080
tags question: http://stackoverflow.com/q/52229212
tags question: http://stackoverflow.com/q/52238621
tags question: http://stackoverflow.com/q/52135459
tags question: http://stackoverflow.com/q/52207394
tags question: http://stackoverflow.com/q/52122750
tags question: http://stackoverflow.com/q/52175351
tags question: http://stackoverflow.com/q/52263923
tags question: http://stackoverflow.com/q/52114689
tags question: http://stackoverflow.com/q/52183696
tags question: http://stackoverflow.com/q/52207200
tags question: http://stackoverflow.com/q/52138324
tags question: http://stackoverflow.com/q/52263112

http://stackoverflow.com/comment/91338415
score: 1
type: QuestionComment
has text: Possible duplicate of [error: command 'x86\_64-linux-gnu-gcc' when installing mysqlclient](https://stackoverflow.com/questions/33315210/error-command-x86-64-linux-gnu-gcc-when-installing-mysqlclient)
comment on: http://stackoverflow.com/q/52193937
type: Comment

http://stackoverflow.com/a/52142710
score: 1
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52142237
has body: 2018-09-03_map_with_pandas.ipynb import pandas as pd df = pd.read_csv('data/RBefh.csv', dtype=str) keys = list(df['to_search'].dropna()) values = list(df['value_to_copy'].dropna()) map_values = dict(zip(keys, values)) mapper = df.to_replace.isin(map_values) df.loc[mapper, 'to_replace'] = df.loc[mapper, 'to_replace'].apply(lambda row: map_values[row]) df.fillna('', inplace=True) Output: to_replace value_to_copy to_search 0 __import__.value_1 __import__.value_1 2012000401 1 __import__.value_1 __import__.value_2 2012000501 2 __import__.value_1 __import__.value_3 2012000601 3 __import__.value_2 __import__.value_4 2012000603 4 __import__.value_2 __import__.value_5 2012000604 5 __import__.value_2 __import__.value_6 2012000605 6 __import__.value_7 2012000606 7 __import__.value_2 __import__.value_8 2012000607 8 __import__.value_2 __import__.value_9 2012000608 9 __import__.value_2 __import__.value_10 2012000609 10 __import__.value_11 2012000610 11 __import__.value_2 __import__.value_12 2012000701 12 __import__.value_2 __import__.value_13 2012000702 13 __import__.value_3 14 __import__.value_4 15 __import__.value_5 16 __import__.value_6 17 __import__.value_7 18 __import__.value_8 19 __import__.value_9 20 __import__.value_10 21 __import__.value_11 22 __import__.value_12 23 __import__.value_12 24 __import__.value_12 25 __import__.value_12 26 __import__.value_12 27 __import__.value_12 28 __import__.value_12 29 2012999999

http://stackoverflow.com/comment/91336933
comment on: http://stackoverflow.com/q/52193580
score: 0
has text: What if you added opening and closing braces and then did a safe eval?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52268819
answers question: http://stackoverflow.com/q/52268613
score: 0
has body: The following seems to work - I think it just needed a 'display' command added: from IPython.display import display a = widgets.IntSlider(description='a') b = widgets.IntSlider(description='b') c = widgets.IntSlider(description='c') def f(a, b, c): print('{}*{}*{}={}'.format(a, b, c, a*b*c)) def f2(a, b, c): print(Markdown('${}\\times{}\\times{}={}$'.format(a, b, c, a*b*c))) def f3(a, b, c): display(Markdown('${}\\times{}\\times{}={}$'.format(a, b, c, a*b*c))) out = widgets.interactive_output(f3, {'a': a, 'b': b, 'c': c}) widgets.HBox([widgets.VBox([a, b, c]), out])
type: Answer

http://stackoverflow.com/a/52209238
has comment: http://stackoverflow.com/comment/91369371
has body: with(open('sample.txt', 'r') as f: for l in f: print(l[l.index(':')+2:]) number = l[l.index(':')+2:] This answer works regardless of what comes before the colon. I just included the print statement in there so you could see what you are getting. The second line in the for loop is what gets the number for each line in your file.
type: Answer
answers question: http://stackoverflow.com/q/52209124
score: 0

http://stackoverflow.com/comment/91427255
score: 0
has text: `python` is imperative. Coding in it is quite normal without returning values. Should calling to `g2` be deeply routed via many intermediate functions, all of them would have to be refactored according to your proposal.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52239185

http://stackoverflow.com/q/52118454
has title: automatically making matplotlib image flush with other subplot label
upvote count: 1
tagged with: image
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52119449
has comment: http://stackoverflow.com/comment/91192410
downvote count: 0
tagged with: data-science
linked to: http://stackoverflow.com/q/332289
has comment: http://stackoverflow.com/comment/91189097
has comment: http://stackoverflow.com/comment/91192172
has body: The problem I am trying to plot an image next to some data. However, I would like the image to expand to be flush with the plot labels. For example, the following code (using this tutorial image): # make the incorrect figure import matplotlib.pyplot as plt import matplotlib.image as mpimg fig = plt.figure(figsize=(8,3)) ax_image = plt.subplot(1,2,1) plt.imshow(mpimg.imread('stinkbug.png')) plt.subplot(1,2,2) plt.plot([0,1],[2,3]) plt.ylabel("y") plt.xlabel("want image flush with bottom of this label") fig.tight_layout() ax_image.axis('off') fig.savefig("incorrect.png") yields this plot, with extra whitespace: The hacky attempt at a solution I would like a plot that doesn't waste whitespace. The following hacky code (in the vein of this SO link) accomplishes this: # make the correct figure with manually changing the size import matplotlib.pyplot as plt import matplotlib.image as mpimg fig = plt.figure(figsize=(8,3)) ax_image = fig.add_axes([0.02,0,0.45,1.0]) plt.imshow(mpimg.imread('stinkbug.png')) plt.subplot(1,2,2) plt.plot([0,1],[2,3]) plt.ylabel("y") plt.xlabel("want image flush with bottom of this label") fig.tight_layout() ax_image.axis('off') fig.savefig("correct.png") yielding the following figure: The question Is there any way to plot an image flush with other subplots, without having to resort to manual adjustment of figure sizes?
answer count: 1
accepted answer: http://stackoverflow.com/a/52119449
favorite count: 0
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91188022
score: 1
has comment: http://stackoverflow.com/comment/91188057
tagged with: matplotlib

http://stackoverflow.com/q/52266674
has answer: http://stackoverflow.com/a/52280081
tagged with: user-interface
has comment: http://stackoverflow.com/comment/91481292
answer count: 1
tagged with: python
favorite count: 0
has title: TK GUI design issues and object has no attribute 'tk'?
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/52280081
downvote count: 2
has comment: http://stackoverflow.com/comment/91483566
upvote count: 1
has comment: http://stackoverflow.com/comment/91484081
has body: Below is the the code that I currently have. I am beginner programmer and am writing a small program that will automate some workflow for primer design (biologist / bioinformaticists represent). The issue I have right now is that my lack of understanding of how OOP works with TKinter. I have read numerous stackoverflow posts and watched youtube videos and read guides that try to explain it but I am still somewhat at a loss. My current understanding is that each window should be its own object, with the window above it as its parent. I've attempted to do this with my program. Currently I have two classes, AUTOPRIMER, and BlastAPI. AUTOPRIMER is the main window. There is a button in that window that I have created that should open up a new window when clicked. From my understanding, I have created a new object for that window called BlastAPI which deals with that particular requirement of my program. I see many guides that suggest the parent should be put in the init of the new object, but there are so many initialization variations I have seen from parent to master to args*, kwargs**. What is appropriate when? Also, currently the stack trace provides this feedback as it doesn't even compile properly. Traceback (most recent call last): File "/Users/Thunderpurtz/Desktop/CGIStuff/AUTOPRIMER/autoprimercode/test1.py", line 201, in &lt;module&gt; autoprimer = AUTOPRIMER(root) File "/Users/Thunderpurtz/Desktop/CGIStuff/AUTOPRIMER/autoprimercode/test1.py", line 105, in __init__ self.blast = BlastAPI(self) File "/Users/Thunderpurtz/Desktop/CGIStuff/AUTOPRIMER/autoprimercode/test1.py", line 150, in __init__ eValueSetting = Entry(parent) File "/anaconda3/lib/python3.6/tkinter/__init__.py", line 2673, in __init__ Widget.__init__(self, master, 'entry', cnf, kw) File "/anaconda3/lib/python3.6/tkinter/__init__.py", line 2289, in __init__ BaseWidget._setup(self, master, cnf) File "/anaconda3/lib/python3.6/tkinter/__init__.py", line 2259, in _setup self.tk = master.tk AttributeError:…
has comment: http://stackoverflow.com/comment/91481435
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91484065
score: -1
type: Question

http://stackoverflow.com/a/52244065
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91443885
type: Answer
upvote count: 6
has body: There are a few related approaches, split into two camps. You can either use a vectorised approach via calculation of a single Boolean array and np.ndarray.all. Or you can calculate the index of the first row which contains only 0 elements, either via a for loop or next with a generator expression. For performance, I recommend you use numba with a manual for loop. Here's one example, but see benchmarking below for a more efficient variant: from numba import jit @jit(nopython=True) def trim_enum_nb(A): for idx in range(A.shape[0]): if (A[idx]==0).all(): break return A[:idx] Performance benchmarking # python 3.6.5, numpy 1.14.3 %timeit trim_enum_loop(A) # 9.09 ms %timeit trim_enum_nb(A) # 193 µs %timeit trim_enum_nb2(A) # 2.2 µs %timeit trim_enum_gen(A) # 8.89 ms %timeit trim_vect(A) # 3.09 ms %timeit trim_searchsorted(A) # 7.67 µs Test code Setup import numpy as np from numba import jit np.random.seed(0) n = 120000 k = 1500 A = np.random.randint(1, 10, (n, 3)) A[k:, :] = 0 Functions def trim_enum_loop(A): for idx, row in enumerate(A): if (row==0).all(): break return A[:idx] @jit(nopython=True) def trim_enum_nb(A): for idx in range(A.shape[0]): if (A[idx]==0).all(): break return A[:idx] @jit(nopython=True) def trim_enum_nb2(A): for idx in range(A.shape[0]): res = False for col in range(A.shape[1]): res |= A[idx, col] if res: break return A[:idx] def trim_enum_gen(A): idx = next(idx for idx, row in enumerate(A) if (row==0).all()) return A[:idx] def trim_vect(A): idx = np.where((A == 0).all(1))[0][0] return A[:idx] def trim_searchsorted(A): B = np.frombuffer(A, 'S12') idx = A.shape[0] - np.searchsorted(B[::-1], B[-1:], 'right')[0] return A[:idx] Checks # check all results are the same assert (trim_vect(A) == trim_enum_loop(A)).all() assert (trim_vect(A) == trim_enum_nb(A)).all() assert (trim_vect(A) == trim_enum_nb2(A)).all() assert (trim_vect(A) == trim_enum_gen(A)).all() assert (trim_vect(A) == trim_searchsorted(A)).all()
answers question: http://stackoverflow.com/q/52243734
score: 6
has comment: http://stackoverflow.com/comment/91440203
has comment: http://stackoverflow.com/comment/91443266
accepted answer of: http://stackoverflow.com/q/52243734
has comment: http://stackoverflow.com/comment/91440139

http://stackoverflow.com/comment/91294792
has text: My difficulty is I do not know where to start. The output table should insert 4 new columns in my data frame and then fill the columns with values based in the reference table based on the relevant month. For example, for 'apples' in August return weight=heavy for 'apples' in September weight=small
type: Comment
comment on: http://stackoverflow.com/q/52156905
score: 0
type: QuestionComment

http://stackoverflow.com/q/52233987
accepted answer: http://stackoverflow.com/a/52234117
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/52234145
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91416940
has body: Data: Github_Link The dataframe looks like this: I am trying to delete commas in the first row(there are some stuff like '1,000') but there is a key error:'Price' Code: import pandas def main(): df=pandas.read_csv("Rent_Message.csv",index_col=0) df=df.drop(df.columns[df.columns.str.contains('Unnamed',case = False)],axis = 1) df['Price'] = df['Price'].str.replace(",").astype(float) main()
possible better answer: http://stackoverflow.com/a/52234145
score: 0
has comment: http://stackoverflow.com/comment/91416808
answer count: 2
has answer: http://stackoverflow.com/a/52234117
tagged with: pandas
has comment: http://stackoverflow.com/comment/91416798
favorite count: 0
has comment: http://stackoverflow.com/comment/91416817
has title: key error when deleting comma in .csv file
tagged with: python

http://stackoverflow.com/q/52246551
has comment: http://stackoverflow.com/comment/91441331
has title: Problem with pagination in template django?
type: Question
accepted answer: http://stackoverflow.com/a/52246728
tagged with: django
tagged with: python
answer count: 1
score: 0
has body: I have such view in my application and I try to paginate in in my temlate. But prev and next don't work. What's wrong? class ForMenView(ListView): model = Post template_name = 'man_index.html' context_object_name = 'all_posts' paginate_by = 1 def get_queryset(self): query = self.request.GET.get('q') qs = Post.objects.filter(sex='M', is_published=True) if query: return qs.filter(title__icontains=query) return qs def get_paginate_by(self, queryset): user = self.request.user if user.is_authenticated and user.sex == 'M': return 1 return self.paginate_by def dispatch(self, request, *args, **kwargs): user = self.request.user if user.is_authenticated and user.sex == 'W': return redirect('/forwomen') # please replace it with the view name else: return super(ForMenView, self).dispatch(self.request ,*args, **kwargs) def get_context_data(self, *args, **kwargs): kwargs = super(ForMenView, self).get_context_data(*args, **kwargs) kwargs['page_range'] = kwargs['paginator'].page_range return kwargs And in my template I try to paginate such way THIS DOESN'T DISPLAY AT ALL {% if all_posts.has_previous %} Prev {% endif %} {% for x in page_range %} {{ x }} {% endfor %} THIS DOESN'T DISPLAY TOO {% if all_posts.has_next %} Next {% endif %} My context value of {{all_posts}} = <[Post: TitlePost]> Why dont previous and next work?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52246728

http://stackoverflow.com/a/52175681
score: 1
upvote count: 1
has body: One solution is to transform your lists into np.arrays and use simple sum a['v'] = a.v.transform(np.array) a.groupby('grp').v.apply(lambda x: x.sum()) grp v 0 test [5, 7, 9, 11, 13] Notice that I changed values to v not to be mistaken with the .values accessor from pd.DataFrame
answers question: http://stackoverflow.com/q/52175650
downvote count: 0
type: Answer

http://stackoverflow.com/a/52240586
has body: That's because your lambda is using the global variable formatstring when computed. formatstring equals {:0&gt;4}, the value set to it in the last iteration. Another simpler example: y = 5 f = lambda x: print(x+y) f(2) # prints 7 y = 10 f(2) # prints 12 How to solve this One way to solve this is to get rid of the lambdas altogether. A hacky example: df.set_index('nme',inplace=True) coll = df.to_dict(orient='index') '0'*coll['a']['width']+str(3) # prints '003' You can convert the last line to a function (or a lambda) if you want.
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91431099
accepted answer of: http://stackoverflow.com/q/52236610
type: Answer
answers question: http://stackoverflow.com/q/52236610
upvote count: 1

http://stackoverflow.com/comment/91486856
score: 0
has text: @Tomalak Thank you so much. I tried but it has Attribute error when I run "get_page" section.
type: Comment
comment on: http://stackoverflow.com/q/52251228
type: QuestionComment

http://stackoverflow.com/comment/91236065
type: Comment
type: QuestionComment
has text: I'm saying that when I restart the kernel and run the code, it maximizes the first time. When I run the code 2nd time on wards, it minimizes.
score: 1
comment on: http://stackoverflow.com/q/52133173

http://stackoverflow.com/q/52244443
tagged with: python
score: 2
upvote count: 2
has title: In place modification of larger than memory Dask array
type: UnansweredQuestion
type: Question
has body: I have a dask array, X, that is approx. 3500 by 700000. Each row has missing values that I need to impute according to the mean of that row. Currently this array is stored as a dask array, and I have a delayed function that can perform the imputation. When I use the compute method however, the memory fills up as it seems to be attempting to leave me with a numpy array. Is there a way I can apply this imputation on the array in place such that I end up with the imputed array as an out of memory dask array?
answer count: 1
tagged with: arrays
downvote count: 0
favorite count: 0
tagged with: dask
has answer: http://stackoverflow.com/a/52391767
has comment: http://stackoverflow.com/comment/91442418

http://stackoverflow.com/q/52211636
type: UnansweredQuestion
tagged with: python
downvote count: 6
linked to: http://stackoverflow.com/q/20002503
duplicate of: http://stackoverflow.com/q/20002503
type: Question
has body: I'm working with Python and I have nearly written some code as part of a required assignment. #------Unit converter------# #-------Challenge 5-------# #-------Definitions-------# def currencyConvert(): print("C") def tempConvert(): print("T") def massConvert(): print("M") def volConvert(): print("V") #-------Executions--------# print("Welcome to my unit converter.\nIn this software, you can convert between the following things:") print(" - Currency: United States Dollar (USD), Pound Sterling (GBP) and Serbian Dinar (RDS).") print(" - Temperature: Fahrenheit (F) and Celsius (C)") print(" - Mass: Pounds (lbs) and grams (mg/g/kg)") print(" - Volume: Fluid ounces (fl oz) and litres (ml/cl/l") def phaseOne(): global unitType print("--------------------") unitType = input("What kind of conversion would you like to make? Currency (C), temperature (T), mass (M) or volume (V)?\n&gt;&gt;&gt;") if unitType == "C" or "c": currencyConvert() elif unitType == "T" or "t": tempConvert() elif unitType == "M" or "m": massConvert() elif unitType == "V" or "v": volConvert() else: print("That is not a valid input. Please try again.") phaseOne() phaseOne() My problem is that when I run the program and input "V", I would expect the volConvert() function to be called (therefore outputting "V") but instead it returns "C". What is causing this? I do not have skills with Python yet, but I am working on it and need some minor help. Thank you!
has answer: http://stackoverflow.com/a/52211666
has title: Unexpected returned variable in Python
upvote count: 0
tagged with: function
answer count: 1
tagged with: string
score: -6
favorite count: 0

http://stackoverflow.com/a/52122763
has comment: http://stackoverflow.com/comment/91197440
type: Answer
score: 0
has body: The image at https://c1.staticflickr.com/4/3667/32598752764_b62a07cf43_n.jpg is 320x240, so it's not good resolution to start with... Trying something high-res, such as this, downloads high quality images. Downloading it this way should be no different than downloading it from your browser (disclaimer: I'm not a copyright lawyer).
answers question: http://stackoverflow.com/q/52122624

http://stackoverflow.com/comment/91244708
score: 1
comment on: http://stackoverflow.com/q/52147379
has text: provide a valid example, your code is too long, introduce just the interested part and give an input example for what your if statement is not working
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91345970
comment on: http://stackoverflow.com/q/52198273
type: Comment
type: QuestionComment
has text: @CSMaverick done, link and soup.find added
score: 0

http://stackoverflow.com/a/52119548
answers question: http://stackoverflow.com/q/52118032
type: Answer
upvote count: 1
has body: It is casting item as a string in the for loop. So when you're calling ['1'] it is throwing an error, where as if you set it to an integer, i.e. [1] it would bring back the second char of the key, in this case 'A' from 'AAL'. This will work if you mod it to fit your needs. import json from urllib.request import Request, urlopen request = Request("http://api.travelpayouts.com/v1/prices/cheap?origin=MOW&amp;page=1&amp; token=77e84779fa444c14806f022f6c41b7fe") response_body = urlopen(request).read() tickets = json.loads(response_body) for item in tickets['data']: if item == 'AAL': price = tickets['data'][item]['1']['price'] print(price)
score: 1
downvote count: 0

http://stackoverflow.com/q/52124033
has comment: http://stackoverflow.com/comment/91199900
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91217034
tagged with: python
has comment: http://stackoverflow.com/comment/91199281
answer count: 0
has body: I try to place post-only limit orders so that there would be no fee, and the following is the related statements: from coinbase.wallet.client import Client spot_price = client.get_spot_price(currency_pair = 'BTC-USD') priceStr = repr(float(spot_price.amount) - 25.0) buy_order = primary_account.buy(amount = '0.001', currency = 'BTC', price = priceStr, post_only = True ) print("buy_order=", buy_order, "price=", priceStr) However, it did not work as a fee of 0.99 is charged and also the price is higher. What could be wrong? OK, now I realize the problem might be that I was using the Coinbase API keys, instead of Coinbase.Pro (previously, GDAX) API keys. I have generated Pro API keys and will retry tomorrow (as it seems that the change will take place tomorrow). Thanks to everyone who tried to help. Thanks, Sean
has title: Limit order in Coinbase Pro
type: Question
has comment: http://stackoverflow.com/comment/91199269
has comment: http://stackoverflow.com/comment/91216975
score: 0
tagged with: fee
tagged with: coinbase-api

http://stackoverflow.com/comment/132271415
comment on: http://stackoverflow.com/a/71982670
type: AnswerComment
has text: Could you explain what the second line does?
score: 0
type: Comment

http://stackoverflow.com/a/52226896
upvote count: 3
has comment: http://stackoverflow.com/comment/91425929
answers question: http://stackoverflow.com/q/52206338
has comment: http://stackoverflow.com/comment/91425700
has body: If you call pd.factorize(s), where s is a Pandas Series, each element of the Series needs to be hashable. For example: &gt;&gt;&gt; s = pd.Series([1, 2, [3, 4, 5]]) &gt;&gt;&gt; s 0 1 1 2 2 [3, 4, 5] dtype: object &gt;&gt;&gt; pd.factorize(s) # this will raise &gt;&gt;&gt; pd.factorize(s.drop(2)) # this is okay (array([0, 1]), Int64Index([1, 2], dtype='int64')) One way to workaround this (not sure what your end goal is) is to convert list elements to tuples, which are hashable: &gt;&gt;&gt; s.apply(lambda x: tuple(x) if isinstance(x, list) else x) 0 1 1 2 2 (3, 4, 5) dtype: object &gt;&gt;&gt; pd.factorize(s.apply(lambda x: tuple(x) if isinstance(x, list) else x)) (array([0, 1, 2]), Index([1, 2, (3, 4, 5)], dtype='object'))
type: Answer
score: 3
downvote count: 0

http://stackoverflow.com/comment/91251509
comment on: http://stackoverflow.com/q/52113566
has text: To see the format of the fixture, I would create some bogus data in code, then use `manage.py dumpdata` (https://docs.djangoproject.com/en/2.0/howto/initial-data/#providing-data-with-fixtures) to get a dump that you can then modify.
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/52262430
has answer: http://stackoverflow.com/a/52269518
has comment: http://stackoverflow.com/comment/91486748
tagged with: python
linked to: http://stackoverflow.com/q/52156388
tagged with: selenium-webdriver
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91486547
tagged with: select
tagged with: selenium
has comment: http://stackoverflow.com/comment/91523704
has title: How to select a value from options as per the HTML through Selenium and Python
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/91485343
answer count: 1
has body: I'm trying to change the value of a dropdown and facing problem while selecting the value from tag and tag. This is HTML that i want to change. one two three four five I'm using Webdriver(Chrome).This is my code. driver.find_element_by_name('frmSearch').find_element_by_id('searchByInput91').click() This code makes me to click the dropdown and open the options. After that, when I use this code : from selenium.webdriver.support.ui import Select select = Select(driver.find_element_by_id('searchBy')) select.select_by_value('1').click() OR driver.find_element_by_id("searchBy").send_keys("two") Error messages always come out. ElementNotVisibleException: Message: element not visible: Element is not currently visible and may not be manipulated (Session info: chrome=69.0.3497.81) (Driver info: chromedriver=2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c197e),platform=Windows NT 10.0.17134 x86_64) what should I do?
has comment: http://stackoverflow.com/comment/91472672
favorite count: 0
score: 0
tagged with: display
has comment: http://stackoverflow.com/comment/91472664
accepted answer: http://stackoverflow.com/a/52269518
downvote count: 1

http://stackoverflow.com/q/52166308
has comment: http://stackoverflow.com/comment/91315016
has comment: http://stackoverflow.com/comment/91284686
tagged with: machine-learning
has body: According to this website, deep belief network is just stacking multiple RBMs together, using the output of previous RBM as the input of next RBM. In the scikit-learn documentation, there is one example of using RBM to classify MNIST dataset. They put a RBM and a LogisticRegression in a pipeline to achieve better accuracy. Therefore I wonder if I can add multiple RBM into that pipeline to create a Deep Belief Networks as shown in the following code. from sklearn.neural_network import BernoulliRBM import numpy as np from sklearn import linear_model, datasets, metrics from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline digits = datasets.load_digits() X = np.asarray(digits.data, 'float32') Y = digits.target X = (X - np.min(X, 0)) / (np.max(X, 0) + 0.0001) # 0-1 scaling X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0) logistic = linear_model.LogisticRegression(C=100) rbm1 = BernoulliRBM(n_components=100, learning_rate=0.06, n_iter=100, verbose=1, random_state=101) rbm2 = BernoulliRBM(n_components=80, learning_rate=0.06, n_iter=100, verbose=1, random_state=101) rbm3 = BernoulliRBM(n_components=60, learning_rate=0.06, n_iter=100, verbose=1, random_state=101) DBN3 = Pipeline(steps=[('rbm1', rbm1),('rbm2', rbm2), ('rbm3', rbm3), ('logistic', logistic)]) DBN3.fit(X_train, Y_train) print("Logistic regression using RBM features:\n%s\n" % ( metrics.classification_report( Y_test, DBN3.predict(X_test)))) However, I discover that the more RBM I add to the pipeline, the less the accuracy is. 1 RBM in pipeline --> 95% 2 RBMs in pipeline --> 93% 3 RBMs in pipeline --> 89% The training curve below shows that 100 iterations is just right for convergent. More iterations will cause over-fitting and the likelihood will go down again. Batch size = 10 Batch size = 256 or above I have noticed one interesting thing. If I use a higher batch size, the performance of the network deteriorates a lot. When the batch size…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91285633
has comment: http://stackoverflow.com/comment/91282658
has comment: http://stackoverflow.com/comment/91283619
has comment: http://stackoverflow.com/comment/91288788
has comment: http://stackoverflow.com/comment/91283497
type: Question
score: 9
has title: Stacking RBMs to create Deep belief network in sklearn
has comment: http://stackoverflow.com/comment/91303317
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/91283754
answer count: 1
downvote count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/91283118
accepted answer: http://stackoverflow.com/a/53503003
has comment: http://stackoverflow.com/comment/91283414
has comment: http://stackoverflow.com/comment/91312076
has comment: http://stackoverflow.com/comment/91283758
upvote count: 10
has comment: http://stackoverflow.com/comment/91283410
tagged with: python
has answer: http://stackoverflow.com/a/53503003
has comment: http://stackoverflow.com/comment/91284690
favorite count: 0
has comment: http://stackoverflow.com/comment/91287191

http://stackoverflow.com/q/52130442
accepted answer: http://stackoverflow.com/a/52131953
has comment: http://stackoverflow.com/comment/91214653
has comment: http://stackoverflow.com/comment/91211736
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91211230
has answer: http://stackoverflow.com/a/52131953
has comment: http://stackoverflow.com/comment/91211878
tagged with: python
has body: I have a complex numpy array signal with dimensions [10,1000,50000] I need to modify this array in slices. This is done in a for loop: for k in range(signal.shape[2]): signal[:,:,k] = myfunction(signal[:,:,k], constant1, constant2, constant5=constant5, constant6=constant6) I optimized myfunction as much as possible. When I run the script it takes quite some time but only uses 1 of 24 CPU's. The code can not be rewritten to perform myfunction on the entire array with numpy. Therefore I want to speed up my code with parallel computing. There seem to many different approach for parallel computing in python. Which one seems to be the best for my problem? And how can I implement it?
has title: Modify 3D numpy array in slices in parallel
tagged with: parallel-processing
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/91211927

http://stackoverflow.com/comment/91521093
type: AnswerComment
score: 0
type: Comment
has text: Ok I see your problem. Your indention is bad. Fix your indention all the methods should line up right now you have them set as inside of the `__init__` method instead at the same level. See my updated answer. Sorry I missed the indention mistake in my answer.
comment on: http://stackoverflow.com/a/52280081

http://stackoverflow.com/q/52129738
has comment: http://stackoverflow.com/comment/91210453
type: Question
has body: I have a server that collects 3 CSV files every hour files thus generating 72 files in 24 hours. The files have a date and an hour extension, the hour extensions will be the same every day (for that hour) just the date will change in which they all go into a directory called completed. Occasionally some files dont get collected in the hour thus i want to find out which CSV files are missing for that date . To begin with i want to search for the files in the completed directory that were collected, using glob function import sys import glob csv_files = glob.glob('*.csv') print(csv_files) Question : is it possible to make the wild card an input variable, for example if i could input a date into this wild card i could see what files have been generated for that day only , from here i could compare the 72 files that should be in the directory (based on the hour). Any other ideas would be appreciated.
score: 0
has title: Read the contents of a directory using a variable input as a wild card
has comment: http://stackoverflow.com/comment/91210135
has comment: http://stackoverflow.com/comment/91209798
has comment: http://stackoverflow.com/comment/91209813
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91210003
has comment: http://stackoverflow.com/comment/91209830
tagged with: python
answer count: 0

http://stackoverflow.com/a/52151123
score: 1
has body: I'm not sure about this solution, because I have another output. But maybe it helps. Step 1. Create data and merge. import pandas as pd from scipy.stats.stats import pearsonr df1 = pd.DataFrame(data=[[1,2,0.1,0.2,0.3], [1,3,0.2,0.3,0.5], [2,4,0.5,0.5,0.7], [3,5,0.7,0.2,0.1]], columns=['item1', 'item2', 'val1', 'val2', 'val3']) df2 = pd.DataFrame(data=[[1,0.1,0.5,0.7], [2,0.2,0.8,0.9], [3,0.7,0.6,0.5]], columns=['item1', 'val1', 'val2', 'val3']) df = df1.merge(df2,on='item1') Output: item1 item2 val1_x val2_x val3_x val1_y val2_y val3_y 0 1 2 0.1 0.2 0.3 0.1 0.5 0.7 1 1 3 0.2 0.3 0.5 0.1 0.5 0.7 2 2 4 0.5 0.5 0.7 0.2 0.8 0.9 3 3 5 0.7 0.2 0.1 0.7 0.6 0.5 Step 2. Definition function to calculate the correlation. def corr(df): return pd.DataFrame(data=[pearsonr( df'val1_x', 'val2_x', 'val3_x'.as_matrix()[0], df'val1_y', 'val2_y', 'val3_y'.as_matrix()[0])[0]], columns=['similarity']) Step 3. Use group by items and apply the corr-function. df = df.groupby(['item1', 'item2']).apply(corr).reset_index().drop(['level_2'],1) Output: item1 item2 similarity 0 1 2 0.981981 1 1 3 0.928571 2 2 4 0.609994 3 3 5 0.933257
upvote count: 1
has comment: http://stackoverflow.com/comment/91291840
accepted answer of: http://stackoverflow.com/q/52148638
has comment: http://stackoverflow.com/comment/91302786
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52148638
has comment: http://stackoverflow.com/comment/91291934
type: Answer

http://stackoverflow.com/comment/91322173
score: 0
has text: Are you attempting to find Jack based on the value of 1 or based on the positional "index" of 0?
type: Comment
comment on: http://stackoverflow.com/q/52185838
type: QuestionComment

http://stackoverflow.com/comment/91289133
type: Comment
comment on: http://stackoverflow.com/a/52169168
type: AnswerComment
has text: Not sure I understand. Just add any parameters you need at the end. Please click `edit` under your question and show 3 lines of your `"arguments.txt"` file and then show the 3 corresponding commands that should be executed.
score: 0

http://stackoverflow.com/q/52151673
tagged with: python
has comment: http://stackoverflow.com/comment/91256143
has title: Dependencies missing in current linux-64 channels when trying to install tensorflow-gpu with conda command
upvote count: 5
has answer: http://stackoverflow.com/a/53540256
tagged with: tensorflow
type: Question
score: 5
has body: Hi I tried conda install tensorflow-gpu in my terminal and I get this Error: Dependencies missing in current linux-64 channels: - tensorflow -&gt; numpy &gt;=1.11 -&gt; blas * mkl - tensorflow -&gt; numpy 1.11* -&gt; blas * openblas - tensorflow -&gt; tensorflow-tensorboard -&gt; numpy &gt;=1.11 -&gt; blas * openblas - tensorflow -&gt; numpy 1.12* -&gt; blas * openblas - tensorflow -&gt; tensorflow-base ==1.3.0 -&gt; numpy &gt;=1.11 -&gt; blas * mkl - tensorflow -&gt; tensorflow-base ==1.3.0 -&gt; numpy &gt;=1.11 -&gt; blas * openblas - tensorflow -&gt; tensorflow-tensorboard -&gt; numpy &gt;=1.11 -&gt; blas * mkl - tensorflow -&gt; numpy 1.12* -&gt; blas * mkl - tensorflow -&gt; numpy 1.11* -&gt; blas * mkl - tensorflow -&gt; numpy &gt;=1.11 -&gt; blas * openblas I also installed openblas after but still same error. What is the issue?
has comment: http://stackoverflow.com/comment/91254742
has comment: http://stackoverflow.com/comment/91253771
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/137126884
type: UnansweredQuestion

http://stackoverflow.com/comment/91193636
type: QuestionComment
score: 0
has text: It is rather sad, since this could perhaps get exploited for SQL injection (although I can not immediately come up with a scenario, it *could* perhaps result in a security vulnerability)
comment on: http://stackoverflow.com/q/52121149
type: Comment

dictionary
tags question: http://stackoverflow.com/q/52242489
tags question: http://stackoverflow.com/q/52225770
tags question: http://stackoverflow.com/q/52240080
tags question: http://stackoverflow.com/q/52236643
tags question: http://stackoverflow.com/q/52240699
tags question: http://stackoverflow.com/q/52119760
tags question: http://stackoverflow.com/q/52190140
tags question: http://stackoverflow.com/q/52155123
tags question: http://stackoverflow.com/q/52150122
tags question: http://stackoverflow.com/q/52118574
tags question: http://stackoverflow.com/q/52166920
tags question: http://stackoverflow.com/q/52260556
tags question: http://stackoverflow.com/q/52130720
tags question: http://stackoverflow.com/q/52183013
tags question: http://stackoverflow.com/q/52159748
tags question: http://stackoverflow.com/q/52268742
tags question: http://stackoverflow.com/q/52183696
tags question: http://stackoverflow.com/q/52185838
tags question: http://stackoverflow.com/q/52207200
tags question: http://stackoverflow.com/q/52195005
tags question: http://stackoverflow.com/q/52135345
tags question: http://stackoverflow.com/q/52131295
tags question: http://stackoverflow.com/q/52138324
tags question: http://stackoverflow.com/q/52269707
tags question: http://stackoverflow.com/q/52207140
tags question: http://stackoverflow.com/q/52170668
tags question: http://stackoverflow.com/q/52121560
tags question: http://stackoverflow.com/q/52148009
tags question: http://stackoverflow.com/q/52127854
tags question: http://stackoverflow.com/q/52171726
tags question: http://stackoverflow.com/q/52196721
tags question: http://stackoverflow.com/q/52227540
tags question: http://stackoverflow.com/q/52149781
tags question: http://stackoverflow.com/q/52139110
tags question: http://stackoverflow.com/q/52245821
tags question: http://stackoverflow.com/q/52195887
tags question: http://stackoverflow.com/q/52232973
tags question: http://stackoverflow.com/q/52219249
tags question: http://stackoverflow.com/q/52258451
tags question: http://stackoverflow.com/q/52259298
tags question: http://stackoverflow.com/q/52133506
tags question: http://stackoverflow.com/q/52208802
tags question: http://stackoverflow.com/q/52149434
tags question: http://stackoverflow.com/q/52234487
tags question: http://stackoverflow.com/q/52233215
tags question: http://stackoverflow.com/q/52118472
tags question: http://stackoverflow.com/q/52206075
tags question: http://stackoverflow.com/q/52126707
tags question: http://stackoverflow.com/q/52180451
tags question: http://stackoverflow.com/q/52188627
tag name: dictionary
tags question: http://stackoverflow.com/q/52218107
tags question: http://stackoverflow.com/q/52152512
tags question: http://stackoverflow.com/q/52204952
tags question: http://stackoverflow.com/q/52260091
tags question: http://stackoverflow.com/q/52239401
tags question: http://stackoverflow.com/q/52249889
tags question: http://stackoverflow.com/q/52268262
tags question: http://stackoverflow.com/q/52164721
tags question: http://stackoverflow.com/q/52186108
tags question: http://stackoverflow.com/q/52250121
tags question: http://stackoverflow.com/q/52155046
tags question: http://stackoverflow.com/q/52143288
tags question: http://stackoverflow.com/q/52148153
tags question: http://stackoverflow.com/q/52162026
tags question: http://stackoverflow.com/q/52132207
tags question: http://stackoverflow.com/q/52138930
tags question: http://stackoverflow.com/q/52158793
tags question: http://stackoverflow.com/q/52178185
tags question: http://stackoverflow.com/q/52161886
tags question: http://stackoverflow.com/q/52213265
tags question: http://stackoverflow.com/q/52261121
tags question: http://stackoverflow.com/q/52148667
tags question: http://stackoverflow.com/q/52141517
tags question: http://stackoverflow.com/q/52157858
tags question: http://stackoverflow.com/q/52245335
tags question: http://stackoverflow.com/q/52148959
tags question: http://stackoverflow.com/q/52148690
tags question: http://stackoverflow.com/q/52227707
tags question: http://stackoverflow.com/q/52194837

http://stackoverflow.com/comment/91383036
type: Comment
comment on: http://stackoverflow.com/a/52217159
score: 0
type: AnswerComment
has text: Can you check once ?

http://stackoverflow.com/a/52132257
has body: This has returned a list for your row number. You can process it like this: for dict_current in dataset.orderItems[691581]: i_prod_num = dict_current["product"] i_price = dict_current["price"] fl_quantity = dict_current["quantity"] What you do next depends on what you want to do with these values.
type: Answer
answers question: http://stackoverflow.com/q/52132207
has comment: http://stackoverflow.com/comment/91215126
score: 0

http://stackoverflow.com/a/52189813
accepted answer of: http://stackoverflow.com/q/52186851
answers question: http://stackoverflow.com/q/52186851
has body: You have a couple options that you can use for long-running tasks: Use GAE Task Queues: GAE provides push and pull queues which allow you to do work asynchronously outside of the individual request. Use Cloud Pub/Sub: A type of pull queue, this would allow your App Engine app to publish a message every time you wanted fetch followers or fetch tweets. The subscriber would then take the message from the queue, perform a long-running task, and then put the result into some datastore. Use GAE Services: This would allow you to create a background service and manually scale it to run as long as you need.
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91346149
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91354475

http://stackoverflow.com/comment/91299437
comment on: http://stackoverflow.com/a/52171210
type: Comment
has text: It works fine for me for your new data set as well. See my edited answer for your new dataset
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91329969
has text: Please check https://stackoverflow.com/questions/4666973/how-to-extract-a-substring-from-inside-a-string-in-python
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52190030

http://stackoverflow.com/q/52265615
answer count: 1
has comment: http://stackoverflow.com/comment/91479394
favorite count: 0
has comment: http://stackoverflow.com/comment/91479338
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52265703
tagged with: python
has comment: http://stackoverflow.com/comment/91480242
has comment: http://stackoverflow.com/comment/91480147
type: AnsweredQuestion
tagged with: tkinter
has title: Can each class have an __init__() function?
has comment: http://stackoverflow.com/comment/91479501
upvote count: 2
has comment: http://stackoverflow.com/comment/91479522
downvote count: 2
has comment: http://stackoverflow.com/comment/91479343
has comment: http://stackoverflow.com/comment/91479303
type: Question
has comment: http://stackoverflow.com/comment/91479400
accepted answer: http://stackoverflow.com/a/52265703
has comment: http://stackoverflow.com/comment/91479411
has comment: http://stackoverflow.com/comment/91479784
has body: I am learning Python and I have a situation in which I am tempted to have an __init__() function in several of my different classes. Are there any problems that this could cause? If it makes any difference one of them is in a Tkinter main loop for the user interface. Thanks.
has comment: http://stackoverflow.com/comment/91481390
score: 0

http://stackoverflow.com/comment/91480154
has text: Error expected lstm_2 to have two dimensions but it received array of shape (1, T, N)
comment on: http://stackoverflow.com/q/52265795
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91249386
score: 0
type: Comment
type: QuestionComment
has text: I solved it. I had to use `model.get_support` instead of `SelectFromModel.get_support`.
comment on: http://stackoverflow.com/q/52149376

http://stackoverflow.com/q/52114247
has comment: http://stackoverflow.com/comment/91179191
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/52114348
favorite count: 0
has comment: http://stackoverflow.com/comment/91178897
tagged with: python
type: AnsweredQuestion
upvote count: 2
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91179110
type: Question
has comment: http://stackoverflow.com/comment/91178922
has answer: http://stackoverflow.com/a/52114348
has body: I want to zip the dataframe of pandas and make it a list. list(zip(dataframe['a'], dataframe['b'], dataframe['c'], dataframe['d'], dataframe['e'], dataframe['f']) This is the final result I want to make. [('q', 'w', 'e', 'r', 't', 'y'), (...)] The above code works, but it looks very messy and dirty. So, I am looking for a way to simplify the code by using the Comprehension method or other methods. Thank you for your help.
tagged with: dataframe
has title: How to Zip Dataframe

http://stackoverflow.com/q/52205964
upvote count: 2
has body: I am trying to write values to a dictionary every 5 seconds for 1 minute. I then want to take those values and put into a dataframe to write to csv and clear the original dictionary and keep going. import time import random from multiprocessing import Process a = {'value':[], 'timeStamp': []} def func1(): global a print "starting First Function" a['value'].append(random.randint(1,101)) a['timeStamp'].append(time.time()*1000.0) time.sleep(5) return a def func2(): print "starting Second Function" time.sleep(60) d = pd.DataFrame(a) print d # here i would write out the df to csv and del d a.update({}.fromkeys(a,0)) print "cleared" if __name__=='__main__': while True: p1 = Process(target = func1) p1.start() p2 = Process(target = func2) p2.start() p1.join() p2.join() print "test" print a This is where i'm at now, which may or may not be the correct way to do this. Regardless, this code is not giving me the correct results. I am trying to figure out the best way to get the dict into the df and clear it. Hopefully, someone has done something similar?
has answer: http://stackoverflow.com/a/52206628
type: Question
has comment: http://stackoverflow.com/comment/91362095
answer count: 2
has title: load dict every x seconds then pass to df and clear dict
accepted answer: http://stackoverflow.com/a/52206628
downvote count: 0
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/52206620
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52206620

http://stackoverflow.com/a/52267123
has comment: http://stackoverflow.com/comment/91482345
answers question: http://stackoverflow.com/q/52267034
has body: Constructing a DataFrame df as follows: df = pd.DataFrame() df = df.append(['1.star t-shirt-large-red']) df = df.append(['2.star t-shirt-large-blue']) df = df.append(['4.beautiful rainbow skirt small']) df = df.append(['5.long maxwell logan jeans- light blue -32L-28W']) df = df.append(['6.long maxwell logan jeans- Dark blue -32L-28W']) df.columns = ['Product'] The following code (a) strips any whitespace, (b) splits by the period ('.') and grabs what follows, (c) replaces 't-shirt' with 'tshirt' because of further operations (change this back if you want after the operation) (d) splits again by '-' and expands to give your dataframe. df['Product'].str.strip().str.split('.').str.get(1).str.replace('t-shirt', 'tshirt').str.split('-', expand = True) Output: 0 1 2 3 0 star tshirt large red None 0 star tshirt large blue None 0 beautiful rainbow skirt small None None None 0 long maxwell logan jeans light blue 32L 28W 0 long maxwell logan jeans Dark blue 32L 28W Given the inconsistency in nomenclature for your product, there will be edge-cases that are missed (ex : beautiful rainbow skirt small). You may have to fish them out again.
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91486129
downvote count: 0
has comment: http://stackoverflow.com/comment/91482314

http://stackoverflow.com/a/52266497
answers question: http://stackoverflow.com/q/52266462
has body: Not a fan of inplace, but try pd.sort_index(): df.reset_index(level=['Date'], inplace= True) df.set_index(['symbol', 'Date'], inplace=True) print(df.sort_index()) Output: high low symbol Date nflx 2018-08-16 331.170013 321.209991 2018-08-17 324.369995 312.959991 spy 2017-07-17 245.910004 245.330002 2017-07-18 245.720001 244.669998 2018-08-16 285.040009 283.359985 2018-08-17 285.559998 283.369995
score: 1
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/52198846
has answer: http://stackoverflow.com/a/52199329
accepted answer: http://stackoverflow.com/a/52199330
score: 4
type: Question
upvote count: 4
tagged with: numpy
has body: I am new to numpy and am stuck at this problem. I have two 2-dimensional numpy array such as x = numpy.random.random((10, 5)) y = numpy.random.random((10, 5)) I want to use numpy cov function to find covariance of these two ndarrays row wise. i.e., for above example the output array should consist of 10 elements each denoting the covariance of corresponding rows of the ndarrays. I know I can do this by traversing the rows and finding the covariance of two 1D arrays but it isn't pythonic. Edit1: The covariance of two array denotes the element at 0, 1 index. Edit2: Currently this is my implementation s = numpy.empty((x.shape[0], 1)) for i in range(x.shape[0]): s[i] = numpy.cov(x[i], y[i])[0][1]
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52199330
tagged with: python
linked to: http://stackoverflow.com/q/41700840
answer count: 4
has answer: http://stackoverflow.com/a/52199466
has answer: http://stackoverflow.com/a/52199326
has title: Numpy find covariance of two 2-dimensional ndarray
possible better answer: http://stackoverflow.com/a/52199329
type: AnsweredQuestion

http://stackoverflow.com/a/52238018
type: Answer
has body: This was indeed an import error where the event handlers were not being imported in the __init__.py file that contained my app factory, thus they were not registered to my app. To fix this I added a socket_instance.py file to my root directory that contains from flask_socketio import SocketIO and imported that in my __init__.py file as well as in all my event handler creation files. Then from any files I can now import my socketio object as such: from socket_instance import socketio
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52194063
answers question: http://stackoverflow.com/q/52194063

http://stackoverflow.com/comment/91442731
score: 0
has text: This is a good first post. My small recommendation, for even better questions, is to use technical writing - we like succinctness here. There's no need for niceties or chit-chat - just describe your general problem, what you have done to try to solve it, and any notes on where you think the problem is. This looks pretty good now.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52246136

http://stackoverflow.com/q/52173495
tagged with: python
score: 2
downvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/23747564
type: Question
tagged with: ordereddictionary
duplicate of: http://stackoverflow.com/q/35446015
has comment: http://stackoverflow.com/comment/91297916
upvote count: 2
has comment: http://stackoverflow.com/comment/91297870
has comment: http://stackoverflow.com/comment/91297887
answer count: 1
duplicate of: http://stackoverflow.com/q/23747564
has title: How to get values of a Counter object in the order which it was received?
favorite count: 0
has body: Task: The first line contains the integer, N. The next N lines each contain a word. Output should be: 1) On the first line, output the number of distinct words from the input. 2) On the second line, output the number of occurrences for each distinct word according to their appearance in the input. I had no difficulty with #1. For point #2, I used Counter to get the occurrences of the words. However I am having difficulty in printing them in the order which it was received. Below is my code. from collections import Counter from collections import OrderedDict all_words=[] for _ in range(int(raw_input())): name=raw_input() all_words.append(name) uniqlst=list(set(all_words)) print len(uniqlst)##On the first line, output the number of distinct words from the input. x=OrderedDict(Counter(all_words)) #This is where I am having trouble to get values of x in the order it was received. print " ".join(map(str,x.values())) Input: 4 bcdef abcdef bcde bcdef Output of my code: 3 1 1 2 Expected output: 3 2 1 1
has answer: http://stackoverflow.com/a/52173593
linked to: http://stackoverflow.com/q/35446015

http://stackoverflow.com/q/52138894
has comment: http://stackoverflow.com/comment/91423679
tagged with: python
linked to: http://stackoverflow.com/q/51314105
type: Question
has body: Running my frozen script stops immediately with this message: 1 Fatal Python error: initfsencoding: unable to load the file system codec. ImportError: invalid flags 1530064918 in 'encodings' Current thread 0x00000f94 (most recent call first): I use Python 3.7.0 and cx_Freeze 5.1.1 (64bit). My script: import os from cx_Freeze import setup, Executable PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__)) os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6') os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6') build_exe_options={ 'packages':['copy', 'tkinter', 'os', 'pandas', 'numpy', 'scipy', 'csv', 'datetime', 'matplotlib'] executables=[Executable("Data_GUI_11.py")] setup(name='Data_GUI_11', version=0.1, description='Data reader and plotter', options={"build_exe": build_exe_options}, executables=executables ) There might be more errors – it is my first attempt with cx_Freeze. No clue… Thank you.
has comment: http://stackoverflow.com/comment/91246594
linked to: http://stackoverflow.com/q/52237533
score: 0
has comment: http://stackoverflow.com/comment/91236924
answer count: 1
tagged with: cx-freeze
has title: cx_Freeze makes file with initfsencoding problem
has answer: http://stackoverflow.com/a/53412760
type: UnansweredQuestion

http://stackoverflow.com/q/52179071
upvote count: 1
type: Question
has title: Python - Create objects with indexed names
has body: I want to make a list of dictionaries that I can append an updated dictionary with a new name (indexed) each time I iterate through a certain code, in which dict is updated. dict = {'Key1': 'Value1' 'Key2': 'Valeu2' } list1 = [dict1, dict2, dictx, ....] So basicly I define dict and then i run the loop the first time, now what i want to happen is that dict will be updated according to the code and then be appeneded to list1 by the name dict1, and by the 2nd iteration it will be dict2 and so on. Ofcourse each of the dictionaries will have it's own items.
has answer: http://stackoverflow.com/a/52179561
has comment: http://stackoverflow.com/comment/91308632
has comment: http://stackoverflow.com/comment/91308264
has comment: http://stackoverflow.com/comment/91309836
downvote count: 4
has comment: http://stackoverflow.com/comment/91308306
has comment: http://stackoverflow.com/comment/91308586
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52179561
has comment: http://stackoverflow.com/comment/91309553
score: -3
has comment: http://stackoverflow.com/comment/91308944
has comment: http://stackoverflow.com/comment/91308499
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91309015
has comment: http://stackoverflow.com/comment/91308465

http://stackoverflow.com/a/52241914
has body: I'll fabricate some data for illustration. Consider import numpy as np import pandas as pd imputed_X_train_plus = pd.DataFrame({'joe': [3, np.nan], 'nick': [np.nan, 6], 'fred': [1, 7]}) At this moment, imputed_X_train_plus is a data frame with NaN values. joe nick fred 0 3.0 NaN 1 1 NaN 6.0 7 Suppose you somehow have known which columns have missing values. They are in cols_with_missing. cols_with_missing = ['joe', 'nick'] Now you want to mark out those missing values. So you do for col in cols_with_missing: imputed_X_train_plus[col +'_was_missing'] = imputed_X_train_plus[col].isnull() Now you are having imputed_X_train_plus like joe nick fred joe_was_missing nick_was_missing 0 3.0 NaN 1 False True 1 NaN 6.0 7 True False To conclude, col + '_was_missing' made a new str (like joe_was_missing) which is used to insert a new column name for imputed_X_train_plus.
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52241827
score: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52241827

http://stackoverflow.com/comment/91354420
score: 0
type: Comment
has text: @Ashwinkumar: Put differently, **never** use Python container representations as a format to communicate with another tool. Use an explicit serialisation format. JSON is one such format, but there are others. For Python to Python communication where you don't have to worry about untrusted third-party interference, consider using `pickle`, for example.
comment on: http://stackoverflow.com/a/52201537
type: AnswerComment

http://stackoverflow.com/q/52206338
tagged with: typeerror
tagged with: pandas
tagged with: python
downvote count: 0
linked to: http://stackoverflow.com/q/14535730
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52226896
has title: TypeError: unhashable type: 'list' from pandas' pd.factorize()
score: 1
type: Question
has body: So I'm following a tutorial on Multi-Class Text Classification and I'm trying to find a way to predict tags of on recipes in a supervised method with a JSON file that has the recipes in this format: { "title": "Turtle Cheesecake", "summary": "Cheesecake is a staple at the Market, but it’s different nearly every day because we vary the toppings, crusts, and flavorings. Cookie crusts are particularly good with cheesecakes. If you prefer your cheesecake plain, just serve it without the topping", "ingr": [ "1½ cups graham cracker crumbs", "½ cup finely chopped pecans (pulse in a food processor several times)", "6 tablespoons ( ¾ stick) unsalted butter, melted", "1½ pounds cream cheese, softened", "¾ cup sugar", "2 tablespoons all purpose flour", "3 large eggs", "1large egg yolk", "½ cup heavy cream", "2 teaspoons pure vanilla extract", "1 cup sugar", "1 cup heavy cream", "½ teaspoon pure vanilla extract", "½ cup coarsely chopped pecans, toasted", "2 ounces semisweet chocolate, melted" ], "prep": "To Make the Crust:\n\n\n\n Grease a 9-inch springform pan. Wrap the outside of the pan, including the bottom, with a large square of aluminum foil. Set aside.\n\n\n\..." "tag": [ "Moderate", "Casual Dinner Party", "Family Get-together", "Formal Dinner Party", "dessert", "dinner", "cake", "cheesecake", "dessert" } This is the code I'm running that's cause the TypeError: import pandas as pd df = pd.read_json('tagged-sample.json') ######################### Data Exploration ####################### from io import StringIO col = ['tag', 'summary'] df = df[col] df = df[pd.notnull(df['summary'])] df.columns = ['tag', 'summary'] df['category_id'] = df['tag'].factorize()[0] What can I do to be able to use the pandas.factorize on the 'tag' category in the json. The tutorial does this on a csv file which might make a difference. This is the error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-9-d471…
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/q/52265577
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/91479452
has comment: http://stackoverflow.com/comment/91479362
has comment: http://stackoverflow.com/comment/91479412
type: Question
has comment: http://stackoverflow.com/comment/91479289
has answer: http://stackoverflow.com/a/52265739
accepted answer: http://stackoverflow.com/a/52265739
score: 0
answer count: 1
tagged with: beautifulsoup
has body: I'm pretty new to coding and recently I've started looking into web scraping. I've been following this tutorial and also reading the BS4 documentation but I just can't see why my code isn't working. I'm trying to extract this post's headline with the webscraper but it looks like it can't find any tags that match "('div', class_='header')" My code: import requests from bs4 import BeautifulSoup SOURCE = requests.get('http://coreyms.com/').text SOUP = BeautifulSoup('SOURCE', 'lxml') HEADER = SOUP.find('div', class_='header') HEADLINE = HEADER.h2.a.href print(HEADLINE) Error message: Traceback (most recent call last): File "WSCoreySchafer.py", line 10, in &lt;module&gt; HEADLINE = ARTICLE.h2.a.href AttributeError: 'NoneType' object has no attribute 'h2'
tagged with: python
has comment: http://stackoverflow.com/comment/91479500
type: AnsweredQuestion
has title: Basic Python web scraping with BeautifulSoup

http://stackoverflow.com/a/52191751
upvote count: 2
answers question: http://stackoverflow.com/q/52169554
has body: The primary option would be to vendor your dependencies. With this option, you build locally and then push all the compiled bits too. The trick is that you have to build on a compatible system, so you need an Ubuntu Trusty PC/VM/Docker container. Follow these instructions, then run cf push &amp; make sure that you do not have the vendor directory ignored (remove from .cfignore, if it exists). https://docs.cloudfoundry.org/buildpacks/python/index.html#vendoring The other option that should work is to use multi-buildpack support. With this you can push using two buildpacks. The first would be the Apt buildpack and the second would be the python buildpack. The Apt buildpack allows you to install the packages that you need, which looks like libxmlsec1-dev. The second is just the standard Python buildpack, but it will have access to what has been installed via the Apt buildpack. You can see instructions here: https://docs.cloudfoundry.org/buildpacks/use-multiple-buildpacks.html
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52169554

http://stackoverflow.com/q/52165774
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52167063
accepted answer: http://stackoverflow.com/a/52167063
tagged with: flask
tagged with: flask-sqlalchemy
possible better answer: http://stackoverflow.com/a/60258720
has body: I cant install flask-mysqldb _mysql.c:37:20: fatal error: Python.h: No such file or directory compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 i can't resolve
downvote count: 3
has title: unable to install flask-mysqldb
has answer: http://stackoverflow.com/a/60258720
favorite count: 0
upvote count: 0
has comment: http://stackoverflow.com/comment/91282859
score: -3
tagged with: web-applications
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91281299

http://stackoverflow.com/a/68717622
answers question: http://stackoverflow.com/q/52123470
downvote count: 0
has body: I use pylint Ctrl+P: Python Select Linter > select pylint 一. vscode says those warning type Unused PrimaryKeyConstraint imported from sqlalchemypylint(unused-import) Imports from package sqlalchemy are not groupedpylint(ungrouped-imports) Import "import logging" should be placed at the top of the modulepylint(wrong-import-position) standard import "import logging" should be placed before "from sqlalchemy import Column, Integer, String"pylint(wrong-import-order) Line too long (141/100)pylint(line-too-long) ... 二. ignore those warning type in setting Ctrl+P: WorkSpace Setting JSON { "python.linting.pylintArgs": [ "--disable=wrong-import-order,wrong-import-position,unused-import,ungrouped-imports,line-too-long" ], } OR use setting ui Ctrl+P: WorkSpace Setting search python.linting.pylintArgs Add Item OR edit item existed.
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/91464006
type: Comment
has text: file not found `/tmp/build_4d889a5985b9c262c637b03bd07e9098/hello/static` to fix this run `python manage.py collectstatic` locally and in the settings file set `DEBUG=False` and then check where that error is occuring
score: 0
comment on: http://stackoverflow.com/q/52248562
type: QuestionComment

http://stackoverflow.com/a/52225966
accepted answer of: http://stackoverflow.com/q/52225661
type: Answer
answers question: http://stackoverflow.com/q/52225661
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Before one clicks on the 'Advanced Search' link, the entire Advanced Search Form is not at all present in the DOM. After clicking on the link, the entire form is loaded in the DOM at runtime. So I can't think of anything other than this being a synchronization issue. Try adding a step before "driver.find_element_by_id("uxStartDateDecisionTextBox").click()" that pauses the execution for a second or so. If after that, Selenium is able to locate the element, you can be pretty sure that this is a synchronization problem. Then you can opt for some kind of explicit waits to improve your execution speed.

http://stackoverflow.com/q/52250516
has body: I am making a flask form that contains multiple checkbox. I have this code in the form.py file. var_name = BooleanField('', default=False) And I have this in the html. &lt;p&gt;{{ var_name }}&lt;/p&gt; The checkbox that I get on the browser is too small. I guess it is the default size. How do I increase the size of the checkbox? Thank you
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: css
accepted answer: http://stackoverflow.com/a/52250606
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: jinja2
type: Question
downvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/52250606
possible better answer: http://stackoverflow.com/a/77727540
has comment: http://stackoverflow.com/comment/91449019
has answer: http://stackoverflow.com/a/77727540
has title: How to increase the size of the booleanfield in flask form?
favorite count: 0
tagged with: flask-wtforms

http://stackoverflow.com/comment/91374590
type: QuestionComment
has text: Possible answer, https://stackoverflow.com/a/40157390/5781248
score: 0
comment on: http://stackoverflow.com/q/52210267
type: Comment

http://stackoverflow.com/q/52201167
has comment: http://stackoverflow.com/comment/91351299
has comment: http://stackoverflow.com/comment/91351272
has comment: http://stackoverflow.com/comment/91351661
upvote count: 1
has comment: http://stackoverflow.com/comment/91351446
favorite count: 0
has answer: http://stackoverflow.com/a/52201240
accepted answer: http://stackoverflow.com/a/52201240
has comment: http://stackoverflow.com/comment/91351331
has answer: http://stackoverflow.com/a/52201586
tagged with: python
has answer: http://stackoverflow.com/a/52201255
has comment: http://stackoverflow.com/comment/91351379
answer count: 4
has comment: http://stackoverflow.com/comment/91351307
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52201303
downvote count: 0
has answer: http://stackoverflow.com/a/52201303
score: 1
has body: I have the following list: items = [{'item': 1}, {'item': 2}, {'item': 3}] How can I convert it to this? items = [1, 2, 3] This is my current solution but I wonder if there is a better one items = [item['item'] for item in items]
type: Question
has title: Remove dictionaries from list
has comment: http://stackoverflow.com/comment/91351435
has comment: http://stackoverflow.com/comment/91351704

http://stackoverflow.com/comment/91389561
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52220514
has text: Please show the full traceback. The error indicates that you have unicode strings in your code.
score: 0

http://stackoverflow.com/comment/91349548
has text: I've already have email_verified but it's on a different table(email addresses table) not in User table
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52196414
type: Comment

http://stackoverflow.com/q/52189567
upvote count: 1
has body: I'm trying to install Tensorflow on Win 10 machine with Celeron G1840 2.8 GHZ cpu. Python version is 3.6.2 and I successfully installed tensorflow but when I try to import tensorflow error occurs. I've tried with different Python versions. If I am not wrong this CPU doesn't have AVX. Can I still use Tensorflow? import tensorflow as tf Traceback (most recent call last): File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper return importlib.import_module(mname) File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 978, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 961, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 950, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 648, in _load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 560, in module_from_spec File "&lt;frozen importlib._bootstrap_external&gt;", line 922, in create_module File "&lt;frozen importlib._bootstrap&gt;", line 205, in _call_with_frames_removed ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 21, in &lt;module&gt; _pywrap_tensorflow_internal = swig_import_helper() File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper return importlib.import_module('_pywrap_tensorflow_internal') File "C:\Program Files\Python36\lib\impo…
score: 1
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/91408799
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/91407286
has title: Tensorflow and Celeron G1840 WIn 10 install
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/91419747
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52136410
has answer: http://stackoverflow.com/a/52136468
tagged with: python
score: -1
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/20449427
has answer: http://stackoverflow.com/a/52136458
downvote count: 1
type: Question
has body: I know the names are kind of long but I wanted to make sure there was no way it was pulling from used variables firstvalue = input("first") secondvalue = input("second") if firstvalue &lt; secondvalue: print ("first value is &lt; second value") print ( firstvalue, "less than", secondvalue) else: if firstvalue == secondvalue: print ("first is = second") else: print ("first is greater than 2nd") print (firstvalue , "greater than", secondvalue) when i input 12 for the first value and 3 as the second value, i get 12 &lt; 3
answer count: 3
has title: I'm not sure why I keep getting 12 < 3
has answer: http://stackoverflow.com/a/52136437
upvote count: 0
linked to: http://stackoverflow.com/q/20449427
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91222780

http://stackoverflow.com/q/52240631
tagged with: openai-gym
accepted answer: http://stackoverflow.com/a/52262568
has title: How to implement Q-learning to approximate an optimal control?
has comment: http://stackoverflow.com/comment/91433972
type: Question
tagged with: q-learning
has body: I am interested in implementing Q-learning (or some form of reinforcement learning) to find an optimal protocol. Currently, I have a function written in Python where I can take in the protocol or "action" and "state" and returns a new state and a "reward". However, I am having trouble finding a Python implementation of Q-learning that I can use in this situation (i.e. something that can learn the function as if it is a black box). I have looked at OpenAI gym but that would require writing a new environment. Would anyone know of a simpler package or script that I can adopt for this? My code is of the form: def myModel (state, action, param1, param2): ... return (state, reward) What I am looking for would be an algorithm of the form: def QLearning (state, reward): ... return (action) And some way to keeping the actions that transition between states. If anyone has any idea where to look for this, I would be very excited!
answer count: 2
downvote count: 0
tagged with: reinforcement-learning
possible better answer: http://stackoverflow.com/a/52284842
has comment: http://stackoverflow.com/comment/91445378
tagged with: python
has comment: http://stackoverflow.com/comment/91446258
has answer: http://stackoverflow.com/a/52262568
has answer: http://stackoverflow.com/a/52284842
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/91445341
has comment: http://stackoverflow.com/comment/91445175
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/91445429

http://stackoverflow.com/q/52258202
answer count: 0
has comment: http://stackoverflow.com/comment/91471939
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91473020
has comment: http://stackoverflow.com/comment/91463611
tagged with: http://stackoverflow.com/tag/r
score: 0
has title: What is matrix cross product as implemented by the R function `tcrossprod`?
has body: I am new to cross product but from some resources I've understood what is cross product for vector and I understand how it's implemented by the numpy's function np.cross(). It's only defined for two or three dimensions and which is correct according to my understanding But recently I also came across R's tcrossprod which implements cross product for arbitrarily large dimensions of matrices. Can you help me understand why is it different from np.cross(A.T, A) , what does it implement and what's the equivalent numpy function to do it.
has comment: http://stackoverflow.com/comment/91467950
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/52148087
answers question: http://stackoverflow.com/q/52147901
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/91246809
has body: Strings in Python are immutable which means that once a string variable is assigned to a string (For eg a ='Hello') the contents of the string cannot be changed unlike the list object. In the code above you are in a way transforming your string and not changing the contents of your string variable. a=input() for i in a: if i.isupper(): print (i.lower(),end='') else: print (i.upper(),end='') print(a) If you would run this code you will see that the value of a is the same which you entered. The strings methods lower() and upper() just returns a copy of the string.
accepted answer of: http://stackoverflow.com/q/52147901

http://stackoverflow.com/q/52239590
type: Question
has body: {% for post in posts %} {{post.name}} {{post.content}} {% endfor %} I created html file and i'm trying to use python code in html but {{}} {%%} tags not working. It show me my code like a html p tag Only i see this on browser not working codes. where is the problem library?
score: -1
has title: I want import python code in htm file with django
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91427839
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: python
tagged with: django-templates
downvote count: 1
has answer: http://stackoverflow.com/a/52239793

http://stackoverflow.com/comment/91225620
has text: @DarkSuniuM Yes, but all that did was creating a new directory containing the static files? Do I also need to change the path to static files then?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52137729
score: 0

http://stackoverflow.com/comment/91303608
comment on: http://stackoverflow.com/q/52176575
score: 0
type: Comment
type: QuestionComment
has text: Mine was to Siberia. And it *was* the toaster. There goes my last available Doom port.

http://stackoverflow.com/comment/91358094
type: Comment
has text: The lists are sorted
comment on: http://stackoverflow.com/q/52203775
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91399201
type: Comment
has text: Much better, but see my note about `any` on José Pedro Duarte's answer. (`all` and `any` have similar behaviour). However, I think the OP wants `any` rather than `all`.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52221883

http://stackoverflow.com/comment/91306979
type: AnswerComment
comment on: http://stackoverflow.com/a/52178330
score: 0
type: Comment
has text: This is not working, and I am not sure why is would work?

http://stackoverflow.com/a/52185366
has body: Ok i used a different approach. The solution is: df = pd.DataFrame() n = 1 for i in range(len(list_df)): l = [] for j in range(n, len(list_df)): corrcoef = np.corrcoef(list_df[i], list_df[j])[1][0] if corrcoef &gt; 0.7: #adjustable threshold l.append(j) df_ = pd.DataFrame(data=l, columns=[str(i)]) df = pd.concat([df,df_], axis=1) n+=1 This way i get a DataFrame each column containing the index of the correlating subsets.
answers question: http://stackoverflow.com/q/52183321
score: 0
type: Answer

http://stackoverflow.com/comment/91360757
type: Comment
has text: then it's easy implementing the second formula, it's just while loop.
type: QuestionComment
comment on: http://stackoverflow.com/q/52204231
score: 0

http://stackoverflow.com/comment/91374428
comment on: http://stackoverflow.com/a/52212398
has text: By and large, preallocating a `list` with `None`s like that is considered unPythonic; repeated `append`s remove the risk of the presizing getting out of sync with the loop that replaces the placeholder values. The original code was trivially fixable just by moving the creation of the empty `list` outside the loop body, there is no real benefit to presizing the `list`.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52231108
type: Question
tagged with: deep-learning
has title: Get classification score of hypothetical detection box
answer count: 1
score: 0
tagged with: python
type: UnansweredQuestion
tagged with: tensorflow
has body: Is there anyway to assert the presence of a detection box in an image and obtain the classification score of said hypothetical box? I am working with a tensorflow object detection graph and want to refine it's accuracy with a little trickery; by making the claim that there are more (N) objects in a given image than it is detecting, asserting there are image objects in multiple areas in the image, and evaluating each hypothetical image object based on it's classification score between 0 and 1. In other words: I want to say "Hey, TensorFlow, I think there is an image object with rectangular coordinates (x1, y1), (x2, y2) in this image. What would the classification score of a hypothetical detection box defined by that rectangle be?" Is this possible?
has answer: http://stackoverflow.com/a/52245736

http://stackoverflow.com/q/52246983
has title: Sum pattern across array
has body: I'm having trouble finding the proper way to do something I think should be trivial using numpy. I have an array (1000x1000) and I want to calculate the sum of a specific pattern across the array. For example: If I have this array and want to calculate the sum of a two-cell-right diagonal I would expect [7,12,11,8,12,6,11,7] (a total of 8 sums). How can I do this?
type: Question
upvote count: 14
tagged with: numpy
has answer: http://stackoverflow.com/a/52247094
answer count: 2
accepted answer: http://stackoverflow.com/a/52247094
downvote count: 6
possible better answer: http://stackoverflow.com/a/52247227
favorite count: 0
has answer: http://stackoverflow.com/a/52247227
tagged with: python-3.x
tagged with: python
score: 8
type: AnsweredQuestion

http://stackoverflow.com/a/52241455
type: Answer
has comment: http://stackoverflow.com/comment/91431644
answers question: http://stackoverflow.com/q/52241422
has comment: http://stackoverflow.com/comment/91431665
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52241422
has body: You're doing the same thing as: def f(): print('hello') print(f()) So basically narrows down to: print(print('hello world')) Also btw: &gt;&gt;&gt; type(print('hello')) hello &lt;class 'NoneType'&gt; &gt;&gt;&gt; To solve your code do: def file_in_english(filename, character_limit): s="" """English File""" newone = open(filename) nowline = newone.readline() characters = 0 while characters &lt; character_limit and nowline != "": process = nowline[0:-1] s+=english_sentence(process)+'\n' characters += len(nowline) nowline = newone.readline() if characters &gt; character_limit: s+="&lt;&lt;Output limit exceeded&gt;&gt;" return s ans = file_in_english('test1.txt', 20) print(ans)

http://stackoverflow.com/q/52132331
score: 2
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/52132400
type: Question
has body: Let’s say I have two NumPy arrays, a and b: a = np.array([ [1, 2, 3], [2, 3, 4] ]) b = np.array([8,9]) And I would like to append the same array b to every row (ie. adding multiple columns) to get an array, c: b = np.array([ [1, 2, 3, 8, 9], [2, 3, 4, 8, 9] ]) How can I do this easily and efficiently in NumPy? I am especially concerned about its behaviour with big datasets (where a is much bigger than b), is there any way around creating many copies (ie. a.shape[0]) of b? Related to this question, but with multiple values.
tagged with: numpy
tagged with: arrays
has title: How to add multiple extra columns to a NumPy array
downvote count: 0
possible better answer: http://stackoverflow.com/a/52132371
tagged with: data-science
has answer: http://stackoverflow.com/a/52132371
favorite count: 0
has answer: http://stackoverflow.com/a/52132481
answer count: 3
linked to: http://stackoverflow.com/q/8486294
tagged with: python
accepted answer: http://stackoverflow.com/a/52132481

http://stackoverflow.com/q/52133453
upvote count: 1
accepted answer: http://stackoverflow.com/a/52133459
type: Question
downvote count: 0
tagged with: pandas
has body: How to calculate amounts that row values greater than a specific value in pandas? For example, I have a Pandas DataFrame dff. I want to count row values greater than 0. dff = pd.DataFrame(np.random.randn(9,3),columns=['a','b','c']) dff a b c 0 -0.047753 -1.172751 0.428752 1 -0.763297 -0.539290 1.004502 2 -0.845018 1.780180 1.354705 3 -0.044451 0.271344 0.166762 4 -0.230092 -0.684156 -0.448916 5 -0.137938 1.403581 0.570804 6 -0.259851 0.589898 0.099670 7 0.642413 -0.762344 -0.167562 8 1.940560 -1.276856 0.361775 I am using an inefficient way. How to be more efficient? dff['count'] = 0 for m in range(len(dff)): og = 0 for i in dff.columns: if dff[i][m] &gt; 0: og += 1 dff['count'][m] = og dff a b c count 0 -0.047753 -1.172751 0.428752 1 1 -0.763297 -0.539290 1.004502 1 2 -0.845018 1.780180 1.354705 2 3 -0.044451 0.271344 0.166762 2 4 -0.230092 -0.684156 -0.448916 0 5 -0.137938 1.403581 0.570804 2 6 -0.259851 0.589898 0.099670 2 7 0.642413 -0.762344 -0.167562 1 8 1.940560 -1.276856 0.361775 2
answer count: 1
has title: How to calculate amounts that row values greater than a specific value in pandas?
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52133459
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/52135223
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91221466
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52134654
answers question: http://stackoverflow.com/q/52134654
has comment: http://stackoverflow.com/comment/91222271
has body: It seems you only need UserService class for namespace so you don't need to create the instance. You can change your methods to staticmethods or create a module that contains these functions: # userservice.py class UserService(): @staticmethod def getUserByName(name): return User.query.filter(User.name == name).first() # userservice.py def getUserByName(name): return User.query.filter(User.name == name).first() ... I would prefer the second approach, its more clean and pythonic way of doing this: # views.py import userservice user = userservice.getUserByName(name) # first approach from userservice import UserService user = UserService.getUserByName(name)
type: Answer

http://stackoverflow.com/a/52204761
downvote count: 0
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91394715
accepted answer of: http://stackoverflow.com/q/52204336
has body: Use re.search Demo: import re ex1 = "miramar road margie shoop san diego ca 12793 manager phone 6035550160 fax 6035550161 mobile 6035550178 marsgies travel wwwmarpiestravelcom" ex2 = "david packard electrical engineering 350 serra mall room 170 phone 650 7259327 stanford university fax 650 723 1882 stanford california 943059505 ulateecestanfordedu" ex3 = "stanford electrical engineering vijay chandrasekhar electrical engineering 17 comstock circle apt 101 stanford ca 94305 phone 9162210411" for i in [ex1, ex2, ex3]: phone = re.search(r"(?P&lt;phone&gt;(?&lt;=\phone\b).*?(?=([a-z]|$)))", i) if phone: print "Phone: ", phone.group("phone") fax = re.search(r"(?P&lt;fax&gt;(?&lt;=\bfax\b).*?(?=([a-z]|$)))", i) if fax: print "Fax: ", fax.group("fax") mob = re.search(r"(?P&lt;mob&gt;(?&lt;=\bmobile\b).*?(?=([a-z]|$)))", i) if mob: print "mob: ", mob.group("mob") print("-----") Output: Phone: 6035550160 Fax: 6035550161 mob: 6035550178 ----- Phone: 650 7259327 Fax: 650 723 1882 ----- Phone: 9162210411 -----
type: Answer
answers question: http://stackoverflow.com/q/52204336
score: 2

http://stackoverflow.com/q/52117704
tagged with: dataframe
score: 4
upvote count: 4
tagged with: pandas
has answer: http://stackoverflow.com/a/52119697
has body: I have two dataframes - one which is edited by users from a powerapp. The other which comes directly from onedrive. The columns headers are almost the same and I need to compare the two dataframes and add any new rows into the dataframe which comes from powerapps. Here are two example dataframes: Powerapps dataframe: Send/Collect Hospital Courier Kit Manufacturer Status 0 Send Nuffield Ipswich Courier ActivMotion (HTO - DFO) NewClip Hire Log 2018.xlsx Not Started 1 Send BMI Rosshal Courier ActivMotion (HTO - DFO) NewClip Hire Log 2018.xlsx In Progress 2 Collect Stepping Hill Courier ActivMotion (HTO - DFO) NewClip Hire Log 2018.xlsx Not Started 3 Collect York District Courier ActivMotion (HTO - DFO) NewClip Hire Log 2018.xlsx Not Started 4 Royal Devon Exeter NaN NaN ActivMotion (HTO - DFO) NewClip Hire Log 2018.xlsx Not Started 5 collect Spire Bristol Courier ActivMotion (HTO - DFO) NewClip Hire Log 2018.xlsx Complete 6 Send Bridlington Courier ToeMotion - MTP DF Arthrosurface Hire Log 2018.xlsx Not Started 7 Send Femoral Head Hampshire Clinic DHL Human Tissue Human Tissue Log.xlsx Not Started Onedrive dataframe: Send/Collect Hospital Courier Kit Manufacturer 0 Send Nuffield Ipswich Courier ActivMotion (HTO - DFO) NewClip Hire Log 2018.xlsx 1 Send BMI Rosshal Courier ActivMotion (HTO - DFO) NewClip Hire Log 2018.xlsx 2 Collect Stepping Hill Courier ActivMotion (HTO - DFO) NewClip Hire Log 2018.xlsx 3 Collect York District Courier ActivMotion (HTO - DFO) NewClip Hire Log 2018.xlsx 4 Royal Devon Exeter ActivMotion (HTO - DFO) NewClip Hire Log 2018.xlsx 5 collect Spire Bristol Courier ActivMotion (HTO - DFO) NewClip Hire Log 2018.xlsx 6 Royal Devon Exeter ActivMotion (HTO - DFO) NewClip Hire Log 2018.xlsx 7 Send Bridlington Courier ToeMotion - MTP DF Arthrosurface Hire Log 2018.xlsx 8 Send Femoral Head Hampshire Clinic DHL Human Tissue Human Tissue Log.xlsx As you can see, the powerapps dataframe has a different column (which can contain different values, not only just…
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91186951
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91187321
tagged with: python
has comment: http://stackoverflow.com/comment/91186330
type: Question
has title: Pandas - Find the outlier row between two dataframes when only looking at certain columns
has comment: http://stackoverflow.com/comment/91187285
has comment: http://stackoverflow.com/comment/91186444

http://stackoverflow.com/q/52144880
has body: I'm using django 1.11 and PostgreSQL 9.6. When I want to test an app, I find that the django test will create and use a test database.This test database doesn't have an extension that need to be created first. So how to create an extension after create the test database and before create the test data？
upvote count: 6
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52145017
score: 6
type: Question
has comment: http://stackoverflow.com/comment/91848094
has title: How could I create a postgresql extension in django test setup
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52145017
favorite count: 0
tagged with: postgresql
tagged with: django
tagged with: python

http://stackoverflow.com/a/52152345
upvote count: 1
has body: numpy approach: numpy.repeat and numpy.reshape with pandas.DataFrame: import numpy as np import pandas as pd data = np.array(['1.5','2.5','1.3']) # numpy array s = pd.Series(data) # pandas series Option 1, by using the numpy.ndarray, numpy.repeat and numpy.reshape: df = pd.DataFrame(np.repeat(data,9).reshape((3, 9)), columns=['A' for i in range(9)]) Option 2, by using the values of the Series (values of a pandas.Series is also numpy.ndarray): df1 = pd.DataFrame(np.repeat(s.values,9).reshape((3, 9)), columns=['A' for i in range(9)]) Option 3, with different column names: df2 = pd.DataFrame(np.repeat(s.values,9).reshape((3, 9)), columns=[f'A{i}' for i in range(9)]) Output: Option1: df: A A A A A A A A A 0 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2 1.3 1.3 1.3 1.3 1.3 1.3 1.3 1.3 1.3 Option 2: df1: A A A A A A A A A 0 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2 1.3 1.3 1.3 1.3 1.3 1.3 1.3 1.3 1.3 Option 3: df2: A0 A1 A2 A3 A4 A5 A6 A7 A8 0 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2 1.3 1.3 1.3 1.3 1.3 1.3 1.3 1.3 1.3 numpy.repeat numpy.reshape
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52151831
score: 1

http://stackoverflow.com/a/52155609
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52155591
upvote count: 2
type: Answer
has body: Use print with format, it makes your code look good print("The Enemy's health is {} The Enemy is {}".format(str(EnemyHealth),EnemyIs)

http://stackoverflow.com/q/52241986
tagged with: jupyter-notebook
favorite count: 0
has answer: http://stackoverflow.com/a/52247920
type: Question
has body: I have the following code to add a table of contents to the beginning of my ipython notebooks. When I run the cell on jupyter on my computer I get But when I upload the notebook to github and choose to view the notebook, I see this for the first cell. Is there a way to enforce that this javascript line runs like the first picture when on github?
answer count: 2
tagged with: python
has title: Javascript not Executing on Github
possible better answer: http://stackoverflow.com/a/52247920
has answer: http://stackoverflow.com/a/52242277
upvote count: 1
downvote count: 0
tagged with: javascript
accepted answer: http://stackoverflow.com/a/52242277
type: AnsweredQuestion
score: 1
tagged with: github

http://stackoverflow.com/comment/91481453
comment on: http://stackoverflow.com/a/52261309
has text: I discovered something, any number x, which gives a remainder after % 4, i.e x % 4 != 0, will result to 2 when XORed to a number -2 itself. For example, 6. It is not divisible by 4, therefore, 6 XOR 6-2 (4),==> 2. 10 is not divisible by 4, hence, 10 XOR 10-2 (8) ==> 2. Can you please tell me how this could help me optimize my code? I just know now that I will just look for numbers divisible by 4 and find the count of their + 2.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52260968
has comment: http://stackoverflow.com/comment/91471563
has comment: http://stackoverflow.com/comment/91471527
has comment: http://stackoverflow.com/comment/91471388
has body: For giving the model and its data stored in db, I want to write it into an csv file. Yet, the first row of my resulted csv file was not in correct order. models.py class BRANCH(): ID = db.Column(db.String(6), primary_key=True) Branch = db.Column(db.String(20)) Status = db.Column(db.String(20)) Curr = db.Column(db.String(5)) Inputter = db.Column(db.String(35)) Createdon = db.Column(db.String(20)) Authorizer = db.Column(db.String(35)) Authorizeon = db.Column(db.String(20)) Description = db.Column(db.String(50)) LocalDescription = db.Column(db.String(50)) BranchManagerName = db.Column(db.String(35)) LocalBranchManagerName = db.Column(db.String(100)) ContactNumber = db.Column(db.String(35)) Address = db.Column(db.String(100)) LocalAddress = db.Column(db.String(100)) District = db.Column(db.String(9)) Province = db.Column(db.String(3)) ReportLocked = db.Column(db.String(1)) RegisteredDate = db.Column(db.String(20)) PrevMonthAmount = db.Column(db.Numeric(25, 9)) PrevYearAmount = db.Column(db.Numeric(25, 9)) So, the data store in db is like below: Branch | Status | Curr | Inputter | Createdon | Authorizer | Authorizeon | ID | Description | BranchManagerName | ContactNumber | Address | District | Province | ReportLocked | RegisteredDate | PrevYearAmount | PrevMonthAmount | LocalBranchManagerName | LocalDescription | LocalAddress --------+--------+------+-----------+---------------------+------------+---------------------+-----+-------------------------+-------------------+---------------+-----------------------------------------------------------------------------------------+----------+----------+--------------+----------------+----------------+-----------------+------------------------+------------------+----------------------------------------------------------------------------- HO | AUTH | 9 | MINAL | 2018-09-10 21:48:13 | MORAKOT.V | 2018-09-10 21:48:13 | HO | Head Office | Chariya Sambeth | N/A | #3722, Sihanou Blv, Veal Vonging, 7 Makara, Phnom Penh City. | | 12 | 1…
answer count: 2
has comment: http://stackoverflow.com/comment/91470511
accepted answer: http://stackoverflow.com/a/52349163
downvote count: 0
has comment: http://stackoverflow.com/comment/91470460
has comment: http://stackoverflow.com/comment/91470412
favorite count: 0
has comment: http://stackoverflow.com/comment/91469554
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/91483616
tagged with: python
has comment: http://stackoverflow.com/comment/91469676
has answer: http://stackoverflow.com/a/52321014
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91470099
upvote count: 1
possible better answer: http://stackoverflow.com/a/52321014
type: Question
has comment: http://stackoverflow.com/comment/91469907
has title: How to write CSV file correctly?
has answer: http://stackoverflow.com/a/52349163

http://stackoverflow.com/comment/91239427
type: Comment
type: QuestionComment
has text: Please look at the [`csv`](https://docs.python.org/3/library/csv.html?highlight=csv#module-csv) module it is designed for reading and writing csv files. `line.split()` returns a `list` the string literal of a `list` is `[...]` - hence what you are seeing in your file.
comment on: http://stackoverflow.com/q/52144847
score: 4

http://stackoverflow.com/comment/91376897
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52213678
has text: Oh I didn't realize this either, thank you for the tip!

http://stackoverflow.com/a/52177058
type: Answer
answers question: http://stackoverflow.com/q/52176882
has body: You could do this in a list comprehension: my_list = [ [(0.12064145946741212, 0.8105813193990855), 0.007220216606498195], [(0.12064145946741212, 0.8040496407576747), 0.007220216606498195], [(-1, 0.8105813193990855), 0], [(0.12064145946741212, -1), 0.007220216606498195], [(-1, -1), 2], [(-1, -1), 0]] [[(a[0], a[1]) if a[0]&gt;0 and a[1]&gt;0 else (0, 0) if a[0]&lt;0 and a[1]&lt;0 else (0, a[1]) if a[0]&lt;0 else (a[0], 0)] + [0.01] if c==0 else [(a[0], a[1]) if a[0]&gt;0 and a[1]&gt;0 else (0, 0) if a[0]&lt;0 and a[1]&lt;0 else (0, a[1]) if a[0]&lt;0 else (a[0], 0)] + [c] for a, c in my_list] output: [[(0.12064145946741212, 0.8105813193990855), 0.007220216606498195], [(0.12064145946741212, 0.8040496407576747), 0.007220216606498195], [(0, 0.8105813193990855), 0.01], [(0.12064145946741212, 0), 0.007220216606498195], [(0, 0), 2], [(0, 0), 0.01]]
upvote count: 1
has comment: http://stackoverflow.com/comment/91305520
downvote count: 0
has comment: http://stackoverflow.com/comment/91339141
score: 1

http://stackoverflow.com/comment/91311138
comment on: http://stackoverflow.com/a/52180305
type: AnswerComment
type: Comment
has text: @Ben, If that's true, then you shouldn't get "all columns converted to `object`" at the end. I suggest you add a minimal example showing this exactly happens. Because, right now, I refuse to believe an `int` series becomes `object` after converting some values to `0`.
score: 1

http://stackoverflow.com/q/52209106
type: AnsweredQuestion
has title: Python Can't understand conditional statement in loop
tagged with: conditional-statements
score: -2
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/91367597
has body: Need help in python. This code is from leetcode.com, one of the solutions for this problem and cannot understand conditional statement there, exactly the code "stack[-1][1]" class Solution(object): def dailyTemperatures(self, temps): if not temps: return [] result = [0] * len(temps) stack = [] for curr_idx, curr_temp in enumerate(temps): while stack and curr_temp &gt; stack[-1][1]: # not clear, and I know, it is not a type of access to list element last_idx, last_temp = stack.pop() result[last_idx] = curr_idx - last_idx stack.append((curr_idx, curr_temp)) return result
favorite count: 0
has answer: http://stackoverflow.com/a/52209193
accepted answer: http://stackoverflow.com/a/52209193
has comment: http://stackoverflow.com/comment/91367818
tagged with: statements
tagged with: python
upvote count: 0
has comment: http://stackoverflow.com/comment/91367699
tagged with: loops
type: Question

http://stackoverflow.com/q/52267547
has comment: http://stackoverflow.com/comment/91482985
tagged with: django
has title: In Django, how do you keep a module's url configurations encapsulated inside the module?
type: Question
tagged with: json-api
type: AnsweredQuestion
has body: Currently, I import url configurations into my Django project with: from django.conf.urls import include from django.contrib import admin from django.urls import path, re_path from rest_framework import routers from greeter.views import GreeterViewSet ROUTER = routers.DefaultRouter() ROUTER.register(r'greeters', GreeterViewSet) urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^', include(ROUTER.urls)), ] Is there a way where I can move these parts of the code: ROUTER = routers.DefaultRouter() ROUTER.register(r'greeters', GreeterViewSet) into a separate file in greeter/urls.py? And still keep these URLs: GET /greeter/ to fetch list of greeters POST /greeter/ to create a new greeter I have tried: my_project/urls.py from django.conf.urls import include from django.contrib import admin from django.urls import path, re_path urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^greeters/', include('greeter.urls')), ] greeter/urls.py from django.conf.urls import url, include from rest_framework import routers from .views import GreeterViewSet ROUTER = routers.DefaultRouter() ROUTER.register(r'^', GreeterViewSet) urlpatterns = [ url(r'^', include(ROUTER.urls)), ] But got: $ curl -H 'Accept: application/vnd.api+json; indent=2' -X POST http://localhost:8000/greeters/ { "errors": [ { "detail": "Method \"POST\" not allowed.", "source": { "pointer": "/data" }, "status": "405" } ] } In case it helps, here is my original question that has been resolved: Method "POST" not allowed with Django Rest Framework Update: With the help of the answers, I was able to arrive at this solution: my_project/urls.py from django.conf.urls import include from django.contrib import admin from django.urls import re_path urlpatterns = [ re_path('admin/', admin.site.urls), re_path('greeters/', include('greeter.urls')), ] greeter/urls.py from django.conf.urls import include from django.urls import re_path from rest_framework import routers from .views import GreeterViewSet ROUTER = router…
has answer: http://stackoverflow.com/a/52269832
accepted answer: http://stackoverflow.com/a/52269832
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/91482871
tagged with: django-rest-framework
favorite count: 0
possible better answer: http://stackoverflow.com/a/52267810
has answer: http://stackoverflow.com/a/52267810
tagged with: python
linked to: http://stackoverflow.com/q/52211142
has comment: http://stackoverflow.com/comment/91482841
score: 2
downvote count: 0

http://stackoverflow.com/comment/91413181
comment on: http://stackoverflow.com/a/52231148
has text: Could you share the url?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91488915
type: QuestionComment
has text: Use `df['ID_index'] = df.groupby('ID').cumcount() + 1`
comment on: http://stackoverflow.com/q/52270808
score: 4
type: Comment

http://stackoverflow.com/q/52125543
has comment: http://stackoverflow.com/comment/93759838
type: UnansweredQuestion
tagged with: python
tagged with: prompt
tagged with: anaconda
downvote count: 0
has body: I tried out the following command on the Anaconda command prompt, pip show tensorflow which gave me the result, Name: tensorflow Version: 1.10.0 Summary: TensorFlow is an open source machine learning framework for everyone. Home-page: https://www.tensorflow.org/ Author: Google Inc. Author-email: opensource@google.com License: Apache 2.0 Location: d:\softwares\pycond\envs\tensorflow2\lib\site-packages Requires: termcolor, absl-py, grpcio, tensorboard, wheel, protobuf, gast, six, numpy, setuptools, astor I want to know if the installed TensorFlow is CPU supported or GPU supported. How can I get this information?
score: 7
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/91202674
answer count: 1
has answer: http://stackoverflow.com/a/65534513
favorite count: 0
has title: How to find which TensorFlow is installed in my windows system? Whether it is CPU or GPU TensorFlow
upvote count: 7

http://stackoverflow.com/a/52254493
type: AcceptedAnswer
has body: It seems that my understanding of pytest fixtures was incomplete. The following works just fine: class Test(): @pytest.fixture(scope='class') def data(self): return ... def test_min(data): assert data.min() == 'min' def test_max(data): assert data.max() == 'max'
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52223723
answers question: http://stackoverflow.com/q/52223723
upvote count: 1

http://stackoverflow.com/q/52172380
has answer: http://stackoverflow.com/a/52172815
accepted answer: http://stackoverflow.com/a/52172815
type: Question
has title: Run a command, after return, python
has body: I have come across this issue, where I want to return something and call another function afterwards (in python) heres my current code: def new_user(request): '''Takes a request and enters it in the database IF that wallet id is not in the database! ''' data = request.body if data != '': user_info = eval(data) if type(user_info) != type({}): ... more code here ... send_email(vCode) return HttpResponse(response) I want to call send_email after returning a response. I have tried a few things here: -calling both new_user and send_email in another function but I need to return some sort of HttpResponse (so I can't call new_user without returning it...) so this does not work - tried to yield a request, cannot call another function after yield -tried threading, had a similar issue -Currently trying asyncio but i'm running into issues with that aswell, is there anything else I can do?
linked to: http://stackoverflow.com/q/37024343
has comment: http://stackoverflow.com/comment/91296342
has answer: http://stackoverflow.com/a/52172511
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52172464
has comment: http://stackoverflow.com/comment/91323595
tagged with: python
tagged with: asynchronous
possible better answer: http://stackoverflow.com/a/52172511
tagged with: return
tagged with: django
type: AnsweredQuestion

http://stackoverflow.com/comment/91477991
type: AnswerComment
has text: Thank you for your answer! I will give this a try and accept the answer if it worked out.
type: Comment
comment on: http://stackoverflow.com/a/52263383
score: 0

http://stackoverflow.com/comment/91385657
comment on: http://stackoverflow.com/q/52169226
type: Comment
type: QuestionComment
has text: would you show an example of how the python subprocess invoked.
score: 1

http://stackoverflow.com/comment/91445032
score: 0
type: Comment
has text: f.read() was the way to go! Much appreciated. This is working now!
type: AnswerComment
comment on: http://stackoverflow.com/a/52246242

http://stackoverflow.com/q/52131535
type: Question
has comment: http://stackoverflow.com/comment/91213779
accepted answer: http://stackoverflow.com/a/52131699
has answer: http://stackoverflow.com/a/52131790
tagged with: numpy
answer count: 2
tagged with: pandas
has title: Identify first non-zero element within group composed of multiple columns in pandas
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52131699
tagged with: python
linked to: http://stackoverflow.com/q/51583908
score: 2
type: AnsweredQuestion
has body: I have a dataframe that looks like the following. The rightmost column is my desired column: Group1 Group2 Value Target_Column 1 3 0 0 1 3 1 1 1 4 1 1 1 4 1 0 2 5 5 5 2 5 1 0 2 6 0 0 2 6 1 1 2 6 9 0 How do I identify the first non-zero value in a group that is made up of two columns(Group1 &amp; Group2) and then create a column that shows the first non-zero value and shows all else as zeroes? This question is very similar to one posed earlier here: Identify first non-zero element within a group in pandas but that solution gives an error on groups based on multiple columns. I have tried: import pandas as pd dt = pd.DataFrame({'Group1': [1,1,1,1,2,2,2,2,2], 'Group2': [3,3,4,4,5,5,6,6,6], 'Value': [0,1,1,1,5,1,0,1,9]}) dt['Newcol']=0 dt.loc[dt.Value.ne(0).groupby(dt['Group1','Group2']).idxmax(),'Newcol']=dt.Value
upvote count: 2
has comment: http://stackoverflow.com/comment/91213741
possible better answer: http://stackoverflow.com/a/52131790

http://stackoverflow.com/q/52129572
answer count: 2
has answer: http://stackoverflow.com/a/52129735
linked to: http://stackoverflow.com/q/3535615
has body: Consider the following models: class Car(Model): owner = ForeignKey(User) ... some irrelevant attributes ... class User(Model): # Django user model Given a queryset of users, is there an easy way (e. g. one method call) how to get a queryset of cars which are owned by a user from the first queryset? Something like User.objects.all().related("cars").
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52129586
possible better answer: http://stackoverflow.com/a/52129735
tagged with: orm
tagged with: django
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52129586
has title: Django ORM - get queryset of related items
type: Question

http://stackoverflow.com/a/52174883
has body: One potential solution is to use a simpler GUI package. Perhaps the GUI package PySimpleGUI would be a fit. It could solve your GUI problem and free you up to work on the other portions of your project. Check out the Chat Demo that implements a Chat front-end. Therre's also a Chatterbot Demo that implements a front-end to the Chatterbot project. You can start by copying that code and modifying it.
answers question: http://stackoverflow.com/q/52135974
has comment: http://stackoverflow.com/comment/92273170
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92200926
has comment: http://stackoverflow.com/comment/92241278
has comment: http://stackoverflow.com/comment/91300797
type: Answer
has comment: http://stackoverflow.com/comment/92207482
has comment: http://stackoverflow.com/comment/92271980
downvote count: 0

http://stackoverflow.com/comment/91407451
type: QuestionComment
has text: You could also stack up `a[::2]` and `a[1::2]` and then reshape that. I don’t know if it’ll be much shorter. Ultimately, you’re doing two things: un-interleaving and array, and reshaping an array—and any readable solution is going to involve two steps like your existing ones.
score: 3
comment on: http://stackoverflow.com/q/52228885
type: Comment

http://stackoverflow.com/comment/91302771
comment on: http://stackoverflow.com/q/52168164
type: Comment
type: QuestionComment
score: 1
has text: Run your problematic code in a loop: if the memory doesn’t keep climbing, it’s not a leak but merely failure to return memory to the OS (which is common and complicated).

http://stackoverflow.com/q/52269397
has comment: http://stackoverflow.com/comment/91486166
has answer: http://stackoverflow.com/a/52277979
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91508965
linked to: http://stackoverflow.com/q/4706499
has comment: http://stackoverflow.com/comment/91503709
has comment: http://stackoverflow.com/comment/91486525
has title: insert content in a specific place inside an existing file python
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52269667
has body: I am trying to append the parameters passed to a function to a specific place in an existing text file. txt file: query{ text:"", source_language:"", target_language:"", }, data_type:[16], params{ client:"xyz" } python: def function(text,source_language,target_language): f = open("file.txt", "w"); f.write( 'text:' + text + '\n' ) f.write( 'source_language:' + source_language + '\n' ) f.write( 'target_language:' + target_language + '\n' ) f.close() But, its not working. Is there a way to append the parameters directly into the file including " " and ,. I am trying to add just the parameters into the existing file with data at the specified position.
tagged with: file
type: Question

http://stackoverflow.com/q/52250013
has comment: http://stackoverflow.com/comment/91520289
has comment: http://stackoverflow.com/comment/91448186
tagged with: python-3.x
has body: I am running Python 3.6.2 and trying to import other files into my shell prompt as needed. I have the following code inside my_file.py. import numpy as np def my_file(x): s = 1/(1+np.exp(-x)) return s From my 3.6.2 shell prompt I call from my_file import my_file But in my shell prompt if I want to use the library numpy I still have to import numpy into the shell prompt even though I have imported a file that imports numpy. Is this functionality by design? Or is there a way to import numpy once?
has answer: http://stackoverflow.com/a/52250243
type: UnansweredQuestion
upvote count: 7
type: Question
score: 7
tagged with: numpy
has title: Does importing a Python file also import the imported files into shell?
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91448234
favorite count: 0
tagged with: python

http://stackoverflow.com/q/52188923
tagged with: python
linked to: http://stackoverflow.com/q/7972141
answer count: 0
has title: Python Selenium Converted to Powershell
type: Question
has comment: http://stackoverflow.com/comment/91327951
tagged with: powershell
has comment: http://stackoverflow.com/comment/91330092
score: 0
has body: Looking to write a script for work to go to one of our websites and auto populate a page for submission. I have created this below with python below but I would like to avoid downloading anything extra onto our servers (ie. Python). Wondering if there is a library in powershell like selenium for python. Is there a way to find the xpath or name of buttons in IE like you do in chrome? Python script below: import time from selenium import webdriver #Go to website Site driver = webdriver.Chrome("C:/WebDrivers/chromedriver.exe") # Optional argument, if not specified will search path. driver.get('yourwebsite'); time.sleep(2) # Let page load! #Log In with Credentials search_box = driver.find_element_by_name("txtUserName") search_box.send_keys('YourUsername')#Your Username search_box1 = driver.find_element_by_name("txtPassword") search_box1.send_keys('YourPassword')#Your Password submit_button = driver.find_element_by_name('btnLogin') submit_button.click() time.sleep(10) # Let page load!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91372495

http://stackoverflow.com/comment/91355863
type: Comment
type: QuestionComment
score: 0
has text: Just to make sure it works in general, did you try a derivative-free algorithm?
comment on: http://stackoverflow.com/q/52202006

http://stackoverflow.com/comment/91343366
comment on: http://stackoverflow.com/a/52133610
score: 0
type: AnswerComment
has text: also read the documentation and the article for more information.[Documentation link](http://docs.python-requests.org/en/master/user/quickstart/),[Article link](https://datawookie.netlify.com/blog/2016/09/view-post-data-using-chrome-developer-tools/)
type: Comment

variables
tag name: variables
tags question: http://stackoverflow.com/q/52176813
tags question: http://stackoverflow.com/q/52113425
tags question: http://stackoverflow.com/q/52155591
tags question: http://stackoverflow.com/q/52254421
tags question: http://stackoverflow.com/q/52127886
tags question: http://stackoverflow.com/q/52247428
type: Tag
tags question: http://stackoverflow.com/q/52178329
tags question: http://stackoverflow.com/q/52196843
tags question: http://stackoverflow.com/q/52248600
tags question: http://stackoverflow.com/q/52184796
tags question: http://stackoverflow.com/q/52142155
tags question: http://stackoverflow.com/q/52223069
tags question: http://stackoverflow.com/q/52189200
tags question: http://stackoverflow.com/q/52194648
tags question: http://stackoverflow.com/q/52179198
tags question: http://stackoverflow.com/q/52128868

http://stackoverflow.com/comment/91477945
type: AnswerComment
type: Comment
has text: Indeed, it was this simple :-) Thank you very much!
comment on: http://stackoverflow.com/a/52253221
score: 0

http://stackoverflow.com/a/52119020
type: Answer
has comment: http://stackoverflow.com/comment/91189583
has comment: http://stackoverflow.com/comment/91189048
has body: AFAIK, there's no sklearn.family module. Have you tried importing other modules? Say, from sklearn.model_selection import TimeSeriesSplit Does that work for you?
has comment: http://stackoverflow.com/comment/91189243
has comment: http://stackoverflow.com/comment/91194310
score: 0
answers question: http://stackoverflow.com/q/52118969
has comment: http://stackoverflow.com/comment/91189199
has comment: http://stackoverflow.com/comment/91193075

http://stackoverflow.com/comment/91228472
has text: Thanks, but I managed to find an easier way. I installed Python 3.6.6 in a separate folder and installed spyder there. The shortcut to the corresponding .exe automatically starts with Python 3.6.6, so I just have to switch spyder if I want to use another Python version. While this solution isn't very beautiful, it's enough for my purposes.
comment on: http://stackoverflow.com/a/52138321
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/a/52290216
has body: I became curious if it's possible to implement such kind of triangle oscillator without conditions and enumerations. Well, one option is the following: def oscillator(magnitude): i = 0 x = y = -1 double_magnitude = magnitude + magnitude while True: yield i x = (x + 1) * (1 - (x // (double_magnitude - 1))) # instead of (x + 1) % double_magnitude y = (y + 1) * (1 - (y // (magnitude - 1))) # instead of (y + 1) % magnitude difference = x - y # difference ∈ {0, magnitude} derivative = (-1 * (difference &gt; 0) + 1 * (difference == 0)) i += derivative The idea behind this is to take 2 sawtooth waves with different periods and subtract one from another. The result will be a square wave with values in {0, magnitude}. Then we just substitute {0, magnitude} with {-1, +1} respectively to get derivative values for our target signal. Let's look at example with magnitude = 5: o = oscillator(5) [next(o) for _ in range(21)] This outputs [0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0]. If abs() is allowed, it can be used for simplicity. For example, the following code gives the same output as above: [abs(5 - ((x + 5) % 10)) for x in range(21)]
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52187275
type: Answer

http://stackoverflow.com/comment/91410082
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52230058
type: AnswerComment
has text: Odd... that doesn't start with "MZ" like the other two. What were you using to see the binary data that's in your question? (the one with MZ and a bunch of � glyphs)

http://stackoverflow.com/comment/91179897
type: QuestionComment
comment on: http://stackoverflow.com/q/52114719
score: 1
has text: Put `resume_code` inside the `try` block…!?
type: Comment

http://stackoverflow.com/q/52269448
has title: kaggle: Charts plotted using Altair visualization library did not show up after commit
answer count: 1
has body: I am using Altair Visualization library for plotting charts in a kaggle kernel. When I run cell by cell, the charts show up. But when I commit the notebook and see the result, the charts are not shown. I checked the altair version using the alt.version command. I am using the latest version of altair as per the above result. I even tried adding 'vega' package from settings and committing. Even then, the altair charts were not shown. Not sure what's going wrong.
score: 0
accepted answer: http://stackoverflow.com/a/52277346
tagged with: altair
has answer: http://stackoverflow.com/a/52277346
tagged with: kaggle
tagged with: python
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/91187615
type: QuestionComment
has text: The idea is to remove that rows that not present consecutive numbers in E in reference with the column A
comment on: http://stackoverflow.com/q/52118251
score: 0
type: Comment

http://stackoverflow.com/a/52188999
has body: I do not think you can delete the root environment because this is where all packages are downloaded and it is the main path of the anaconda you installed. What you can do, however, is source activate py3.6 in your bashrc file right under the export line of your anaconda3 path. So in your .bashrc file you should have: # added by Anaconda3 installer export PATH="/home/lvtingbo/anaconda3/bin:$PATH" source activate py3.6 This will load your environment everytime you start a terminal.
answers question: http://stackoverflow.com/q/52185521
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/96209200
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91401628
type: AnswerComment
type: Comment
has text: Futher to your suggestions. I believe I will go with the DB management option. Unfortunately I need this to be "active or inactive" session, e.g. the timer must continue regardless of if the user is currently connected or logged in etc. A well deserved accepted answer sir, thank you for your time!
comment on: http://stackoverflow.com/a/52216293
score: 0

http://stackoverflow.com/q/52199392
has body: I am new here and a beginner in Python. I retrieved a JSON list using requests which an example of the output is: {"data":[{"Id":"12345", "Name":"C123", "StartTime": 153507240000, "EndTime": 1535077800000}, {"Id": "12346", "Name": "C124", "StartTime": 1530839700000, "EndTime": 1530864000000} ]} And I would like to sort it according to the oldest (or lowest StartTime) to a new variable where I print out and format it properly but I have no idea how to do it
upvote count: 1
tagged with: python
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91348437
tagged with: http://stackoverflow.com/tag/json
type: Question
has comment: http://stackoverflow.com/comment/91347866
answer count: 1
tagged with: sorting
has answer: http://stackoverflow.com/a/52199470
favorite count: 0
accepted answer: http://stackoverflow.com/a/52199470
score: 0
has title: How can I sort a JSON list according to time (in milliseconds)?

http://stackoverflow.com/a/52188695
accepted answer of: http://stackoverflow.com/q/52188421
type: AcceptedAnswer
type: Answer
has body: Here is how you could do it. import schedule def start(): print("{} Start the job".format(datetime.datetime.now())) def stop(): print("{} Time's up!!!".format(datetime.datetime.now())) sys.exit() schedule.every().day.at("09:00").do(start) schedule.every().day.at("17:00").do(stop)
downvote count: 0
has comment: http://stackoverflow.com/comment/91379822
score: 3
answers question: http://stackoverflow.com/q/52188421
has comment: http://stackoverflow.com/comment/91381476
upvote count: 3

http://stackoverflow.com/a/52133567
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91217555
has body: Simple one liner: newdict={v:[i for i in dict1.keys() if v in dict1[i]] for k,v in dict1.items() for v in v} print(newdict) Output: {4: [1, 2], 12: [1], 22: [1], 5: [2], 13: [2], 23: [2], 7: [3], 15: [3], 25: [3]} To merge them: print({**dict1,**newdict})
type: Answer
has comment: http://stackoverflow.com/comment/91264767
has comment: http://stackoverflow.com/comment/91247544
upvote count: 1
answers question: http://stackoverflow.com/q/52133506
accepted answer of: http://stackoverflow.com/q/52133506

http://stackoverflow.com/q/52184733
tagged with: expression
has comment: http://stackoverflow.com/comment/91319382
has answer: http://stackoverflow.com/a/52184848
possible better answer: http://stackoverflow.com/a/52184836
type: Question
has answer: http://stackoverflow.com/a/52184836
accepted answer: http://stackoverflow.com/a/52184785
has comment: http://stackoverflow.com/comment/91319465
score: -1
has comment: http://stackoverflow.com/comment/91319235
favorite count: 0
has body: I don't understand why does this code return repr of object instead of value 20. &gt;&gt;&gt; a = 10 &gt;&gt;&gt; lambda a: a*2 This is what is returned to standard output: &lt;function &lt;lambda&gt; at 0x02D93780&gt;
has answer: http://stackoverflow.com/a/52184941
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/52184785
tagged with: python
tagged with: lambda
answer count: 4
has title: Lambda expression not returning value
type: AnsweredQuestion

http://stackoverflow.com/comment/91268355
has text: can you just share the steps.. It is a `TypeError` which mean you have made a mistake in syntax
type: AnswerComment
comment on: http://stackoverflow.com/a/52159038
type: Comment
score: 0

http://stackoverflow.com/a/52285462
type: Answer
answers question: http://stackoverflow.com/q/52268879
has body: I have found the solution here Incompatible dense layer error in keras I don't think I can mark mine as a duplicate question... Essentially the issue I was having was that I was asking the network to give me an output of (batch_size, 2) when in reality I wanted to get an answer for EVERY data point along the input! I combined bad practices from several tutorials all into one to give me a ton of issues. Hopefully this helps anyone with the same issue. Also my updated code is posted below. def create_model(x_train, GRU_units,DR): model = Sequential() print("Adding first layer...") model.add(CuDNNLSTM(GRU_units, input_shape = (x_train.shape[1:]), return_sequences=True)) model.add(Dropout(DR)) print(model.output_shape) print("Adding second layer...") model.add(CuDNNLSTM(GRU_units, return_sequences=True)) model.add(Dropout(DR)) print(model.output_shape) print("Adding third layer...") model.add(CuDNNLSTM(GRU_units, return_sequences=True)) model.add(Dropout(DR)) print(model.output_shape) print("Adding fourth layer (Dense 32)...") model.add(TimeDistributed(Dense(32, activation='relu'))) model.add(Dropout(DR)) print(model.output_shape) print("Adding output layer...") model.add(TimeDistributed(Dense(1, activation='sigmoid'))) print(model.output_shape) return model
score: 0

http://stackoverflow.com/comment/91634304
comment on: http://stackoverflow.com/q/52257394
score: 0
type: Comment
type: QuestionComment
has text: @Goyo. Your criticism is accurate and agreed. Realizing that fact and worrying at the consequences led me to the answer which I have placed below. Thank you.

http://stackoverflow.com/q/52138664
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91227068
tagged with: django
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91237806
type: Question
has comment: http://stackoverflow.com/comment/91238202
tagged with: database
has body: Hi Guys sorry for being so dumb, but i got this problem even after installing django again and starting a new project, have searched online with no avail for a week now. Every time i run migrations this error appears, it is giving me a headache, have tried, python manage.py runserver --fake, have tried removing py files deleting database and so on and failed Here is the error PS C:\Users\Willie\desktop\maoni\maoni&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\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", lin e 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", lin e 330, in execute output = self.handle(*args, **options) File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\commands\migr ate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\executor.py", l ine 20, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\loader.py", lin e 52, in __init__ self.build_graph() File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\loader.py", lin e 274, in build_graph raise …
score: 0
has title: Migration dependencies reference nonexistent When starting a new project
tagged with: migration
has comment: http://stackoverflow.com/comment/91227019

http://stackoverflow.com/q/52123892
has comment: http://stackoverflow.com/comment/91199561
answer count: 3
possible better answer: http://stackoverflow.com/a/52124176
has answer: http://stackoverflow.com/a/52124176
tagged with: nan
favorite count: 0
has answer: http://stackoverflow.com/a/52124109
score: 20
tagged with: python
has body: This puzzles me: a = np.array([1, 2, np.nan, 3]) # an array with a nan print(np.isnan(a)[2]) # it truly is a nan print(a[2]) # it quacks like a nan print(np.nan is np.nan) # nan's can be compared print(a[2] is np.nan) # But then, this isn't a nan after all!!?? Output: True nan True False I know we're not allowed to compare nan's with ==, but with is should be allowed? After all it works when comparing nan to itself?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/13650293
has comment: http://stackoverflow.com/comment/91199083
accepted answer: http://stackoverflow.com/a/52124109
has title: numpy NaN not always recognized
type: Question
tagged with: numpy
upvote count: 20
downvote count: 0
has comment: http://stackoverflow.com/comment/91199386
has answer: http://stackoverflow.com/a/52123905

http://stackoverflow.com/a/68288454
type: Answer
score: 0
has body: I have used a different approach to solve the problem: def Markov_Steady_State_Prop(p): p = p - np.eye(p.shape[0]) for ii in range(p.shape[0]): p[0,ii] = 1 P0 = np.zeros((p.shape[0],1)) P0[0] = 1 return np.matmul(np.linalg.inv(p),P0) The results are the same as yours and I think your expected results are somehow wrong or they are the approximate version.
answers question: http://stackoverflow.com/q/52137856

http://stackoverflow.com/q/52241117
type: Question
has comment: http://stackoverflow.com/comment/91431454
has answer: http://stackoverflow.com/a/52241562
tagged with: filenames
score: 1
has comment: http://stackoverflow.com/comment/91431468
has comment: http://stackoverflow.com/comment/91431453
duplicate of: http://stackoverflow.com/q/4020539
answer count: 2
linked to: http://stackoverflow.com/q/1885181
has title: Handling backslash escapes in filenames read from a file
has comment: http://stackoverflow.com/comment/91430886
downvote count: 0
linked to: http://stackoverflow.com/q/4020539
tagged with: text-processing
favorite count: 0
has comment: http://stackoverflow.com/comment/91431478
has body: TL;DR: text file contains strings that represent backslash escapes; how do I use them as input to os.stat() ? I've an input file input.txt: ./with\backspace ./with\nnewline Processing them with simple loop doesn't work: &gt;&gt;&gt; import os &gt;&gt;&gt; with open('input.txt') as f: ... for line in f: ... os.stat(line.strip()) ... Traceback (most recent call last): File "&lt;stdin&gt;", line 3, in &lt;module&gt; FileNotFoundError: [Errno 2] No such file or directory: './with\\backspace' Using .decode("unicode_escape") as suggested in another question works only partially - the first line in the file fails, the second with \n doesn't. Sidenote: The input filenames have ./ and I know I can just use os.listdir('.') and iterate over files till I find the right ones. That's not my objective. The objective is processing filenames that contain backslash escapes from a file. Additional test: &gt;&gt;&gt; import os &gt;&gt;&gt; with open('./input.txt') as f: ... for l in f: ... os.stat(l.strip().decode('unicode_escape')) ... Traceback (most recent call last): File "&lt;stdin&gt;", line 3, in &lt;module&gt; AttributeError: 'str' object has no attribute 'decode' &gt;&gt;&gt; with open('./input.txt') as f: ... for l in f: ... try: ... os.stat(l.strip().encode('utf-8').decode('unicode_escape')) ... print(l.strip()) ... except: ... pass ... os.stat_result(st_mode=33188, st_ino=1053469, st_dev=2049, st_nlink=1, st_uid=1000, st_gid=1000, st_size=0, st_atime=1536468565, st_mtime=1536468565, st_ctime=1536468565) ./with\nnewline Writing explicit string with os.fsencode() works: &gt;&gt;&gt; os.stat(os.fsencode('with\x08ackspace')) os.stat_result(st_mode=33188, st_ino=1053465, st_dev=2049, st_nlink=1, st_uid=1000, st_gid=1000, st_size=0, st_atime=1536468565, st_mtime=1536468565, st_ctime=1536468565) However, with multiple variations on the same command, I still can't read the string from the file such that os.stat() accepts it. &gt;&gt;&gt; with open('./input.txt') as f: ... for l in …
has comment: http://stackoverflow.com/comment/91431473
has answer: http://stackoverflow.com/a/52241946
linked to: http://stackoverflow.com/q/21772271
tagged with: python
linked to: http://stackoverflow.com/q/28583565
has comment: http://stackoverflow.com/comment/91431432
has comment: http://stackoverflow.com/comment/91430849
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91431360
upvote count: 1
has comment: http://stackoverflow.com/comment/91431420

http://stackoverflow.com/comment/91308975
type: QuestionComment
type: Comment
has text: ``Nothing else should be increasing the memory usage`` - well no, each new ``long`` object stored in the list takes some extra memory.
comment on: http://stackoverflow.com/q/52160127
score: 0

http://stackoverflow.com/comment/91228886
has text: I don't want to go into the reasons why I am not using a `virtualenv` (/`conda` , etc). They have all been looked at (and tried) multiple times and are no less problematic. I am on `macos`
type: AnswerComment
comment on: http://stackoverflow.com/a/52139485
score: 0
type: Comment

http://stackoverflow.com/comment/91340696
score: 0
type: Comment
type: QuestionComment
has text: @KaiserKatze. Since OP is reporting a normal return, they are both iterables.
comment on: http://stackoverflow.com/q/52195456

http://stackoverflow.com/comment/91435517
comment on: http://stackoverflow.com/q/52243520
score: 0
has text: Well, did you try?
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52267652
score: 0
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
linked to: http://stackoverflow.com/q/12160418
answer count: 0
type: UnansweredQuestion
tagged with: performance
has body: I am trying to parse a 17G XML file. I need to read all attributes of each tag () and save them in a CSV. I am using the following code to parse XML. It is taking too much time to parse. For example, 10000 rows take more than 5 minutes to be exported. I have a Windows machine (Intel i5 2.4GHz/8G RAM). Sample XML &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;comments&gt; &lt;row Id="2" PostId="35314" Score="8" Text="Yeah, I didn't believe it until I created a console app - but good lord! Why would they give you the rope to hang yourself! I hated that about VB.NET - the OrElse and AndAlso keywords!" CreationDate="2008-09-06T08:09:52.330" UserId="3" /&gt; &lt;/comments&gt; Python Code import xml.etree.ElementTree as etree import pandas as pd df = pd.DataFrame(columns=('Id','PostId','Score','Text','CreationDate','UserId')) def process_params(elem): global df row = [elem.attrib.get('Id'),elem.attrib.get('PostId'),elem.attrib.get('Score'),elem.attrib.get('Text'),elem.attrib.get('CreationDate'),elem.attrib.get('UserId')] df.loc[len(df)] = row if (len(df) % 10000 == 0): with open('xaa.csv', 'a', encoding="utf-8") as f: df.to_csv(f, header=False) print("{} rows exported".format(len(df))) for event, elem in etree.iterparse("xaa.xml", events=('start', 'end')): if event == 'start': if elem.tag == 'row': process_params(elem) Tried another variant of code without Pandas which fails due to memory outage def process_params(elem): row = [elem.attrib.get('Id'),elem.attrib.get('PostId'),elem.attrib.get('Score'),elem.attrib.get('Text'),elem.attrib.get('CreationDate'),elem.attrib.get('UserId')] with open("comments1.csv", "a", encoding="utf-8") as f: wr = csv.writer(f) wr.writerow(row) for event, elem in etree.iterparse("comments.xml", events=('start', 'end')): if event == 'start': if elem.tag == 'row': process_params(elem) Tried a few more variants, but nothing worked or takes forever. Please suggest.
has comment: http://stackoverflow.com/comment/91484545
type: Question
tagged with: xml-parsing
has comment: http://stackoverflow.com/comment/91484645
has title: XML Parsing performance tuning python
has comment: http://stackoverflow.com/comment/91488967

http://stackoverflow.com/q/52120205
tagged with: noaa
has body: I have had great success parsing RSS feeds from the National Hurricane Center using the feedparser module: import feedparser feedparser.parse('https://www.nhc.noaa.gov/gis-at.xml') #Works Fine feedparser.parse('https://www.nhc.noaa.gov/gis-ep.xml') #Works Fine However, when I try to read the superficially similar feed from the Central Pacific Hurricane Center, I generate a KeyError: feedparser.parse('http://www.prh.noaa.gov/cphc/gis-cp.xml') #Doesn't work Is this a bug with feedparser? Is the CPHC's feed malformed? Is there an option that I've forgotten to specify? It seems the trouble is that there isn't a key named 'where', but I don't know why this isn't a problem for the NHC feeds. The stack is reproduced below: &gt;&gt;&gt; import feedparser &gt;&gt;&gt; feedparser.parse('http://www.prh.noaa.gov/cphc/gis-cp.xml') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File ".../anaconda3/lib/python3.6/site-packages/feedparser.py", line 3956, in parse saxparser.parse(source) File ".../anaconda3/lib/python3.6/xml/sax/expatreader.py", line 111, in parse xmlreader.IncrementalParser.parse(self, source) File ".../anaconda3/lib/python3.6/xml/sax/xmlreader.py", line 125, in parse self.feed(buffer) File ".../anaconda3/lib/python3.6/xml/sax/expatreader.py", line 217, in feed self._parser.Parse(data, isFinal) File "/tmp/build/80754af9/python_1516124163501/work/Modules/pyexpat.c", line 414, in StartElement File ".../anaconda3/lib/python3.6/xml/sax/expatreader.py", line 370, in start_element_ns AttributesNSImpl(newattrs, qnames)) File ".../anaconda3/lib/python3.6/site-packages/feedparser.py", line 2031, in startElementNS self.unknown_starttag(localname, list(attrsD.items())) File ".../anaconda3/lib/python3.6/site-packages/feedparser.py", line 666, in unknown_starttag return method(attrsD) File ".../anaconda3/lib/python3.6/site-packages/feedparser.py", line 1500, in _start_gml_point self._parse_srs_attrs(attrsD) File ".../anaconda3/lib/python3.6/si…
has answer: http://stackoverflow.com/a/72502485
type: Question
upvote count: 2
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
score: 2
downvote count: 0
tagged with: rss
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/126561477
tagged with: feedparser
has title: Unexpected error when using feedparser.py

http://stackoverflow.com/comment/91413173
comment on: http://stackoverflow.com/a/52203010
has text: Thanks! But there was no link after I run it. Am I going to the right way? The code I put: gpslocation = [] for gps in (secondpage_parser.find("a", {"data-track-id":"Google Map"})['href']): gpslocation.append(gps.attrs["href"])
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52207927
answer count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
tagged with: java
type: Question
tagged with: python-2.7
upvote count: 1
has title: Does python have an equivalent to Java's hashUnencodedChars?
favorite count: 0
has body: I am hashing a string in Java with Hashing.sha256().hashUnencodedChars(data) and I need to recreate this same hash in Python. The current hash I am using for Python is hashlib.sha256(data.encode('utf-8')).hexdigest() These do not create the same hash. As the Java method implies, it is not encoding the value before it hashes. Can I achieve the same functionality in Python?
tagged with: hash

http://stackoverflow.com/comment/121808803
score: 1
comment on: http://stackoverflow.com/a/67705358
type: AnswerComment
type: Comment
has text: When I try this solution I recieve NameError: name 'ax' is not defined.

http://stackoverflow.com/a/52146668
answers question: http://stackoverflow.com/q/52146321
accepted answer of: http://stackoverflow.com/q/52146321
score: 2
type: AcceptedAnswer
downvote count: 0
has body: You may just pass the type of the new object. For instance, &gt;&gt;&gt; def convert(v,t): ... return t(v) &gt;&gt;&gt; a = "test" &gt;&gt;&gt; b = convert(a,list) &gt;&gt;&gt; b ['t', 'e', 's', 't'] &gt;&gt;&gt; b = convert(a,bool) &gt;&gt;&gt; b True &gt;&gt;&gt; b = convert(b,int) &gt;&gt;&gt; b 1 &gt;&gt;&gt; b = convert(b,float) &gt;&gt;&gt; b 1.0
upvote count: 2
type: Answer

signals
tags question: http://stackoverflow.com/q/52112869
tags question: http://stackoverflow.com/q/52135916
tags question: http://stackoverflow.com/q/52261803
tags question: http://stackoverflow.com/q/52196010
type: Tag
tags question: http://stackoverflow.com/q/52200328
tags question: http://stackoverflow.com/q/52163733
tag name: signals

http://stackoverflow.com/q/52130461
has answer: http://stackoverflow.com/a/54877927
type: Question
has title: python zerorpc and multiprocessing issue
tagged with: zeromq
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91584413
favorite count: 0
has body: I'm implementing a bi-directional ping-pong demo app between an electron app and a python backend. This is the code for the python part which causes the problems: import sys import zerorpc import time from multiprocessing import Process def ping_response(): print("Sleeping") time.sleep(5) c = zerorpc.Client() c.connect("tcp://127.0.0.1:4243") print("sending pong") c.pong() class Api(object): def echo(self, text): """echo any text""" return text def ping(self): p = Process(target=ping_response, args=()) p.start() print("got ping") return def parse_port(): port = 4242 try: port = int(sys.argv[1]) except Exception as e: pass return '{}'.format(port) def main(): addr = 'tcp://127.0.0.1:' + parse_port() s = zerorpc.Server(Api()) s.bind(addr) print('start running on {}'.format(addr)) s.run() if __name__ == '__main__': main() Each time ping() is called from javascript side it will start a new process that simulates some work (sleeping for 5 seconds) and replies by calling pong on nodejs server to indicate work is done. The issue is that the pong() request never gets to javascript side. If instead of spawning a new process I create a new thread using _thread and execute the same code in ping_response(), the pong request arrives in the javascript side. Also if I manually run the bash command zerorpc tcp://localhost:4243 pong I can see that the pong request is received by the nodejs script so the server on the javascript side works ok. What happens with zerorpc client when I create a new process and it doesn't manage to send the request ? Thank you. EDIT It seems it gets stuck in c.pong()
has comment: http://stackoverflow.com/comment/91584506
tagged with: zerorpc
tagged with: python
score: 2
tagged with: electron
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/52135916
has body: I'm trying to prevent my UDP client program from waiting forever in cases of a lost packet from the server. I want to use signals to implement this. My code is: def handler(signum): raise TimeoutException("Timeout occured!") signal.signal(signal.SIGALRM, sig_alarm) sock.sendto(data,serv) signal.alarm(5) try: received_time, servaddr = sock.recvfrom(size) except TimeoutException: print "timeout" signal.alarm(0) When running this code in the instance in which the remote server is down, I get the following error: global name 'TimeoutException' is not defined I assume the program does not "see" my handler. What may cause it?
type: UnansweredQuestion
has title: Timeout using signals in Python
has answer: http://stackoverflow.com/a/52137822
tagged with: network-programming
type: Question
score: 0
answer count: 2
tagged with: signals
linked to: http://stackoverflow.com/q/1319615
has answer: http://stackoverflow.com/a/52137624
has comment: http://stackoverflow.com/comment/91223819
has comment: http://stackoverflow.com/comment/91222111
tagged with: sockets
tagged with: python

http://stackoverflow.com/comment/91412052
type: QuestionComment
score: 1
has text: Still unclear, also your model definitions have several errors, like the field employee_family_ids with form_family_id as the target model. You should edit your whole question to make it clear because I could tell you that you could override the create and write from one model to write into the other one the relation field that connect boths records, or you could write a function field to search for all the records matching boths model relations, but it's not clear to me what it's your goal and design
comment on: http://stackoverflow.com/q/52175453
type: Comment

http://stackoverflow.com/a/52214629
type: Answer
has body: You can try any example from below two: example 1: with file handling: with open(filename) as stream: result={} for item in stream.readlines()[1:]: line = item.strip().split() result.update({line[0]:line[2]}) #line[i] is column index to create dict print(result) example 2: with pandas. import pandas as pd df = pd.read_csv(filename, sep='\t', lineterminator='\r') result = dict(zip(df["English Word"],df["Dragon Translation"])) #df['column_name'] is column name to create dict print(result)
score: 0
answers question: http://stackoverflow.com/q/52214170

http://stackoverflow.com/a/52193381
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52190143
answers question: http://stackoverflow.com/q/52190143
type: Answer
score: 1
has body: You are using str.replace, from the documentation: Return a copy of the string with all occurrences of substring old replaced by new Here an occurrence means an exact match of the string old, then the function will try to replace a word surrounded by whitespaces, for example ' book ' that is different than ' BOOK ', ' Book ' and ' book'. Let's see a few cases that also don't match: " book " == " BOOK " # False " book " == " book" # False " book " == " Book " # False " book " == " bOok " # False " book " == " book " # False One alternative is to use a regex like this: import re words = ["book", "rule"] sentences = ["This book is amazing", "The not so good book", "OMG what a great BOOK", "One Book to rule them all", "Just book."] patterns = [re.compile(r"\b({})\b".format(word), re.IGNORECASE | re.UNICODE) for word in words] replacements = ['' + word + '' for word in words] for sentence in sentences: result = sentence[:] for pattern, replacement in zip(patterns, replacements): result = pattern.sub(r'\1', result) print(result) Output This book is amazing The not so good book OMG what a great BOOK One Book to rule them all Just book.
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/52214192
has body: I used this in an xterminal to include trusty repository in synaptic. echo "deb http://archive.ubuntu.com/ubuntu trusty main universe" | sudo tee /etc/apt/sources.list.d/wily-copies.list after this in Synaptic-packagemanager reloaded the repository and then I installed it. Be sure to un-select the repository (under "Settings" "Repositories" "Additional repositories") so you won't install obsolete software from this old repository
downvote count: 1
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/52199666
type: Answer

http://stackoverflow.com/q/52127601
answer count: 1
has body: I have written a code with django and celery, it is for a machine to run some tasks and to be accessible through net. So I need the django and celery to run automatically when the built-in PC starts. Can anyone please tell me the best and easiest way to do this? Can servers like Apache handle such thing?
has answer: http://stackoverflow.com/a/52540500
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 0
tagged with: celery
type: Question
has title: Celery + Django on startup
tagged with: apache

http://stackoverflow.com/a/52158117
has comment: http://stackoverflow.com/comment/91267886
has comment: http://stackoverflow.com/comment/91303061
score: 5
answers question: http://stackoverflow.com/q/52155642
upvote count: 5
has comment: http://stackoverflow.com/comment/91267914
has comment: http://stackoverflow.com/comment/110110109
has comment: http://stackoverflow.com/comment/91335589
has body: There is no need to use the Flatten after the LSTM as the LSTM (per default) only returns the last state and not a sequence, i.e. the data will have the shape (BS, n_output) but the Flatten layer expects a shape of (BS, a, b) which will be transformed into (BS, a*b). So, either remove the Flatten layer and work just with the last state or add return_sequences=True to the LSTM. This will make the LSTM to return all outputs and not just the last one, i.e. (BS, T, n_out). Edit: Also, the way how you created the final model is wrong. Please take a look at this example; for you, it should be something like this: merge = Concatenate([lstm_model, cnn_model]) hidden = Dense(1, activation = 'sigmoid') conc_model = Sequential() conc_model.add(merge) conc_model.add(hidden) conc_model.compile(...) output = conc_model .fit(X_train, y_train, epochs=3, batch_size=64) All in all, it might be better to use the Functional API. Edit 2: This is the final code cnn_model = Sequential() cnn_model.add(Embedding(top_words, embedding_vecor_length, input_length=max_review_length)) cnn_model.add(Conv1D(filters=32, kernel_size=3, padding='same', activation='relu')) cnn_model.add(MaxPooling1D(pool_size=2)) cnn_model.add(Flatten()) lstm_model = Sequential() lstm_model.add(Embedding(top_words, embedding_vecor_length, input_length=max_review_length)) lstm_model.add(LSTM(64, activation = 'relu', return_sequences=True)) lstm_model.add(Flatten()) # instead of the last two lines you can also use # lstm_model.add(LSTM(64, activation = 'relu')) # then you do not have to use the Flatten layer. depends on your actual needs merge = Concatenate([lstm_model, cnn_model]) hidden = Dense(1, activation = 'sigmoid') conc_model = Sequential() conc_model.add(merge) conc_model.add(hidden)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91335999
has comment: http://stackoverflow.com/comment/91300066
type: Answer
accepted answer of: http://stackoverflow.com/q/52155642
has comment: http://stackoverflow.com/comment/91335550
has comment: http://stackoverflow.com/comment/91267429

http://stackoverflow.com/a/52235164
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52235103
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/122324416
answers question: http://stackoverflow.com/q/52235103
downvote count: 1
score: 5
has body: You are seeing the limit of Python's integer interning here. The CPython implementation keeps a pool of small int objects (-5 through 257) in memory and reuses them as much as possible. That is why id(a) and id(1) return the same value; both a and the literal 1 refer to the same object. That value, though, is a much larger integer (namely 1844525312). That means that Python is free to (and does) allocate separate int objects for the return value of id(a) and id(1), leading to the result you see. 1844525312 == 1844525312 is true, but id(a) and id(1) each return separate objects that represent the same value, leading to id(a) is id(1) returning false. Note that with a = 1; id(a) == id(1) is not guaranteed to be true by Python itself; it's an implementation detail of a particular Python interpreter. It's allowed for an implementation to always allocate a new object for each new use, and it is allowed for an implementation to always reuse an existing object where possible. The only time Python guarantees that id(a) == id(b) for separate names a and b is if one name is assigned directly to the other (b = a or a = b).
has comment: http://stackoverflow.com/comment/122324348

http://stackoverflow.com/a/52255996
answers question: http://stackoverflow.com/q/52255960
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91459512
upvote count: 2
has comment: http://stackoverflow.com/comment/91459658
has body: list_out = [('2240', '313', {'Sign': 1}), ('2240', '321', {'Sign': 1}), ('2240', '365', {'Sign': -1})] column2=[j for _,j,_ in list_out] output ['313', '321', '365']
type: Answer

http://stackoverflow.com/q/52144101
accepted answer: http://stackoverflow.com/a/52144120
type: AnsweredQuestion
has body: I have a df in below format: Priority Mined_Category server date_reported Count Zscore_Volume 1 - Critical Memory issue xxxxxx111 2018-07-11 1 nan 1 - Critical Memory issue xxxxxx111 2018-08-11 1 nan 1 - Critical Memory issue yyyyyy195 2018-07-06 1 1.71 1 - Critical Memory issue yyyyyy195 2018-07-08 1 1.71 2 - High Memory issue abcabcabcba1410 2018-08-21 1 nan my aim is to replace nan with 100 whenever Priority Mined_Category and Server groupby count is 1 and replace nan with 1000 whenever Priority Mined_Category and Server groupby count is >1 I tried below code: &gt; df_aggegrate_Volume.loc[(df_aggegrate_Volume.groupby(["Priority","Mined_Category","server"]).count()&gt;1)&amp;(df_aggegrate_Volume['Zscore_Volume'].isnull()) ,"Zscore_Volume"]= -100 but I get below error: ValueError: operands could not be broadcast together with shapes (7410,) (3,)
score: 1
upvote count: 1
answer count: 1
has title: ValueError: operands could not be broadcast together with shapes (7410,) (3,)
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
favorite count: 0
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/52144120

http://stackoverflow.com/q/52225743
has comment: http://stackoverflow.com/comment/91405747
tagged with: azure-machine-learning-service
has title: How can I read a local file from an R or Python script in Azure Machine Learning Studio?
score: 4
tagged with: http://stackoverflow.com/tag/r
tagged with: azure
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/91492334
type: Question
has body: I need to read a csv file, which is saved in my local computer, from code within an "Execute R/Python Script" in an experiment of Azure Machine Learning Studio. I don't have to upload the data as usually, i.e. from Datasets -> New -> Load from local file or with an Import Data module. I must do it with code. In principle this is not possible, neither from an experiment nor from a notebook, and in fact I always got error. But I'm confused because the documentation about Execute Python Script module says (among other things): Limitations The Execute Python Script currently has the following limitations: Sandboxed execution. The Python runtime is currently sandboxed and, as a result, does not allow access to the network or to the local file system in a persistent manner. All files saved locally are isolated and deleted once the module finishes. The Python code cannot access most directories on the machine it runs on, the exception being the current directory and its subdirectories. According to the highlighted text, it should be possible to access and load a file from current directory, using for instance the pandas function read_csv. But actually no. There is some trick to accomplish this? Thanks.
has answer: http://stackoverflow.com/a/52247446

http://stackoverflow.com/comment/91381459
comment on: http://stackoverflow.com/q/52216318
score: 0
has text: I think the problem is in use of single quote and double quote. Better keep ```{{ url_for('static', filename='./img/logo.png') }}``` in a separate variable and concatenate.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52241340
upvote count: 0
duplicate of: http://stackoverflow.com/q/14939953
has body: I'm trying to create a program that takes a number and sums it But for some reason the code wont work number = input("please enter a four digit number: ") final = sum(number) print(final) TypeError: unsupported operand type(s) for +: 'int' and 'str' I've attempted to convert it into a integer and string but it keeps saying that each of them is irritable What am I doing wrong?
type: Question
has answer: http://stackoverflow.com/a/52241354
score: -2
has answer: http://stackoverflow.com/a/52241411
downvote count: 2
linked to: http://stackoverflow.com/q/14939953
answer count: 3
has title: python 3 summing numbers from input
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52241625
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91478541
comment on: http://stackoverflow.com/q/52265021
type: Comment
type: QuestionComment
has text: @mad_ sorry my bad, im building service only for one country, so timezone is not important. Thank you
score: 0

http://stackoverflow.com/comment/91421807
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52236537
has text: @user2357112 Sorry about the spelling. But I see no explicit hint about asking for a static check in the body of the question. And in tag list there are both _typing_ and _static-typing_. I can hardly determine if OP wants no runtime check.

http://stackoverflow.com/q/52115366
has body: I trained a model for neural network to find the roots of the quadratic equation (discriminant >= 0) But when I checked the same on my example, even the loss is small it is showing a far from exact answer. Loss graph: My example: a = 1 b = -2 c = -24 model.predict(np.array(a/max,b/max,c/max)) * max Out[421]: array([[-15.218947 , -1.3733944]], dtype=float32) #but should be 6 and -4 Look here please: import numpy as np from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.utils import np_utils from keras.layers import Dropout x_in = np.array([]).reshape(0,3) x_answer = np.array([]).reshape(0,2) for i in range(300): a = np.random.randint(-1000,1000) b = np.random.randint(-1000,1000) c = np.random.randint(-1000,1000) D = np.power(b,2)-4*a*c if(a != 0): if(D &gt;= 0): x1 = (-b+np.sqrt(D))/(2*a) x2 = (-b-np.sqrt(D))/(2*a) x_in = np.concatenate((x_in,a,b,c)) x_answer = np.concatenate((x_answer,x1,x2)) np.random.seed() NB_EPOCH = 300 VERBOSE = 1 x_in = np.asarray(x_in, dtype=np.float32) x_answer = np.asarray(x_answer, dtype=np.float32) min_in = np.nanmin(x_in) min_answ = np.nanmin(x_answer) min = -1000 #np.min(np.array([min_in,min_answ])) max_in = np.nanmax(x_in) max_answ = np.nanmax(x_answer) max = 1000 #np.max(np.array([max_in,max_answ])) x_in /= max x_answer /= max model = Sequential() model.add(Dense(30, input_dim = 3, activation='relu')) #model.add(Dropout(0.2)) model.add(Dense(40, activation='softmax')) #model.add(Dropout(0.2)) model.add(Dense(50, activation='linear')) model.add(Dense(2)) model.compile(loss='mse', optimizer='adam') history = model.fit(x_in, x_answer, epochs=NB_EPOCH, verbose=VERBOSE) UPDATE: what to do?
has title: Neural Network Loss Inaccurate
type: Question
answer count: 1
tagged with: neural-network
tagged with: keras
has comment: http://stackoverflow.com/comment/91181524
score: 0
has comment: http://stackoverflow.com/comment/91197431
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52115601
tagged with: python
has comment: http://stackoverflow.com/comment/91181763

http://stackoverflow.com/a/52253517
downvote count: 0
type: Answer
has body: Assuming, you want a list of tags, you can do the following: for line in f.readlines(): new_line = '' isTag = False for char in line: if char == "&lt;": isTag = True elif char == "&gt;": isTag = False empty_tag_list.append(new_line) new_line = '' elif isTag: new_line += char print(empty_tag_list) # ['html', 'head', 'title', '/title', '/head', 'body', '/body', '/html']
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52253357

http://stackoverflow.com/q/52152944
has comment: http://stackoverflow.com/comment/91260828
has body: The data I'm working with is in a Pandas DataFrame with about a thousand rows looking like this myData.head() Coordinates Cluster 0 [53.044341, -2.2496476] None 1 [53.1498286, -2.2358307] None 2 [53.2562888, -1.9137567] None 3 [53.2588584, -1.9120726] None 4 [53.2588584, -1.9120726] None The Cluster column in myData will have the index number of the cluster they belong to, which is referenced in the clusterCenters DataFrame (20 clusters in length): The cluster centers are generated by picking 20 random coordinates from myData like so: clusterCenters = random.sample(myData['Coordinates'], 20) clusterCenters.head() Clusters centers 0 [52.8901739, -2.1489866] 1 [53.3838042, -2.4839233] 2 [52.910345, -1.5138248] 3 [52.9816612, -2.1729386] 4 [53.3154335, -2.0873787] I have two main functions, one to assign members to clusters and one to find the mean of the points to use within the algorithm. def assignCluster(cluster_df,ccenters): # Add members to each cluster by finding difference between every cluster and the current coordinate and adding coordinate point to lowest difference. cluster_belong = [] # For each post code coordinate for row in cluster_df.iterrows(): co = row[1]['Coordinates'] d = [] # For each cluster center coordinate for index, cluster_co in ccenters.iterrows(): d.append(distance.euclidean(cluster_co[0], co)) # list d now has the distance between the current post code coordinate and every cluster center coordinate # append the index value (which is one of the cluster centers) for every post code coordinate cluster_belong.append(d.index(sorted(d)[0])) # for the moment, we will append the closest cluster center, but my goal is to append the closest cluster center that has less than 40 members already. (LC below) Is this even possible? # cluster_belong.append(d.index([x for index, x in enumerate(sorted(d)) if len(LBBL_df[LBBL_df['Cluster'] == index]) &lt; 40][0]) cluster_df['Cluster'] = cluster_belong return cluster_df def find_CO_mean(cluster,mean_col): me…
favorite count: 0
has comment: http://stackoverflow.com/comment/91256532
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91260898
has comment: http://stackoverflow.com/comment/91257129
answer count: 0
score: 1
upvote count: 1
has title: I wrote a simple clustering algorithm in Python but I don't get the intended result. Is my algorithm correct?
has comment: http://stackoverflow.com/comment/91258868
has comment: http://stackoverflow.com/comment/91256693
type: Question
has comment: http://stackoverflow.com/comment/91260386
tagged with: k-means
downvote count: 0
has comment: http://stackoverflow.com/comment/91257024

http://stackoverflow.com/q/52138630
has body: Consider the following code: class A: def __init__(self): def do(): print("y") return iter([1,2,3]) self.__iter__ = do def __iter__(self): print("x") return iter([4,5,6]) for x in A(): print(x) for x in A().__iter__(): print(x) The output is: x 4 5 6 y 1 2 3 What I would expect as an output: y 1 2 3 y 1 2 3 How does iter() (which is called by the for loop) work and why does it not call the object's __iter__() that has been overridden in the constructor but the classes' default __iter__()? Edit: Workaround: class A: def __init__(self): def do(): print("y") return iter([1,2,3]) self.it = do def __iter__(self): return self.it() for x in A(): print(x) for x in A().__iter__(): print(x)
upvote count: 3
downvote count: 1
linked to: http://stackoverflow.com/q/33824228
type: Question
tagged with: iterator
duplicate of: http://stackoverflow.com/q/33824228
favorite count: 0
tagged with: python-3.x
has title: Understanding how iter() works, does not call the object's __iter__()
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/91227060
answer count: 0

awk
tag name: awk
tags question: http://stackoverflow.com/q/52212182
type: Tag
tags question: http://stackoverflow.com/q/52160126

http://stackoverflow.com/a/52116727
has comment: http://stackoverflow.com/comment/91184585
upvote count: 0
has comment: http://stackoverflow.com/comment/91185653
has comment: http://stackoverflow.com/comment/91186254
has comment: http://stackoverflow.com/comment/91184435
has comment: http://stackoverflow.com/comment/91189436
has comment: http://stackoverflow.com/comment/91185622
answers question: http://stackoverflow.com/q/52116500
type: Answer
downvote count: 1
score: -1
has comment: http://stackoverflow.com/comment/91184579
has body: The virtual environment tree contains a bin directory, and setuptools will install stub programs there that correctly set up the Python environment and then run some main function within that. This means you can directly run one of those stub programs without "activating" the virtual environment or setting up any environment variables. If you have a directory tree that looks roughly like: \--.virtualenvs +-- app-py37 | +-- bin | | \-- app | \-- lib | \-- ... | \-- app_main.py +-- other-py27 +-- bin | \-- helper \-- lib \-- ... \-- helper_main.py and you invoked the helper with a call like import os import subprocess subprocess.run([os.path.join(os.environ('HOME'), '.virtualenvs', 'other-py27', 'bin', 'helper'], check=True) I would expect it to correctly set up its own Python environment.

http://stackoverflow.com/comment/91333503
has text: I get no errors running the code as given and using tf.InteractiveSession().
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52190877
score: 0

http://stackoverflow.com/q/52218258
upvote count: 3
has comment: http://stackoverflow.com/comment/91385365
has answer: http://stackoverflow.com/a/64081904
downvote count: 1
answer count: 1
tagged with: keras
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I was trying to use Keras but it showed mw this error :(. Using TensorFlow backend. Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in &lt;module&gt; import keras File "C:\Python37\lib\site-packages\keras\__init__.py", line 3, in &lt;module&gt; from . import utils File "C:\Python37\lib\site-packages\keras\utils\__init__.py", line 6, in &lt;module&gt; from . import conv_utils File "C:\Python37\lib\site-packages\keras\utils\conv_utils.py", line 9, in &lt;module&gt; from .. import backend as K File "C:\Python37\lib\site-packages\keras\backend\__init__.py", line 89, in &lt;module&gt; from .tensorflow_backend import * File "C:\Python37\lib\site-packages\keras\backend\tensorflow_backend.py", line 5, in &lt;module&gt; import tensorflow as tf File "C:\Python37\lib\site-packages\tensorflow\__init__.py", line 22, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import File "C:\Python37\lib\site-packages\tensorflow\python\__init__.py", line 49, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "C:\Python37\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Python37\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 114 def TFE_ContextOptionsSetAsync(arg1, async): ^ SyntaxError: invalid syntax Additional information: python version: 3.7. Tensorflow version: 1.10.0.
score: 2
has comment: http://stackoverflow.com/comment/91385505
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/91385341
type: Question
has title: unable to import tensorflow and keras
linked to: http://stackoverflow.com/q/51824226

http://stackoverflow.com/q/52176124
has comment: http://stackoverflow.com/comment/91335663
tagged with: discord.py
has comment: http://stackoverflow.com/comment/91336313
score: 1
has title: NameError: name 'ctx' is not defined
has comment: http://stackoverflow.com/comment/91336004
has comment: http://stackoverflow.com/comment/91302818
downvote count: 0
linked to: http://stackoverflow.com/q/51127860
has comment: http://stackoverflow.com/comment/91639684
favorite count: 0
tagged with: python-3.x
has body: Keep getting this error in my discord bot cog. I use message.author in other cogs just fine just with events not commands. async def on_member_join(member): with open('profiles.json', 'r') as f: profiles = json.load(f) await update_profile(profiles, member) with open('profiles.json', 'w') as f: json.dump(profiles, f, indent=2) @commands.command(name='my', pass_context=True) async def my(self, ctx): with open('profiles.json', 'r') as x: profiles = json.load(x) await self.update_profile(profiles, ctx.message.author) with open('profiles.json', 'w') as x: json.dump(profiles, x, indent=2) async def update_profile(self, user, message): profile_params = {'Xbox Live': 'xbl', 'PSN': 'psn', 'Steam ID': 'stm','Nintendo Friend Code': 'nfc'} msg = ctx.message bmsg = msg[4:7] emsg = msg[8:] if not user.name in users and not user.bot: do some stuff This is the error i get I have tried many work arounds with this I can not find anything that will fix this issue Traceback (most recent call last): File "C:\Users\Erik\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 50, in wrapped ret = yield from coro(*args, **kwargs) File "D:\Discord Bot\profiles.py", line 28, in my await self.update_profile(profiles, ctx.message.author) File "D:\Discord Bot\profiles.py", line 36, in update_profile msg = ctx.message NameError: name 'ctx' is not defined I have tried many work arounds searching for similar issues. I have noticed that it works fine in the main py file and it also works fine in a cog in the on_message event. It only does not work when I use it inside a @commands.command command function.
type: UnansweredQuestion
tagged with: python
tagged with: discord
has comment: http://stackoverflow.com/comment/91336279
answer count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/91655588
type: Question

http://stackoverflow.com/q/52158931
type: Question
linked to: http://stackoverflow.com/q/32442608
has comment: http://stackoverflow.com/comment/91267802
has answer: http://stackoverflow.com/a/52161434
answer count: 1
has body: I am trying to work on my little side project with python (recently started learning about it), and I'm trying to make an emoji converter. What I mean by that, is that when a text contains an emoji, the converter would that word into an emoji. An example would be: String to translate: Smile! You're too cool. Translation: ! You're too . The problem is, I have no slightest idea where to begin, and the things I have tried keep giving me the same error: UnicodeEncodeError: 'UCS-2' codec can't encode character '\U0001f40d' in position 0: Non-BMP character not supported in Tk Any suggestions? Thanks in advance
favorite count: 0
has title: Emojis in Python
upvote count: 2
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/52154875
tagged with: emoji
has comment: http://stackoverflow.com/comment/91268958
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91267818

http://stackoverflow.com/a/52268199
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91485104
has comment: http://stackoverflow.com/comment/91489228
has comment: http://stackoverflow.com/comment/91484257
has comment: http://stackoverflow.com/comment/91489426
accepted answer of: http://stackoverflow.com/q/52268130
has comment: http://stackoverflow.com/comment/91484264
has body: Try zip + list comprehension + product + for-loop + indexing (even works for below list): from itertools import product A = [["1a", "ab"], ["2b", "cd"], ["1a", "ef"], ['2b','gh']] l,_=zip(*A) l2=[idx for idx,i in enumerate(l) if l.count(i)&gt;1] l3=list(set([tuple(sorted((x,y))) for x,y in product(l2,repeat=2) if l[x]==l[y] and x!=y])) for x,y in l3: A[x][1]=[A[x][1],A[y][1]] A.pop(y) print(A) Output: [['1a', ['ab', 'ef']], ['2b', ['cd', 'gh']]]
answers question: http://stackoverflow.com/q/52268130
has comment: http://stackoverflow.com/comment/91486990
has comment: http://stackoverflow.com/comment/91484301
has comment: http://stackoverflow.com/comment/91484323
score: 0

http://stackoverflow.com/comment/91438960
has text: @|'-'| wait... do you mean i should rename the column after fillforward right? can i not do it during the concatenation? or maybe i just need to set the name in df2 right?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52244619
type: AnswerComment

http://stackoverflow.com/a/52146662
score: 1
has comment: http://stackoverflow.com/comment/91243288
has body: Add the folder project/testA to the system pythonpath first: import sys sys.path.insert(0, "/path/to/pythonfile") and try the import again.
downvote count: 0
has comment: http://stackoverflow.com/comment/91244322
upvote count: 1
answers question: http://stackoverflow.com/q/52146524
type: Answer

http://stackoverflow.com/a/52149742
answers question: http://stackoverflow.com/q/52148916
score: 0
type: AcceptedAnswer
type: Answer
has body: user_input = input("Type an integer: ") user_int = int(user_input) if user_int % 3==0: print("Yes") else: print("No") print("Yes") Use modulo operator
accepted answer of: http://stackoverflow.com/q/52148916

http://stackoverflow.com/a/52179296
downvote count: 0
has body: In your validation function, def validation(model, testloader, criterion): test_loss = 0 accuracy = 0 for inputs, classes in testloader: inputs = inputs.to('cuda') output = model.forward(inputs) test_loss += criterion(output, labels).item() ps = torch.exp(output) equality = (labels.data == ps.max(dim=1)[1]) accuracy += equality.type(torch.FloatTensor).mean() return test_loss, accuracy You are iterating on testloader and passing values to the variables inputs, classes but you are passing labels to your criterion.
accepted answer of: http://stackoverflow.com/q/52178922
answers question: http://stackoverflow.com/q/52178922
score: 5
type: AcceptedAnswer
upvote count: 5
type: Answer

http://stackoverflow.com/comment/138847934
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/77376902
has text: This works well if you are running your script in a vm where there is no screen. In my case i was running in google cloud compute engine. VERY GREAT SOLUTION.

http://stackoverflow.com/q/52148131
type: Question
has body: I am new to django , I am unable to set path to load js and css file from directory. When I run server my page is showing without css and js. I setting file of project I have set static path as: STATIC_URL = '/templates/' and in template directory I have 3 dir named html, js, css. I am able to load html file from html dir but not js and css.
has comment: http://stackoverflow.com/comment/91246607
answer count: 1
has title: How to load static JavaScript file and css in Django with Pycharm
tagged with: python
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52149551
tagged with: django

http://stackoverflow.com/comment/91268396
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52159341
has text: I think you should edit your code snipped. You asked why np.nan is True, but the snippet shows that it is False
score: 1

http://stackoverflow.com/comment/91415158
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52218418
has text: What proxies are you using? I guess your server's IP is not entered into the proxy's authorized IPs section.

http://stackoverflow.com/a/52267237
score: 0
answers question: http://stackoverflow.com/q/52257249
type: Answer
has body: if you want to make the bot repeat the author's message, and delete the original, try using this: @bot.command(pass_context=True) async def say(ctx, *args): mesg = ''.join(args) await bot.delete_message(ctx.message) return await bot.say(mesg)

http://stackoverflow.com/q/52226755
answer count: 2
has title: Removing pairs that belong to the same distance score in python pandas
favorite count: 0
possible better answer: http://stackoverflow.com/a/52226940
tagged with: pandas
has answer: http://stackoverflow.com/a/52227130
accepted answer: http://stackoverflow.com/a/52227130
has answer: http://stackoverflow.com/a/52226940
duplicate of: http://stackoverflow.com/q/51182228
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: duplicates
tagged with: dataframe
has body: I am working on a code to calculate distances between each and every string in a row. My code is working good. However, my problem now is in filtering my results for example I have the following resulted data frame : nodeA nodeB distance_score 0 0 0 0 1 95 0 2 105 1 0 95 1 1 0 1 2 128 ........ I want to remove one of rows that belongs to the same nodes for example for the pair (0,1) and (1,0) one entry is enough. Based on my experience in Matlab, I could've done so by iterating over two loops and store the elements of each loop in an array and then check if the are already elements in these arrays and remove them. But I dont think this is the optimized way to do it in python since I have a huge data files and doing so will cost a lot
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/51182228

http://stackoverflow.com/comment/91442412
score: 0
type: Comment
type: QuestionComment
has text: Please post the traceback. If you get that error during a `migrate` call, it's likely that your app is trying to access an User object too early (for example during import time).
comment on: http://stackoverflow.com/q/52247216

http://stackoverflow.com/q/52194174
accepted answer: http://stackoverflow.com/a/52194239
score: 0
has title: Check if one column matches all objects in a list from another column
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
tagged with: string
has body: I have a dataframe with one column of strings and another with a list of strings. 0 1 0 apples are good [orange, banana] 1 bananas are good [bananas, bad] 2 cucumbers are green [cucumbers, are] 3 grapes are green [grapes, are, green] 4 oranges are good [oranges] 5 pineapples are big [flowers, apples] I want the find all the indices where the string in Column 0 matches all the list contents in Column 1. In this case the output would look like: 0 1 2 cucumbers are green [cucumbers, are] 3 grapes are green [grapes, are, green] 4 oranges are good [oranges] I know I can use pandas.Series.str.contains but that only works on a single list and I want to avoid iterating/looping if possible.
has answer: http://stackoverflow.com/a/52194239
tagged with: python
type: AnsweredQuestion
type: Question

http://stackoverflow.com/q/52124961
tagged with: numpy
score: 2
has answer: http://stackoverflow.com/a/52125135
type: AnsweredQuestion
has body: I want to convert python 2d list, [[1,2,3],[4,5,6]] to python3 array.array type, [ [1 2 3] [4 5 6] ] The most important challenge is I wont import numpy. So I cant use np.asarray(). I have also used array.fromlist() and array.extend(). Both methods are creating an array of single dimension. But I want to convert multi dimension list to multi dimension array. Is there any way?
tagged with: arrays
has comment: http://stackoverflow.com/comment/91201737
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/52125135
tagged with: list
has comment: http://stackoverflow.com/comment/91201165
upvote count: 3
has title: how to convert 2d list to 2d native python array not numpy array?
answer count: 1
downvote count: 1

http://stackoverflow.com/q/52175730
has title: Python - Question on logging in __init__.py
has comment: http://stackoverflow.com/comment/91302276
type: Question
score: 9
upvote count: 9
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91405916
has body: I have the following python package structure. python_logging python_logging __init__.py first_class.py second_class.py run.py Here is the code in __init__.py init.py import logging import logging.config # Create the Logger loggers = logging.getLogger(__name__) loggers.setLevel(logging.DEBUG) # Create the Handler for logging data to a file logger_handler = logging.FileHandler(filename='C:\Python\Log\stest.txt') logger_handler.setLevel(logging.DEBUG) # Create a Formatter for formatting the log messages logger_formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s') # Add the Formatter to the Handler logger_handler.setFormatter(logger_formatter) # Add the Handler to the Logger loggers.addHandler(logger_handler) loggers.info('Completed configuring logger()!') Here is code for first_class.py import logging class FirstClass(object): def __init__(self): self.current_number = 0 self.logger = logging.getLogger(__name__) def increment_number(self): self.current_number += 1 self.logger.warning('Incrementing number!') self.logger.info('Still incrementing number!!') Here is code for second_class.py class SecondClass(object): def __init__(self): self.enabled = False self.logger = logging.getLogger(__name__) def enable_system(self): self.enabled = True self.logger.warning('Enabling system!') self.logger.info('Still enabling system!!') Here is code for run.py from LogModule.first_class import FirstClass from LogModule.second_class import SecondClass number = FirstClass() number.increment_number() system = SecondClass() system.enable_system() This is the output in the log file LogModule - INFO - Completed configuring logger()! LogModule.first_class - WARNING - Incrementing number! LogModule.first_class - INFO - Still incrementing number!! LogModule.second_class - WARNING - Enabling system! LogModule.second_class - INFO - Still enabling system!! Question : How did number.increment_number() and system.enable_system() write to a log file when the file handler was initia…
has answer: http://stackoverflow.com/a/63690930
favorite count: 0
tagged with: python
tagged with: logging
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/63690930

http://stackoverflow.com/comment/91361813
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52206327
has text: @shadowtalker agreed, some data cleaning is probably needed.

http://stackoverflow.com/comment/91252571
type: QuestionComment
type: Comment
has text: Redefining the builtin sum might confuse some here
score: 0
comment on: http://stackoverflow.com/q/52151122

http://stackoverflow.com/comment/91446753
type: QuestionComment
has text: As it stands now it is unclear what you are asking. Would be much better if you your data and what you are trying to make it look like.
type: Comment
comment on: http://stackoverflow.com/q/52247252
score: 0

http://stackoverflow.com/a/52225729
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52224432
has body: It is probably a matter of taste and of how you intend to use your objects. If it is OK for you to limit your objects to deal with a single tf.Session (as in Keras — should cover basic needs and probably a bit beyond), then you could simply instantiate a single tf.Session via your preferred Singleton-like pattern (maybe just plain old functions like in Keras).

http://stackoverflow.com/q/52236984
has title: except: invalid syntax after using actionChains
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/52237077
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91422529
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52237077
tagged with: python
has body: i get an error at this part of my code. try: actionChains.double_click(driver.find_element_by_xpath("//div[4]/form/div/div").perform() except NoSuchElementException: actionChains.double_click(driver.find_element_by_xpath("//form/div[2]/div").perform() If I remove the second line of the code (actionChains.double_click(driver.find_element_by_xpath("//div[4]/form/div/div").perform() ), it works. But, if I don't It doesn't. Any help is greatly appreciated!
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/52205323
tagged with: python
has comment: http://stackoverflow.com/comment/91359944
has title: Method call with a handed over function parameter
tagged with: pyqt5
type: AnsweredQuestion
tagged with: widget
has answer: http://stackoverflow.com/a/52205499
type: Question
tagged with: pyqt
has body: I'm currently working on an UI based on Qt, pyqt and Python as my language. I would like to know if there is any way that I can define a method, which I can hand over a variabel that is later used in a function call. Currently I'm solving it like this: def loader(self, filePath, id): #firstTable, secondTable and thirdTable are three different Table Widgets in the UI if id == "1": tab = self.ui.firstTable elif id == "2": tab = self.ui.secondTable elif id == "3": tab = self.ui.thirdTable tab.clearContents() with open(filePath, "r", encoding="utf-8") as file: rowCount = tab.rowCount() columnCount = tab.columnCount() csvReader = csv.reader(file, delimiter=",", quotechar="'") for row in csvReader: if csvReader.line_num &gt; rowCount: tab.insertRow(csvReader.line_num - 1) for i in range(0, columnCount): tab.setItem((csvReader.line_num - 1), i, QtWidgets.QTableWidgetItem(row[i])) tab.sortItems(1) I want to solve it somewhat like this, but I just don't know how to do it and did not find any solution while researching this problem: def loader(self, filePath, widget): #variabel widget would be the corresponding object name I want to adress, like firstTable, secondTable, thirdTable #... self.ui.widget.clearContents() #... self.ui.widget.rowCount() I hope I could explain my problem properly and someone can help me with it. Thank you! Edit: Here is how I'm currently calling the loader: self.loader("file.csv", "1")
answer count: 1
score: 0
accepted answer: http://stackoverflow.com/a/52205499

http://stackoverflow.com/q/52161380
has answer: http://stackoverflow.com/a/52161406
has title: Does condition selection preserve order in Pandas DataFrame?
tagged with: dataframe
score: 4
upvote count: 4
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52161579
tagged with: python
has body: For example, df = pandas.DataFrame({'name':['a','b','c'], 'age':[10,20,30]}) name age 0 a 10 1 b 20 2 c 30 df[df['age'] &gt; 10] name age 1 b 20 2 c 30 My question is: Does Pandas make sure the index order is preserved? Is any possible the result like: name age 2 c 30 1 b 20 Thanks
type: Question

http://stackoverflow.com/q/52173331
tagged with: telepot
has body: I'm using this line for a custom keyboard on my Telegram bot: markup = ReplyKeyboardMarkup(keyboard=[['Time', KeyboardButton(text='NewKey')],["File", "Audio"]]) I want my bot to change custom keyboard to another when user sends NewKey. And it will send show up a new custom keyboard but it's layout will be same as the default keyboard. I have tried this but it is not working: elif command == 'NewKey': markup = ReplyKeyboardMarkup(keyboard=[['More', KeyboardButton(text='More2')],["More3", "More5"]]) Here is my full code of my bot: import time, datetime import telepot from telepot.loop import MessageLoop from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton now = datetime.datetime.now() def action(msg): chat_id = msg['`chat']['id'] command = msg['text'] print('Received: %s' % command) markup = ReplyKeyboardMarkup(keyboard=[['Time', KeyboardButton(text='NewKey')],["File", "Audio"]]) if command == '/start': telegram_bot.sendMessage (chat_id, str("Hi! Which one do you want? choose from the below keyboard buttons."), reply_markup=markup) telegram_bot.sendMessage(chat_id, str(now.hour)+str(":")+str(now.minute)) elif command == 'NewKey': markup = ReplyKeyboardMarkup(keyboard=[['More', KeyboardButton(text='More2')],["More3", "More5"]])) elif command == 'Time': telegram_bot.sendMessage(chat_id, str(now.hour)+str(":")+str(now.minute)) elif command == '/file': telegram_bot.sendDocument(chat_id, document=open('/home/pi/Aisha.py')) elif command == '/audio': telegram_bot.sendAudio(chat_id, audio=open('/home/pi/test.mp3')) telegram_bot = telepot.Bot('MY-BOT-TOKEN') print((telegram_bot.getMe())) MessageLoop(telegram_bot, action).run_as_thread() print('Up and Running....') while 1: time.sleep(10) `
downvote count: 1
type: Question
has title: Change custom keyboard by sending commands on telepot Telegram Bot
has comment: http://stackoverflow.com/comment/91304915
favorite count: 0
tagged with: telegram-bot
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91315969
type: UnansweredQuestion
tagged with: python
answer count: 0
upvote count: 2
score: 1

http://stackoverflow.com/q/52226280
has title: How to return a python datetime format string?
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: datetime
upvote count: 1
tagged with: python
answer count: 0
tagged with: python-datetime
has body: I would like to have the following funcitonality some_function('2018-06-05 00:00:00') and it should return "%Y-%m-%d %H:%M:%S" which is the format of the input date. Is there a function in dateutils.parser or in some other library that I can use?
linked to: http://stackoverflow.com/q/44321601
type: Question
duplicate of: http://stackoverflow.com/q/44321601
tagged with: datetime-format

http://stackoverflow.com/q/52252580
score: 0
has comment: http://stackoverflow.com/comment/91456780
tagged with: python
has body: I'm fairly new to AWS and for the past week, been following all the helpful documentation on the site. I am currently stuck on bring unable to pull the External Image Id data from a Reko collection after a 'search face by image', I just need to be able to put that data into a variable or to print it, does anybody know how I could do that? Basically, this is my code: import boto3 if name == "main": bucket = 'bucketname' collectionId = 'collectionname' fileName = 'test.jpg' threshold = 90 maxFaces = 2 admin = 'test' targetFile = "%sTarget.jpg" % admin imageTarget = open(targetFile, 'rb') client = boto3.client('rekognition') response = client.search_faces_by_image(CollectionId=collectionId, Image={'Bytes': imageTarget.read()}, FaceMatchThreshold=threshold, MaxFaces=maxFaces) faceMatches = response['FaceMatches'] print ('Matching faces') for match in faceMatches: print ('FaceId:' + match['Face']['FaceId']) print ('Similarity: ' + "{:.2f}".format(match['Similarity']) + "%") at the end of it, I receive: Matching faces FaceId:8081ad90-b3bf-47e0-9745-dfb5a530a1a7 Similarity: 96.12% Process finished with exit code 0 What I need is the External Image Id instead of the FaceId. Thanks!
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91455989
has title: Pulling the 'ExternalImageId' data when running search_faces_by_image
type: Question
has comment: http://stackoverflow.com/comment/91483753
has comment: http://stackoverflow.com/comment/91456586
tagged with: amazon-web-services

http://stackoverflow.com/q/52118525
favorite count: 0
accepted answer: http://stackoverflow.com/a/52121124
has body: I am trying to use keras to fit a CNN model to classify images. The data set has much more images form certain classes, so its unbalanced. I read different thing on how to weight the loss to account for this in Keras, e.g.: https://datascience.stackexchange.com/questions/13490/how-to-set-class-weights-for-imbalanced-classes-in-keras, which is nicely explained. But, its always explaining for the fit() function, not the fit_generator() one. Indeed, in the fit_generator() function we dont have the 'class_weights' parameter, but instead we have 'weighted_metrics', which I dont understand its description: "weighted_metrics: List of metrics to be evaluated and weighted by sample_weight or class_weight during training and testing." How can I pass from 'class_weights' to 'weighted_metrics'? Would any one have a simple example?
tagged with: python
score: 11
upvote count: 11
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/52121124
has title: How to weight classes using fit_generator() in Keras?
has comment: http://stackoverflow.com/comment/99140456
answer count: 1
downvote count: 0
tagged with: keras

http-headers
tags question: http://stackoverflow.com/q/52156583
tags question: http://stackoverflow.com/q/52183664
type: Tag
tag name: http-headers

http://stackoverflow.com/comment/91200873
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52124719
has text: return render(request, 'exampapersNew/exampaper.html', {"paperS": paperS})
score: 0

http://stackoverflow.com/comment/91332227
has text: I'm not sure what your problem is, but bcrypt doesn't _encrypt_ passwords. Passwords are properly stored _hashed_, which is an important distinction. Encrypted data can be decrypted; cryptographic hashes are designed to be irreversible. Also, the size of the output from these hashes is predictable and the same for the empty string and the entire text of _War and Peace_, meaning it's easy to store hashes of arbitrarily large passwords in a database column with a fixed size.
comment on: http://stackoverflow.com/q/52190989
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52198795
tagged with: tkinter
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/52202252
score: -1
type: Question
upvote count: 0
answer count: 1
has body: I use bind() to set actions for keys, but when I want to add action to number keys on Numpad it doesn't work. How should the code look if I want it to work?
has title: How do I recognize key on numpad is being clicked?
has comment: http://stackoverflow.com/comment/91350881
has comment: http://stackoverflow.com/comment/91452438
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/91283553
type: Comment
has text: mydf = mydf.loc[:, mydf.columns.contains('|'.join(L))] fails because a boolean is returned
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52166878

http://stackoverflow.com/comment/91253487
comment on: http://stackoverflow.com/q/52150441
has text: Possible duplicate of [Capturing http status codes with scrapy spider](https://stackoverflow.com/questions/10982417/capturing-http-status-codes-with-scrapy-spider)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91335801
type: Comment
comment on: http://stackoverflow.com/a/52192317
has text: Update: ref = web3.personal.Personal('web3') I need to add 'web3' as an argument, however I can't call functions from this class
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91176169
comment on: http://stackoverflow.com/q/52112774
score: 0
has text: @fedorqui yes.I want something like that
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92885412
type: AnswerComment
comment on: http://stackoverflow.com/a/52272825
score: 0
type: Comment
has text: Sorry but that’s not help , it’s working for free. Sorry me.

http://stackoverflow.com/a/52211909
has comment: http://stackoverflow.com/comment/91395142
has comment: http://stackoverflow.com/comment/91373922
type: Answer
has comment: http://stackoverflow.com/comment/91374313
answers question: http://stackoverflow.com/q/52211840
score: 2
has body: Use duplicated df.assign(Flag=1 - df.duplicated(['id', 'quarter', 'lot'], keep='last')) id quarter ordernumber lot Flag 0 A 2018Q1 orderA lot1 0 1 A 2018Q1 orderB lot1 1 2 A 2018Q1 orderB lot2 1 Same thing df.assign(**{'Last Order': 1 - df.duplicated(['id', 'quarter', 'lot'], keep='last')}) id quarter ordernumber lot Last Order 0 A 2018Q1 orderA lot1 0 1 A 2018Q1 orderB lot1 1 2 A 2018Q1 orderB lot2 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91374616
has comment: http://stackoverflow.com/comment/91373253
has comment: http://stackoverflow.com/comment/91374283
upvote count: 2

http://stackoverflow.com/a/52205831
type: Answer
accepted answer of: http://stackoverflow.com/q/52205416
upvote count: 5
answers question: http://stackoverflow.com/q/52205416
score: 5
type: AcceptedAnswer
has body: Unfortunately cbar_kws doesn't accept the labelpad argument. Therefore one way to add some padding to the labels will be to access the colorbar after it has been drawn. You can use ax.collections[0].colorbar to get access to the matplotlib.colorbar.Colorbar object. This then lets you use the colobar as you normally would with matplotlib. So, you can use set_label() to set your colorbars label, and you can use the labelpad= argument: import seaborn as sns uniform_data = np.random.rand(10, 12) # random data ax = sns.heatmap(uniform_data) cbar = ax.collections[0].colorbar cbar.set_label('Label for colour bar axis', labelpad=40) plt.show()
downvote count: 0

http://stackoverflow.com/a/52239555
type: Answer
accepted answer of: http://stackoverflow.com/q/52239034
has body: Google Cloud Functions uses Flask under the hood to serve your endpoint, so you can just return a redirect at the end: from flask import redirect def test(request): return redirect('https://google.com')
answers question: http://stackoverflow.com/q/52239034
upvote count: 5
score: 5
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91366697
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52208472
type: Comment
has text: Initially my intuition took me to hierarchical clustering, but I'm not sure how to handle it if the dataset does not include starting coordinates, more specifically, the participants only transmit their location long after the departure (hence I'm missing the trees' root)

http://stackoverflow.com/a/52226333
type: Answer
has body: Answered here: https://security.stackexchange.com/questions/193036/analyzing-apache-log-with-snort Basically, instead of crafting my own packets, it is better to use the requests library and send the requests directly.
answers question: http://stackoverflow.com/q/52136724
accepted answer of: http://stackoverflow.com/q/52136724
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91209973
type: Comment
has text: Perfect! Exactly what I needed.
comment on: http://stackoverflow.com/a/52129675
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91333543
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52190649
has text: Are you trying to aggregate the `queueing_time` and `queueing_length` for all `lanes` per `timestep`? So for `timestep=120`, are you wanting `queueing_time=300.00` and `queueing_length=425.63`?
score: 0

http://stackoverflow.com/q/52213098
has title: Trying to use stockstats to cal rsi, getting error "TypeError: list indices must be integers or slices, not str"
has comment: http://stackoverflow.com/comment/91378293
has body: I'm tryng to cal the rsi of a set of test data. This is what I do create a data frame of the test data df = pd.DataFrame(data,columns=['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'adj close']) make the data frame into a webstate frame stock_df = Sdf.retype(df) cal the rsdata['rsi']=stock_df['rsi_14'] complete error message and code "C:\Users\tpottel\programming\java\eclipse projects\BBitBotCoinUsing2\pythonpro\venv\Scripts\python.exe" "C:/Users/tpottel/programming/java/eclipse projects/BBitBotCoinUsing2/pythonpro/webstats/webstats.py" C:\Users\tpottel\programming\java\eclipse projects\BBitBotCoinUsing2\pythonpro\venv\lib\site-packages\pandas\core\indexing.py:189: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy self._setitem_with_indexer(indexer, value) (sample code on internet http://pythondata.com/stockstats-python-module-various-stock-market-statistics-indicators/ ) CODE: import pandas as pd import stockstats as st from stockstats import StockDataFrame as Sdf #from pandas.io import data, wb # becomes #from pandas_datareader import data, wb data=[[567, 700, 650, 710, 760, 1, 670]] data.append([567, 700, 650, 710, 760, 1, 670]) data.append([567, 700, 650, 710, 760, 1, 670]) data.append([567, 700, 650, 710, 760, 1, 670]) data.append([567, 700, 650, 710, 760, 1, 670]) data.append([567, 700, 650, 710, 760, 1, 670]) data.append([567, 700, 650, 710, 760, 1, 670]) data.append([567, 700, 650, 710, 760, 1, 670]) data.append([567, 700, 650, 710, 760, 1, 670]) data.append([567, 700, 650, 710, 760, 1, 670]) data.append([567, 700, 650, 710, 760, 1, 670]) data.append([567, 700, 650, 710, 760, 1, 670]) data.append([567, 700, 650, 710, 760, 1, 670]) data.append([567, 700, 650, 710, 760, 1, 670]) data.append([567, 700, 650, 710, 760, 1, 670]) data.append([567, 700, 650, 710, 760, 1, 670]) data.append([567, 700, 650…
score: 0
has comment: http://stackoverflow.com/comment/91378235
has comment: http://stackoverflow.com/comment/91376038
has comment: http://stackoverflow.com/comment/91376017
type: UnansweredQuestion
tagged with: python
answer count: 0
type: Question

http://stackoverflow.com/q/52201340
has title: Format a string to have n spaces only between words in python
answer count: 4
type: AnsweredQuestion
tagged with: whitespace
tagged with: adjustment
accepted answer: http://stackoverflow.com/a/52201388
type: Question
has body: I am working with strings that have different number of spaces between the non-whitespace characters. The problem is that this strings form a category, and they have to be equal. I would like to format them to have exactly the same number of spaces between the non-whitespace characters, f.e. 1, but this could be generalised to insert more spaces if possible. And there should be no spaces at the beginning and end. Examples with n=1: 'a b b' =&gt; 'a b c' ' a b c ' =&gt; 'a b c'
score: 4
has answer: http://stackoverflow.com/a/52201411
upvote count: 4
downvote count: 0
tagged with: string
has answer: http://stackoverflow.com/a/52201388
favorite count: 0
possible better answer: http://stackoverflow.com/a/52201533
has answer: http://stackoverflow.com/a/52201533
has answer: http://stackoverflow.com/a/52201969
tagged with: python

http://stackoverflow.com/q/52164834
has answer: http://stackoverflow.com/a/52164979
favorite count: 0
has comment: http://stackoverflow.com/comment/91279144
has comment: http://stackoverflow.com/comment/91279110
upvote count: 2
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/91279531
type: AnsweredQuestion
has body: I would like to replace a number with one of the following formats: 200, 200.99, 300,555 unless its between the &lt;> tokens. for example I would like to skip this: &lt;200> This is what I came up with: (?&lt;!&lt;)([\d,|.]+(?:\.\d{2})?)(?!&gt;) from testing it in regex101, I'm skipping only the first and last digit after &lt; and before >. I'm iterating over a text file line by line and I would like to replace all occurrences of the following examples: 200 200.00 200.000 with a token, but if the line already have a number between &lt;> then skip that line, to clarify, I would like to skip the following value in my line and not replaced by the regex: &lt;300&gt; this is the code I use: current_line = re.sub("(?&lt;!&lt;)([\d,|.]+(?:\.\d{2})?)(?!&gt;)", ' &lt;num&gt; ', current_line) could you please assist?
score: 1
linked to: http://stackoverflow.com/q/45189706
tagged with: regex-negation
has comment: http://stackoverflow.com/comment/91279305
accepted answer: http://stackoverflow.com/a/52164979
has comment: http://stackoverflow.com/comment/91279889
downvote count: 1
type: Question
has title: python - regex to capture a number with comma or a dot unless between tokens
has comment: http://stackoverflow.com/comment/91279179
answer count: 1

monkey
tag name: monkey
tags question: http://stackoverflow.com/q/52175281
type: Tag

http://stackoverflow.com/comment/91346131
has text: Note that `"detect" in "undetectable"` is `True`, which might or might not be what you want, especially since you mention "word".
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52198372

http://stackoverflow.com/a/52147284
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52144383
has comment: http://stackoverflow.com/comment/100146239
answers question: http://stackoverflow.com/q/52144383
score: 15
upvote count: 15
has body: AFAICT, this is not possible with Click. The docs state that: Click strictly separates parameters between commands and subcommands. What this means is that options and arguments for a specific command have to be specified after the command name itself, but before any other command names. A possible workaround is writing a common_options decorator. The following example is using the fact that click.option is a function that returns a decorator function which expects to be applied in series. IOW, the following: @click.option("-a") @click.option("-b") def hello(a, b): pass is equivalent to the following: def hello(a, b): pass hello = click.option("-a")(click.option("-b")(hello)) The drawback is that you need to have the common argument set on all your subcommands. This can be resolved through **kwargs, which collects keyword arguments as a dict. (Alternately, you could write a more advanced decorator that would feed the arguments into the context or something like that, but my simple attempt didn't work and i'm not ready to try more advanced approaches. I might edit the answer later and add them.) With that, we can make a program: import click import functools @click.group() def cli(): pass def common_options(f): options = [ click.option("-a", is_flag=True), click.option("-b", is_flag=True), ] return functools.reduce(lambda x, opt: opt(x), options, f) @cli.command() @common_options def hello(**kwargs): print(kwargs) # to get the value of b: print(kwargs["b"]) @cli.command() @common_options @click.option("-c", "--citrus") def world(citrus, a, **kwargs): print("citrus is", citrus) if a: print(kwargs) else: print("a was not passed") if __name__ == "__main__": cli()

http://stackoverflow.com/comment/91284001
type: Comment
has text: Sorry for the last comment, i deleted it, I take my words back, I was looking at wrong value. BTW, the issue is solved ,thanks
comment on: http://stackoverflow.com/q/52159364
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91294712
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52171597
has text: The python `if` doesn't work with arrays. It branches only once, without any sort of iteration.

http://stackoverflow.com/a/63894470
downvote count: 0
answers question: http://stackoverflow.com/q/52118969
type: Answer
score: 3
upvote count: 3
has body: Try doing conda install -c anaconda pip pip install sklearn

http://stackoverflow.com/a/52190008
score: -1
has body: simple_save(session, export_dir, inputs={"inputs" : inputs}, outputs={"predictor" : predictor})
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/91375583
answers question: http://stackoverflow.com/q/52175147
type: Answer
accepted answer of: http://stackoverflow.com/q/52175147
upvote count: 0
has comment: http://stackoverflow.com/comment/91375619
has comment: http://stackoverflow.com/comment/91339818

http://stackoverflow.com/q/52130358
has body: I have written a script which is opening multiple tabs one by one and taking data from there. Now I am able to get data from the page but when writing in CSV file getting data as per below. Bedrooms Bathrooms Super area Floor Status 3 See Dimensions 3 See Dimensions 2100 7 (Out of 23 Floors) 3 See Dimensions Bedrooms Bathrooms Super area Floor Status 3 See Dimensions 3 See Dimensions 2100 7 (Out of 23 Floors) 3 See Dimensions Bedrooms Bathrooms Super area Floor Status 1 1 520 4 (Out of 40 Floors) 1 Bedrooms Bathrooms Super area Floor Status 3 See Dimensions 3 See Dimensions 2100 7 (Out of 23 Floors) 3 See Dimensions Bedrooms Bathrooms Super area Floor Status 1 1 520 4 (Out of 40 Floors) 1 In the Status column i am getting wrong value. I have tried: # Go through of them and click on each. for unique_link in my_needed_links: unique_link.click() time.sleep(2) driver.switch_to_window(driver.window_handles[1]) def get_elements_by_xpath(driver, xpath): return [entry.text for entry in driver.find_elements_by_xpath(xpath)] search_entries = [ ("Bedrooms", "//div[@class='seeBedRoomDimen']"), ("Bathrooms", "//div[@class='p_value']"), ("Super area", "//span[@id='coveredAreaDisplay']"), ("Floor", "//div[@class='p_value truncated']"), ("Lift", "//div[@class='p_value']")] with open('textfile.csv', 'a+') as f_output: csv_output = csv.writer(f_output) # Write header csv_output.writerow([name for name, xpath in search_entries]) entries = [] for name, xpath in search_entries: entries.append(get_elements_by_xpath(driver, xpath)) csv_output.writerows(zip(*entries)) get_elements_by_xpath(driver, xpath) Edit Entries: as list [['3 See Dimensions'], ['3 See Dimensions', '4', '3', '1', '2100 sqft', '1400 sqft', '33%', 'Avenue 54', 'Under Construction', "Dec, '20", 'New Property', '₹ 7.90 Cr ₹ 39,50,000 Approx. Registration Charges ₹ 15 Per sq. Unit Monthly\nSee Other Charges', "Santacruz West, Mumbai., Santacruz West, Mumbai - Western Suburbs, Maharashtra What's Nearby", "Next To St Teresa's…
tagged with: python
has comment: http://stackoverflow.com/comment/91211386
tagged with: python-3.x
has title: How to save data from website by using python + selenium
type: UnansweredQuestion
tagged with: selenium
has answer: http://stackoverflow.com/a/52134264
has answer: http://stackoverflow.com/a/52132145
type: Question
has comment: http://stackoverflow.com/comment/91211182
score: 0
has comment: http://stackoverflow.com/comment/91211466
answer count: 2
has comment: http://stackoverflow.com/comment/91211632
tagged with: pandas

http://stackoverflow.com/q/52194746
has answer: http://stackoverflow.com/a/52194880
score: 0
answer count: 2
tagged with: utf-8
tagged with: string
linked to: http://stackoverflow.com/q/3828723
tagged with: python
has body: I just found out that for some reason when copying using pyperclip a string that was decoded (using utf-8), it will raise an error. import pyperclip with open('chat.txt' 'r') as f: string = f.read() # the string is encoded in utf-8 in order to be able to write down `'`, `emoji` and other special signs or symbol pyperclip.copy(string.decode('utf-8')) It will raise this error: PyperclipException: only str, int, float, and bool values can be copied to the clipboard, not unicode I found a roundabout way to solve it by using str() but then found out that it won't work since str() does not work if there are some character like '. EDIT: Alternative solution An alternative solution except for the solution that I accepted would be degrade the pyperclip from the newest version (right now its 1.6.4) to a lower version (1.6.1 worked for me).
accepted answer: http://stackoverflow.com/a/52194880
possible better answer: http://stackoverflow.com/a/52474929
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52474929
type: Question
tagged with: decode
tagged with: pyperclip
has title: Python pyperclip cannot copy decoded

http://stackoverflow.com/comment/91203085
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52126227
has text: Can you post the full code?

http://stackoverflow.com/comment/91487549
score: 0
has text: @NiteyaShah sub_group is the RAW formation for variable i.e. GDP after transformation will be GDP_M3, GDP_M6 and so on.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52259900

http://stackoverflow.com/comment/91409420
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52229799
score: 0
has text: You are correct as written the last two isinstance checks work. I goofed, they didn't work with my attempt locally with changing __new__ behavior.

http://stackoverflow.com/comment/91322711
score: 0
has text: This is a statement, not a question. What do you want help with?
type: QuestionComment
comment on: http://stackoverflow.com/q/52186426
type: Comment

http://stackoverflow.com/q/52152286
has body: I have two INI files a , b like below File a.ini ########################################## ## Application ## Var Values Comment ## -------- ------------------ ----------------- ------------------------------ ## Application 1,2 Each server is attached to a valid point ## t2 ## 1 = dummy, 2 = hds app=3 sv=2 type=ort serv=t2 val=d7 File b.ini ########################################## ## Application ## Var Values Comment ## -------- ------------------ -------------------- --------------------------- ## Application 1 Each server is attached to a valid point ## t2 ## 1 = dummy, app=3 sv=2 type=ort3 serv=t22 stage=5 I want to compare the un commented keys of a.ini with un commented keys of b.ini. So If keys are matched then I want copy the values of matched keys of a.ini to b.ini without disturbing the comments because this is well structured file. If the new keys are present in a.ini then that key, values blindly copy to b.ini. and when we write the matched keys of values to b.ini the position of keys should not change. so the final output will be like below ########################################## ## Application ## Var Values Comment ## -------- ------------------ -------------------- --------------------------- ## Application 1 Each server is attached to a valid point ## t2 ## 1 = dummy, app=3 sv=2 type=ort serv=t2 stage=5 val=d7 I have followed the below way but it worked until read data of two INI files and print matched dictionary key-pairs. separator = "=" keys = {} with open('test.ini') as f: for line in f: if separator in line: name, value = line.split(separator, 1) keys[name.strip()] = value.strip() separator1 = "=" keys1 = {} with open('temp.ini') as f1: for line in f1: if separator1 in line: name, value = line.split(separator1, 1) keys1[name.strip()] = value.strip() for key, value in keys.viewitems() &amp; keys1.viewitems(): print(key, value)
score: 1
has comment: http://stackoverflow.com/comment/91255169
type: Question
answer count: 2
has title: Compare keys of two ini files and copy the values of matched key's to second ini file in python
has answer: http://stackoverflow.com/a/52152443
downvote count: 0
tagged with: ini
tagged with: copy
has answer: http://stackoverflow.com/a/52152373
tagged with: compare
tagged with: python
favorite count: 0
type: UnansweredQuestion
tagged with: file
upvote count: 1

http://stackoverflow.com/q/52244317
score: 1
has comment: http://stackoverflow.com/comment/91437049
has title: "ValueError: could not convert string to float" when using RandomForestClassifier
has comment: http://stackoverflow.com/comment/91437348
type: Question
has comment: http://stackoverflow.com/comment/91437530
tagged with: scikit-learn
has body: I am attempting to use the RandomForestClassifier of the Scikit Learn library. I have my data in a dataframe which I am preprocessing using LabelEncoder like so: from sklearn import preprocessing from sklearn.preprocessing import LabelEncoder for column in df.columns: if df[column].dtype == type(object): le = LabelEncoder() df[column] = le.fit_transform(df[column]) I then create my training and test sets like so: # Labels are the values we want to predict labels = np.array(df['hta_tota']) # Remove the labels from the features # axis 1 refers to the columns df= df.drop('hta_tota', axis = 1) # Saving feature names for later use feature_list = list(df.columns) # Convert to numpy array dfNpy = np.array(df) train_features, test_features, train_labels, test_labels = train_test_split(dfNpy, labels, test_size = 0.25, random_state = 42) Now I am trying to use the RandomForestClassifier to fit my training set... rf = RandomForestClassifier(n_jobs=2, random_state=0) rf.fit(train_features, train_labels); ... but I get the following error: ValueError: could not convert string to float: masculino masculino is one of the string values under one of my columns in the dataframe. However I used LabelEncoder to encode this column! What's going on? Any ideas? Thanks in advance. UPDATE: Some more information regarding the dataframe, `df'; it is created and simplified as so: df = pd.read_stata('health_data/Hipertension_entrega.dta') cols_wanted = ['folio', 'desc_ent', 'desc_mun', 'sexo', 'edad', 'hta_tota'] df = df[cols_wanted] df = df[pd.notnull(df['hta_tota'])] df.set_index('folio') Then once I do the preprocess via LabelEncoder (as shown above), the df still returns the following:
has comment: http://stackoverflow.com/comment/91440582
has comment: http://stackoverflow.com/comment/91439929
downvote count: 0
has comment: http://stackoverflow.com/comment/91437924
has comment: http://stackoverflow.com/comment/91440277
favorite count: 0
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 1
tagged with: python
answer count: 0

http://stackoverflow.com/comment/91375801
type: Comment
comment on: http://stackoverflow.com/a/52213127
score: 0
type: AnswerComment
has text: @E235 Edited mine

http://stackoverflow.com/q/52196040
score: 0
answer count: 1
type: UnansweredQuestion
has body: I'm scraping a website which requires referer. I set it like this. DEFAULT_REQUEST_HEADERS = { 'Referer': 'http://www.referer.com' } When I tried scrapy shell url in the project folder (the one has scrapy.cfg), which means it's using the same settings in the settings.py file, I can see the referer is in the request, but I got a 403 response. [scrapy.core.engine] DEBUG: Crawled (403) https://my_url.com (referer: http://www.referer.com) However, without changing any thing, scrapy crawl my_spider has no issue. [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (302) to https://redirected_my_url.com> from https://my_url.com> I'm also scrapyrt, which has the same issue as scrapy shell.
tagged with: python
has comment: http://stackoverflow.com/comment/91376389
has comment: http://stackoverflow.com/comment/91355246
has answer: http://stackoverflow.com/a/53215352
tagged with: scrapy
type: Question
has title: scrapy shell and scrapyrt got 403 but scrapy crawl works

http://stackoverflow.com/q/52254678
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52254789
type: Question
has answer: http://stackoverflow.com/a/52254789
tagged with: numpy
score: 0
tagged with: array-broadcasting
has title: Numpy: Find minimum of an expression over several parameters
linked to: http://stackoverflow.com/q/52242832
answer count: 1
has body: Is there a numpy way to get the minimum of an expression over many parameters without explicit loops? #Randomly initialize samples SAMPLES_NUM = 200 L = np.random.rand(SAMPLES_NUM) q1 = np.random.rand(SAMPLES_NUM) q2 = np.random.rand(SAMPLES_NUM) #Make the data X = np.arange(0,1,0.01) Y = np.arange(0,1,0.01) X,Y = np.meshgrid(X,Y) #Calculate Z at (x,y) as the minimum of L[i]+x(q1[i]+q2[i]) + q2[i]y #over all i I tried broadcasting: Z = np.min(L + X*(q1+q2) +Y*q2) But doesn't work because of broadcasting issues. Any ideas, or would I have to explicitly loop over all i?
tagged with: python

http://stackoverflow.com/comment/91234300
type: QuestionComment
comment on: http://stackoverflow.com/q/52141951
has text: @PeterBarrettBryan that did the trick! Turns out tensorflow is referencing numpy arrays and not python's built in arrays. If you post that comment as the answer I'll mark it correct.
score: 0
type: Comment

http://stackoverflow.com/a/52249404
type: AcceptedAnswer
type: Answer
has body: As per the documentation you can't upload an image like you would from a local source so you can either Upload from a local source using send_file await client.send_file(message.channel, 'my_image.png') or Embed the URL import discord embed = discord.Embed() embed.set_image(url = random.choice([jessie1,snowy])) await client.send_message(message.channel,embed=embed)
accepted answer of: http://stackoverflow.com/q/52249107
answers question: http://stackoverflow.com/q/52249107
score: 0

http://stackoverflow.com/q/52248806
tagged with: python
has title: Need Help Using If Statements and Lists
has body: I am new to python and am having a hard time figuring out where my issue begins, I believe that I am mis-defining the variable "primes" in my first if statement. I appreciate the help. The paragraph below is of the task that I am trying to accomplish. Take a number from the user. Respond with the word "Unitary" if the number is 1, with the word "Prime" if the number is in the list and with the word "Composite" otherwise. primes = [2,3,5,7,11,13,17,19,23,29, 31,37,41,43,47,53,59,61,67,71, 73,79,83,89,97,101,103,107,109,113, 127,131,137,139,149,151,157,163,167,173, 179,181,191,193,197,199,211,223,227,229, 233,239,241,251,257,263,269,271,277,281, 283,293,307,311,313,317,331,337,347,349, 353,359,367,373,379,383,389,397,401,409, 419,421,431,433,439,443,449,457,461,463, 67,479,487,491,499,503,509,521,523,541, 547,557,563,569,571,577,587,593,599,601, 607,613,617,619,631,641,643,647,653,659, 661,673,677,683,691,701,709,719,727,733, 739,743,751,757,761,769,773,787,797,809, 811,821,823,827,829,839,853,857,859,863, 877,881,883,887,907,911,919,929,937,941, 947,953,967,971,977,983,991,997,1009,1013, 1019,1021,1031,1033,1039,1049,1051,1061,1063,1069, 1087,1091,1093,1097,1103,1109,1117,1123,1129,1151, 1153,1163,1171,1181,1187,1193,1201,1213,1217,1223, 1229,1231,1237,1249,1259,1277,1279,1283,1289,1291, 1297,1301,1303,1307,1319,1321,1327,1361,1367,1373, 1381,1399,1409,1423,1427,1429,1433,1439,1447,1451, 1453,1459,1471,1481,1483,1487,1489,1493,1499,1511, 1523,1531,1543,1549,1553,1559,1567,1571,1579,1583, 1597,1601,1607,1609,1613,1619,1621,1627,1637,1657, 1663,1667,1669,1693,1697,1699,1709,1721,1723,1733, 1741,1747,1753,1759,1777,1783,1787,1789,1801,1811, 1823,1831,1847,1861,1867,1871,1873,1877,1879,1889, 1901,1907,1913,1931,1933,1949,1951,1973,1979,1987, 1993,1997,1999,2003,2011,2017,2027,2029,2039,2053, 2063,2069,2081,2083,2087,2089,2099,2111,2113,2129, 2131,2137,2141,2143,2153,2161,2179,2203,2207,2213, 2221,2237,2239,2243,2251,2267,2269,2273,2281,2287, 293,2297,2309,2311,2333,2339,…
upvote count: 1
linked to: http://stackoverflow.com/q/11251709
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91445692
duplicate of: http://stackoverflow.com/q/11251709
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91445688
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52248828
has comment: http://stackoverflow.com/comment/91445658
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52248835
has answer: http://stackoverflow.com/a/52248829

http://stackoverflow.com/a/52150900
score: 3
accepted answer of: http://stackoverflow.com/q/52150653
has comment: http://stackoverflow.com/comment/91252662
has comment: http://stackoverflow.com/comment/91252496
has comment: http://stackoverflow.com/comment/91272758
answers question: http://stackoverflow.com/q/52150653
upvote count: 3
has comment: http://stackoverflow.com/comment/91252454
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91272986
has body: Python's closures are late binding. This means that the values of variables used in closures are looked up at the time the function is called. To avoid the late binding effect you can use a lambda with a default arg: index = 1 test = lambda t, index=index: t[index]+1 # binds index at definition time index = 0 print(test([5, 0])) # 1
has comment: http://stackoverflow.com/comment/91264179
type: Answer
downvote count: 0

http://stackoverflow.com/comment/91412626
score: 2
comment on: http://stackoverflow.com/a/52222123
type: AnswerComment
type: Comment
has text: use `df.loc[df['A'].str.contains('|'.join(selected_words)),'A'].value_counts()` and tell me or post a simple dataframe with 5 rows and post its expected output df

http://stackoverflow.com/a/52209303
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52209231
has body: It's doing exactly what you told it to do: update the one and only Cube object in the game, and then redraw the screen and that one object. If you want multiple cubes, you have to create each one. Perhaps something like this: cube_list = [] # List of all cubes while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.MOUSEBUTTONDOWN: # Make a new cube cube = Cube() cube.update() cube_list.append(cube) drawing_cube = True screen.fill((0, 255, 0)) if drawing_cube: #New cube made; draw them all. for cube in cube_list: cube.draw() pygame.display.flip() Now, as an exercise for the student, can you simplify this so that it merely adds the most recent cube to the existing screen, instead of redrawing the entire game area for each new cube?
answers question: http://stackoverflow.com/q/52209231

http://stackoverflow.com/a/52120857
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52120258
answers question: http://stackoverflow.com/q/52120258
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I have improved your code. You have placed the screen update (drawing the screen) portion in the events loop whereas it should be in the while loop. The code I have mode is a bit complex but works as expected. Why it is complex? When the key is held down, then the events list is empty (you can print the events). I have also made the block not to go out of the screen. The speed of the block was high so I decreased it to 10. import pygame import random pygame.init() #Colors white = 255, 255, 255 black = 0, 0, 0 back_color = 48, 255, 124 light_color = 34, 155, 78 #Display W/H display_width = 800 display_height = 600 #X/Y x_axis = 400 y_axis = 580 global x_int Block_size = 20 x_int = 0 y_int = 0 ON = True Window = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('Game') global topass_a,topass_d x_int,topass_a,topass_d = 0,0,0 #On Loop while ON: #Screen Event events = pygame.event.get() def on_a_press(): global topass_a,x_int x_int = -10 topass_a = 1 def on_d_press(): global topass_d,x_int x_int = 10 topass_d = 1 if len(events) == 0: if topass_a == 1:on_a_press() if topass_d == 1:on_d_press() for Screen in events: if Screen.type == pygame.QUIT: pygame.quit() exit() if Screen.type == pygame.KEYDOWN: if Screen.key == pygame.K_q: pygame.quit() exit() if Screen.key == pygame.K_1: pygame.display.set_mode((display_width, display_height),pygame.FULLSCREEN) if Screen.key == pygame.K_2: pygame.display.set_mode((display_width, display_height)) if Screen.key == pygame.K_d or topass_d == 1: on_d_press() if Screen.key == pygame.K_a or topass_a == 1: on_a_press() if Screen.type == pygame.KEYUP: if Screen.key == pygame.K_d or Screen.key == pygame.K_a: x_int = 0 topass_a = 0 topass_d = 0 x_axis += x_int x_int = 0 if x_axis &lt; 0:x_axis=0 elif x_axis &gt;= display_width-Block_size:x_axis = display_width-Block_size Window.fill((back_color)) Player = pygame.draw.rect(Window, light_color, [x_axis, y_axis, Block_size, Block_size]) pygame.display.update() Y…
score: 2

http://stackoverflow.com/q/52243693
type: Question
accepted answer: http://stackoverflow.com/a/52244459
tagged with: dataframe
tagged with: pandas
answer count: 1
has title: Generating future dataframe with annual growth rate
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
has body: I am trying to generate annual data for a certain product when I have data for the base year and growth rate. In the toy example, each product has different annual growth rate in efficiency by its 'color', and I want to generate yearly data until 2030. Therefore, I have base year data (base_year) as follows: year color shape efficiency 0 2018 red circle 50 1 2018 red square 30 2 2018 blue circle 100 3 2018 blue square 60 And each type of product's growth rate (growthrate) as: color rate 0 red 30 1 blue 20 Results I desire is: year color shape efficiency 0 2018 red circle 50 1 2018 red square 30 2 2018 blue circle 100 3 2018 blue square 60 4 2019 red circle 65 5 2019 red square 39 6 2019 blue circle 120 7 2019 blue square 72 8 2020 red circle 84.5 ... (until 2030) The data used in the toy code is.. base_year = pd.DataFrame(data = {'year': [2018,2018,2018,2018], 'color': ['red', 'red', 'blue', 'blue'], 'shape' : ['circle', 'square', 'circle', 'square'], 'efficiency' : [50, 30, 100, 60]}, columns = ['year', 'color', 'shape', 'efficiency']) growthrate = pd.DataFrame(data = {'color': ['red', 'blue'], 'rate' : [30, 20]}, columns = ['color', 'rate']) I've been trying some approach using .loc, but it seems such approach is quite inefficient. Any suggestions or hints would be appreciated. Thank you in advance!
upvote count: 1
has answer: http://stackoverflow.com/a/52244459

http://stackoverflow.com/q/52137205
score: 0
possible better answer: http://stackoverflow.com/a/52137553
tagged with: file-handling
has answer: http://stackoverflow.com/a/52137553
has body: Consider a case where you open a file using the with statement and call it file_handle. Then open a new file from within the with block and assign it to previous file_handle as follows: with open('some/file') as file_handle: # some codes file_handle = open('another/file') # more codes My question: What would happen in this case? In fact, I want to know the answer of following questions: What would happen to the first file_handle? Would it be closed after assignment or it remains open? If after the assignment, an exception happened in the with block, would the newly opened file be closed or not? Once the with block is finished, does it close the new file_handle?
tagged with: python
type: AnsweredQuestion
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91224040
has title: File-handle assignment
has answer: http://stackoverflow.com/a/52137305
accepted answer: http://stackoverflow.com/a/52137305
has comment: http://stackoverflow.com/comment/91224213

http://stackoverflow.com/comment/91433471
score: 0
type: Comment
type: AnswerComment
has text: Just use `extract()` instead
comment on: http://stackoverflow.com/a/52240690

http://stackoverflow.com/q/52268262
answer count: 3
tagged with: iteritems
downvote count: 0
tagged with: python-2.x
favorite count: 0
has answer: http://stackoverflow.com/a/52268399
tagged with: python-internals
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has body: Is it guaranteed that python 2.X's built-in methods dict.items() and dict.iteritems() will always return items in the same order? Or are these methods non-deterministic?
has answer: http://stackoverflow.com/a/60011959
has answer: http://stackoverflow.com/a/52268293
type: Question
has comment: http://stackoverflow.com/comment/91484728
score: 4
has title: Does python's dict.items() always return the same order?
upvote count: 4
linked to: http://stackoverflow.com/q/835092

http://stackoverflow.com/comment/91214460
comment on: http://stackoverflow.com/q/52131978
has text: @zvone I don't think so. I looked at that, and it creates tuples where each element position (index) within the tuple has a name. I need a `__name__` for the tuple object itself.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91474664
type: QuestionComment
comment on: http://stackoverflow.com/q/52263110
type: Comment
has text: 42 was a typo, I fixed it. This is just a simplified and incomplete example, the class will be part of a larger module where path-like names are in use, and this allows us to prefix a set of paths using the `with` statement. The rest of the class will utilize the value, which is why I originally thought to put it at the module level but the answer given corrected that error.
score: 0

http://stackoverflow.com/a/72736354
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52216808
score: 1
has body: Another possible cause is using requests.post when you should be using requests.get or vice versa. I doubt that this is a common problem, but in my case a server that was happy to accept an HTTP GET for a search rejects it with a 415 when HTTP POST is used instead. (Yet another site required that a search be requested using HTTP POST. It was reusing that code that caused my problem.)

http://stackoverflow.com/comment/91431017
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52240868
has text: Thanks so much! It worked for me :). Thanks for the explanation

http://stackoverflow.com/a/52240839
has comment: http://stackoverflow.com/comment/91444113
has body: If you trigger a callback that takes 1 minute to run, you're not returning to the main loop for 1 minute, so the GUI can't respond to anything. There are two common solutions to this. The first is to use a background thread: def function1(): time.sleep(60) print 'function1' def function1_background(): t = threading.Thread(target=function1) t.start() button1 = Button(frame, text='function 1', fg='black', command=function1_background) This is simple, but it only works when your code is purely doing background work, not touching any of the tkinter widgets. The only problem here is that you'd have to def 20 extra functions. You don't want to repeat yourself that much—that's 80 lines of repetitive boilerplate code that gets in the way of seeing the code that matters, and 20 chances to make a stupid bug in copy-pasting that's a pain to track down, and 20 places you have to change if you later decide you want, say, processes instead of threads so the work can parallelize better, or a pool of 4 threads with the background tasks queued up. You can solve that in a few different ways. See this question for more in-depth explanation, but in short, you get Python to do some of the repetitive work for you. You can def a single helper function: def background(func): t = threading.Thread(target=func) t.start() … and then lambda 20 separate function: button1 = Button(frame, text='function 1', fg='black', command=lambda: background(function1)) Alternatively, you can partially apply the function using partial: button1 = Button(frame, text='function 1', fg='black', command=functools.partial(background, function1)) Or, if you never want to call the functions except in the background, you can write a decorator and apply it to each function at def time: def background(func): @functools.wraps(func) def wrapper(): t = threading.Thread(target=func) t.start() return wrapper @background def function1(): time.sleep(60) print 'function1' If you can't use threads (e.g., because the background wor…
has comment: http://stackoverflow.com/comment/91447366
has comment: http://stackoverflow.com/comment/91447039
has comment: http://stackoverflow.com/comment/91438914
score: 5
has comment: http://stackoverflow.com/comment/91436934
type: AcceptedAnswer
upvote count: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52240652
answers question: http://stackoverflow.com/q/52240652
has comment: http://stackoverflow.com/comment/91447381
type: Answer

http://stackoverflow.com/a/52164979
has comment: http://stackoverflow.com/comment/91279324
answers question: http://stackoverflow.com/q/52164834
type: Answer
has comment: http://stackoverflow.com/comment/91279550
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91279653
has comment: http://stackoverflow.com/comment/91279524
has comment: http://stackoverflow.com/comment/91279570
has body: This isn't an exact solution to your requirement, but if you change your negative lookarounds to positive lookarounds, which assert that the number is surrounded on both sides by either whitespace or starting/ending anchors, then you seem to get the behavior you want: rx = r"(\s|^)([\d,|.]+(?:\.\d{2})?)(?=$|\s)" s = "I would like to replace a number with one of the following formats: 200, 200.99, 300,555 unless its between the &lt;&gt; tokens. for example I would like to skip this: &lt;200&gt;" print(re.findall(rx, s)) [(' ', '200,'), (' ', '200.99,'), (' ', '300,555')] Demo (courtesy of Wiktor) One limitation of this is that it won't match a term such as &lt;234, because the number is not surrounded on whitespace/anchors on both sides. But, the pattern does correctly exclude numbers surrounded in tags.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52164834

http://stackoverflow.com/q/52251102
score: 0
tagged with: pandas
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52251709
has comment: http://stackoverflow.com/comment/91449858
tagged with: python
has body: i am want to get some data from 1 data series use value from another data series. for example : dat1 = {'test1':['a','b','c','d','e','f','g','h','i','j','k'], 'test2':[1,2,3,4,5,6,7,8,9,10,11],'test3' [10,11,12,13,14,15,16,17,18,19,20]} dat2 = {'param':['q','a','z','b','o']} df1 = pd.DataFrame(dat1) df2 = pd.DataFrame(dat2) and data i want to get looks like : dat3 = {'test1':['a','b'],'test2':[1,2],'test3':[10,11]} that just example, the data real have more than 1200 rows x 5 columns for the first data series and 5000 rows x 2 columns for the second data series. ps : extension of my data is csv and sep is ","
has comment: http://stackoverflow.com/comment/91449855
type: AnsweredQuestion
has title: get data series with value in another data series python
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52251709

http://stackoverflow.com/comment/91475947
comment on: http://stackoverflow.com/a/52251670
score: 0
type: Comment
type: AnswerComment
has text: @arqchicago how working `df.index = np.where(m, s.mask(m).ffill() + ' ' + s, s)`?

http://stackoverflow.com/comment/91448896
score: 0
comment on: http://stackoverflow.com/q/52250486
type: Comment
type: QuestionComment
has text: So in the above code I have fixed seed value to 1234567 and I am expecting that rf should be same when loop runs 3 times

http://stackoverflow.com/comment/91212992
comment on: http://stackoverflow.com/q/52130838
score: 0
type: Comment
has text: It looks like you have some NaN in that column. You should filter them (drop them or complete them with dict with the keys but empty)
type: QuestionComment

http://stackoverflow.com/comment/91415642
has text: You should add the output to your question. Put it into a code block to preserve formatting.
comment on: http://stackoverflow.com/q/52233254
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52334437
has body: So after spending some time I found a solution myself using numpy.Histogram and plotly Bar chart. Leaving it here in case anyone will face the same problem. def plot_bar_with_outliers(series, name, end): start = int(series.min()) size = 1 # Making a histogram largest_value = series.max() if largest_value &gt; end: hist = np.histogram(series, bins=list(range(start, end+size, size)) + [largest_value]) else: hist = np.histogram(series, bins=list(range(start, end+size, size)) + [end+size]) # Adding labels to the chart labels = [] for i, j in zip(hist[1][0::1], hist[1][1::1]): if j &lt;= end: labels.append('{} - {}'.format(i, j)) else: labels.append('&gt; {}'.format(i)) # Plotting the graph data = [go.Bar(x=labels, y=hist[0])] layout = go.Layout( title=name ) fig = go.Figure(data=data, layout=layout) iplot(fig, filename='basic histogram') plot_bar_with_outliers(test_df['values'], 'values', end=11)
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52225944
upvote count: 11
answers question: http://stackoverflow.com/q/52225944
type: AcceptedAnswer
type: Answer
score: 11

http://stackoverflow.com/a/52167361
answers question: http://stackoverflow.com/q/52167187
has body: A couple things: as soon mentioned, iterating through json_obj['name'] doesn't really make sense - use json_obj['results'] instead. Also, you can use req.json() which is a method that comes with the requests library by default. That will turn the response into a dictionary which you can then iterate through as usual (.iteritems() or .items(), depending if you're using Python 2 or 3).
score: 0
type: Answer

http://stackoverflow.com/q/52165359
type: Question
tagged with: numpy
score: 3
has comment: http://stackoverflow.com/comment/91282290
has title: Lat, Lon, Values CSV to Raster Map Using Python
has body: If I have a CSV Dataset with Lat, Lon, and Value fields, what is the best approach on generating a raster map using python? The raster Z field can be any column within this table.. L5 L6 L7 L8 L9 L10 L11 L12 L13 L14 LAT LON 3.571732 1.338448 0 9.96921E+36 -3.482845 -1.42944 133.229919 141.246002 67.685631 5.059844 24.335797 -95.088764 3.571732 1.338448 0 9.96921E+36 -3.420345 -1.42944 132.749512 140.641464 67.318848 5.105563 24.335107 -95.060013 3.571732 1.338448 0 9.96921E+36 -3.420345 -1.42944 132.230164 140.047211 67.318848 5.063346 24.334408 -95.031263 3.571732 1.338448 0 9.96921E+36 -3.420345 -1.42944 132.230164 139.463104 67.318848 5.063346 24.333701 -95.002512 3.509232 1.369698 0 9.96921E+36 -3.357845 -1.42944 131.702133 137.82196 66.940475 5.021552 24.332986 -94.973763 3.509232 1.369698 0 9.96921E+36 -3.357845 -1.49194 131.702133 137.26651 66.043732 5.021552 24.332263 -94.945013 3.509232 1.369698 0 9.96921E+36 -3.357845 -1.49194 131.165268 136.72081 66.043732 4.980192 24.331531 -94.916265 3.509232 1.338448 0 9.96921E+36 -3.357845 -1.49194 131.165268 136.184738 66.043732 4.980192 24.330792 -94.887516 Keep in mind, These are numpy arrays
answer count: 1
downvote count: 0
tagged with: raster
has comment: http://stackoverflow.com/comment/91281532
has answer: http://stackoverflow.com/a/52169188
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 3
tagged with: maps

http://stackoverflow.com/q/52129486
has comment: http://stackoverflow.com/comment/91209417
has comment: http://stackoverflow.com/comment/91210093
has answer: http://stackoverflow.com/a/52130940
has comment: http://stackoverflow.com/comment/91209535
has comment: http://stackoverflow.com/comment/91209836
tagged with: scipy
has title: Python: Find the nearest neighbor pairs in a list of point coordinates
type: Question
has answer: http://stackoverflow.com/a/52140105
tagged with: numpy
score: 0
has body: I have a list of coordinates. The first element of tuple is the slice number. The 2nd and 3rd are the xy coordinate. Now I want to find the set of points which are nearest. So If I have 6 slices, there must be a return list with pairs of 6 coordinates which belong to each other. Example dataset: array=[(0.0, 333.56146977926664, 3008.7982175915004), (0.0, 172.37833716058688, 1649.3905288621663), (0.0, 77.50966744006188, 2283.89997422016), (0.0, 116.57814612355257, 581.9223534943867), (0.0, 340.0307776756536, 2184.111532373366), (0.0, 313.93527847976634, 318.1736354983754), (0.0, 547.9143957324791, 1097.8102318962867), (0.0, 432.92846166979683, 215.97046269421205), (0.0, 449.53987956249233, 336.3028143050264), (0.0, 503.6196838777661, 167.45041095890411), (0.0, 503.75169204737733, 343.3688663282572), (0.0, 636.3648922234131, 2193.3168988924617), (0.0, 717.4529664732162, 3457.784309632166), (0.0, 846.2564443852878, 603.3166955055681), (0.0, 1535.2396900242939, 3131.323672911694), (0.0, 1469.1578125128474, 1707.8372376026773), (0.0, 1396.379645056139, 92.53690691778341), (0.0, 1415.425816023739, 2627.336980712166), (0.0, 1486.3829039812647, 2626.749414519906), (0.0, 1646.0350180728474, 507.73284624177455), (0.0, 1604.0196393706212, 901.6203629263811), (0.0, 1842.0375522573343, 1814.7994048597038), (0.0, 2007.165137614679, 979.321865443425), (0.0, 2147.671282186245, 1843.2944622254672), (0.0, 2070.921192867391, 3782.243082598893), (0.0, 2065.1681055155877, 478.74772182254196), (0.0, 2104.848780487805, 533.6113821138212), (0.0, 2380.856736123359, 1090.9250925949254), (0.0, 2279.9033647854726, 745.2587146163432), (0.0, 2292.8939526730937, 831.2670902716915), (0.0, 2474.9004065643826, 3268.4603377155236), (0.0, 2453.183810923341, 3408.1759735488613), (0.0, 2585.0363084532373, 2374.9155425659474), (0.0, 2773.128683566231, 725.2908866474347), (0.0, 2624.9709841731856, 915.2607786065126), (0.0, 2714.8521421572996, 971.4124877527389), (0.0, 2798.4276574009355, 2330.613527609011…
answer count: 2
has comment: http://stackoverflow.com/comment/91210005
has comment: http://stackoverflow.com/comment/91209322
has comment: http://stackoverflow.com/comment/91210489
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91210782
has comment: http://stackoverflow.com/comment/91209439
tagged with: python

http://stackoverflow.com/q/52229785
has comment: http://stackoverflow.com/comment/91409494
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91409275
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52230599
has body: So I'm trying to get urls that contain specific strings, but also avoiding urls that contain a bad string. So I don't want any urls that contain the string "/inventory/all/", and I only want urls that contain either the string "/inventories/" or "/inventory/2017/" So I've managed to exclude at least the urls with strings that contain "/inventory/all/" by: get_urls = soup.findAll('a', href=re.compile('^(?!.*/inventory/all/).*$')) But when I try to include the strings I do want to get, then it no longer works, I tried: get_urls = soup.findAll('a', href=re.compile('^(?!.*/inventory/all/).*$'|/inventories/|/inventory/2017/')) Thanks for the help, I'm quite the novice
tagged with: python
tagged with: regex
has title: Excluding/including strings in one re.compile statement in python to extract urls of interest
downvote count: 1
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52230599
has comment: http://stackoverflow.com/comment/91409545
score: -1

http://stackoverflow.com/comment/91471701
score: 0
type: Comment
type: QuestionComment
has text: Actually, it just for my coding skill. I want to know that map can handle those problem too.
comment on: http://stackoverflow.com/q/52236643

http://stackoverflow.com/comment/91459118
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52255642
has text: I'm willing to bet a good amount of money that you haven't even tried any of those answers that "don't solve your problem".

selenium-chromedriver
tags question: http://stackoverflow.com/q/52245604
tags question: http://stackoverflow.com/q/52223302
tags question: http://stackoverflow.com/q/52223642
tags question: http://stackoverflow.com/q/52251595
tags question: http://stackoverflow.com/q/52236941
tags question: http://stackoverflow.com/q/52207679
tags question: http://stackoverflow.com/q/52137903
tags question: http://stackoverflow.com/q/52188524
tags question: http://stackoverflow.com/q/52231034
tags question: http://stackoverflow.com/q/52143316
tags question: http://stackoverflow.com/q/52237681
tags question: http://stackoverflow.com/q/52153398
tags question: http://stackoverflow.com/q/52121506
tags question: http://stackoverflow.com/q/52217866
tags question: http://stackoverflow.com/q/52136427
tags question: http://stackoverflow.com/q/52136897
tags question: http://stackoverflow.com/q/52142270
tag name: selenium-chromedriver
tags question: http://stackoverflow.com/q/52253858
tags question: http://stackoverflow.com/q/52251060
tags question: http://stackoverflow.com/q/52207164
tags question: http://stackoverflow.com/q/52225496
type: Tag
tags question: http://stackoverflow.com/q/52191290
tags question: http://stackoverflow.com/q/52191015
tags question: http://stackoverflow.com/q/52243080
tags question: http://stackoverflow.com/q/52232476

http://stackoverflow.com/q/52153979
has comment: http://stackoverflow.com/comment/91282491
has comment: http://stackoverflow.com/comment/91264554
has comment: http://stackoverflow.com/comment/91282644
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91282605
downvote count: 0
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/91258088
favorite count: 0
accepted answer: http://stackoverflow.com/a/52167973
has comment: http://stackoverflow.com/comment/91282823
type: Question
has comment: http://stackoverflow.com/comment/91283957
has comment: http://stackoverflow.com/comment/91283802
tagged with: python
has comment: http://stackoverflow.com/comment/91266535
has comment: http://stackoverflow.com/comment/91282963
linked to: http://stackoverflow.com/q/40527769
has comment: http://stackoverflow.com/comment/91258124
has comment: http://stackoverflow.com/comment/91283037
score: 20
has comment: http://stackoverflow.com/comment/91267465
answer count: 2
has comment: http://stackoverflow.com/comment/91282856
tagged with: image-processing
possible better answer: http://stackoverflow.com/a/52225346
has body: I am working on an image processing feature extraction. I have a photo of a bird in which I have to extract bird area and tell what color the bird has. I used canny feature extraction method to get the edges of a bird. How to extract only bird area and make the background to blue color? openCv solution should also be fine. import skimage import numpy as np %matplotlib inline import matplotlib.pyplot as plt import os filename = os.path.join(os.getcwd(),'image\image_bird.jpeg') from skimage import io bird =io.imread(filename,as_grey=True) plt.imshow(bird) from skimage import feature edges = feature.canny(bird,sigma=1) plt.imshow(edges ) Actual bird image can be taken from bird link
has comment: http://stackoverflow.com/comment/91282776
has answer: http://stackoverflow.com/a/52225346
tagged with: opencv
has answer: http://stackoverflow.com/a/52167973
upvote count: 20
has comment: http://stackoverflow.com/comment/91281762
has title: Feature extraction and take color histogram
linked to: http://stackoverflow.com/q/27035672
tagged with: scikit-image

http://stackoverflow.com/comment/132571964
type: AnswerComment
comment on: http://stackoverflow.com/a/52228375
type: Comment
has text: What about the `monotonic`(`_ns`)`()` functions? Are these just low-resolution variants of `perf_counter`(`_ns`)`()`?
score: 0

http://stackoverflow.com/comment/91512219
has text: @ManojKengudelu Each iteration of the code will update the curr_password variable. This way, you can use the last generated version in your next function call. Using an external DB would also work, like SQLite3, which is very simple to implement in python3
type: Comment
comment on: http://stackoverflow.com/a/52262895
score: 0
type: AnswerComment

python-imaging-library
tags question: http://stackoverflow.com/q/52162378
tags question: http://stackoverflow.com/q/52205368
tags question: http://stackoverflow.com/q/52259476
tags question: http://stackoverflow.com/q/52124948
tags question: http://stackoverflow.com/q/52145972
tags question: http://stackoverflow.com/q/52184558
tags question: http://stackoverflow.com/q/52234971
tags question: http://stackoverflow.com/q/52222834
tag name: python-imaging-library
tags question: http://stackoverflow.com/q/52235097
tags question: http://stackoverflow.com/q/52157261
type: Tag
tags question: http://stackoverflow.com/q/52175880
tags question: http://stackoverflow.com/q/52112560
tags question: http://stackoverflow.com/q/52251549
tags question: http://stackoverflow.com/q/52186498
tags question: http://stackoverflow.com/q/52250812
tags question: http://stackoverflow.com/q/52266935
tags question: http://stackoverflow.com/q/52234634
tags question: http://stackoverflow.com/q/52172591

http://stackoverflow.com/comment/91198894
comment on: http://stackoverflow.com/q/52123788
score: 1
has text: You haven't really told us what you want to produce. It sounds like you should specify a function. That means specifying what its input should be and what its output should be.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91471413
type: Comment
comment on: http://stackoverflow.com/a/52246512
has text: you are right about that but still have the same error
type: AnswerComment
score: 0

http://stackoverflow.com/a/52281257
has body: I am still learning Python, so there may be better ways, but here is a function that saves a PIL/Pillow image as a JPEG and allows you to specify a maximum size. It uses a binary search to minimise the amount of work needed and it encodes into BytesIO memory buffer to save writing images to disk. If anyone has any suggestions for improvements, please let me know! #!/usr/local/bin/python3 import io import math import sys import numpy as np from PIL import Image def JPEGSaveWithTargetSize(im, filename, target): """Save the image as JPEG with the given name at best quality that makes less than "target" bytes""" # Min and Max quality Qmin, Qmax = 25, 96 # Highest acceptable quality found Qacc = -1 while Qmin &lt;= Qmax: m = math.floor((Qmin + Qmax) / 2) # Encode into memory and get size buffer = io.BytesIO() im.save(buffer, format="JPEG", quality=m) s = buffer.getbuffer().nbytes if s &lt;= target: Qacc = m Qmin = m + 1 elif s &gt; target: Qmax = m - 1 # Write to disk at the defined quality if Qacc &gt; -1: im.save(filename, format="JPEG", quality=Qacc) else: print("ERROR: No acceptble quality factor found", file=sys.stderr) ################################################################################ # main ################################################################################ # Load sample image im = Image.open('/Users/mark/sample/images/lena.png') # Save at best quality under 100,000 bytes JPEGSaveWithTargetSize(im, "result.jpg", 100000) If I run that as is, with target size of 100,000 bytes, I get: -rw-r--r--@ 1 mark staff 96835 11 Sep 18:21 result.jpg If I change the target size to 50,000 bytes, I get: -rw-r--r--@ 1 mark staff 49532 11 Sep 18:26 result.jpg Keywords: Python, PIL, Pillow, JPEG, quality, quality setting, max size, maximum size, image, image processing, binary search.
accepted answer of: http://stackoverflow.com/q/52259476
answers question: http://stackoverflow.com/q/52259476
type: Answer
has comment: http://stackoverflow.com/comment/91919923
upvote count: 17
has comment: http://stackoverflow.com/comment/91801471
has comment: http://stackoverflow.com/comment/91521919
downvote count: 0
has comment: http://stackoverflow.com/comment/91924010
score: 17
has comment: http://stackoverflow.com/comment/91525598
type: AcceptedAnswer

http://stackoverflow.com/a/52257185
answers question: http://stackoverflow.com/q/52256993
type: AcceptedAnswer
type: Answer
has body: I suggest you split your logic into 2 steps. First, reverse your category mappings to map animals to category. For example: animals = {'elephant', 'cobra', 'tiger', 'cow', 'mouse', 'fish', 'turtle'} objects = {'door', 'house', 'desk'} d_cats = {'animals': animals, 'objects': objects} d_cats_rev = {w: k for k, v in d_cats.items() for w in v} You may find the above verbose and painful. But, really, you should never have to make 30 related variables. You should store them in a dictionary for ease, readability, and performance. Second, use collections.Counter, utilizing the mapping you have just created: from collections import Counter res = Counter(map(d_cats_rev.get, words)) Again, the beauty of this method is that you aren't creating new variables, but holding the result in an easily accessible and transportable dictionary. If you find you haven't mapped all words, and only want to include ones you have mapped, you can use filter to remove them: res = Counter(filter(None, map(d_cats_rev.get, words)))
score: 3
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52256993

http://stackoverflow.com/comment/91327170
type: QuestionComment
comment on: http://stackoverflow.com/q/52188435
type: Comment
has text: good job - downvote removed ;)
score: 2

http://stackoverflow.com/q/52132013
has comment: http://stackoverflow.com/comment/91214538
has answer: http://stackoverflow.com/a/52132080
type: Question
has comment: http://stackoverflow.com/comment/91214658
answer count: 2
score: 0
possible better answer: http://stackoverflow.com/a/52132089
has comment: http://stackoverflow.com/comment/91214615
accepted answer: http://stackoverflow.com/a/52132080
has answer: http://stackoverflow.com/a/52132089
favorite count: 0
has body: The request is "Write a function named append_sum that has one parameter named lst. The function should add the last two elements of lst together and append the result to lst. It should do this process three times and then return lst. For example, if lst started as [1, 1, 2], the final result should be [1, 1, 2, 3, 5, 8]." My code is: def append_sum(lst): first = lst.append(lst[-1] + lst[-2]) second = first.append(first[-1] + first[-2]) third = second.append(second[-1] + second[-2]) return third print(append_sum([1, 1, 2])) Then here is the err: Traceback (most recent call last): File 'script.py', line 9, in print(append_sum([1, 1, 2])) File 'script.py', line 4, in append_sum second = first.append(first[-1] + first[-2]) AttributeError: 'NoneType' object has no attribute 'append' Where am I wrong and why? Thank you!
has comment: http://stackoverflow.com/comment/91214631
has comment: http://stackoverflow.com/comment/91214503
upvote count: 1
tagged with: python
downvote count: 1
tagged with: append
type: AnsweredQuestion
has title: Python append_sum(lst)

http://stackoverflow.com/q/52165094
upvote count: 1
has answer: http://stackoverflow.com/a/52165942
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/52165528
answer count: 3
has answer: http://stackoverflow.com/a/52165976
downvote count: 0
favorite count: 0
tagged with: python
has title: Tensor has shape [None, None] when created with placeholders
has body: The product of the two matrices below has a shape of [None, None] if the matrices are created with shapes given in placeholders, but have proper shape when created with ordinary literals: With literals: r1 = 3 r1f = 3.0 c2 = 2 #r1 = tf.placeholder(tf.int32) #r1f = tf.cast(r1, tf.float32) #c2 = tf.placeholder(tf.int32) m1 = tf.reshape(tf.range(r1f), (r1, 1)) m2 = tf.ones((1, c2)) t = tf.matmul(m1, m2) s0 = tf.constant(t.shape[0].value) with tf.Session() as sess: print(sess.run(s0)) #print(sess.run(s0, feed_dict={r1 : 3, c2 : 2})) &gt;&gt;&gt; 3 With placeholders: #r1 = 3 #r1f = 3.0 #c2 = 2 r1 = tf.placeholder(tf.int32) r1f = tf.cast(r1, tf.float32) c2 = tf.placeholder(tf.int32) m1 = tf.reshape(tf.range(r1f), (r1, 1)) m2 = tf.ones((1, c2)) t = tf.matmul(m1, m2) s0 = tf.constant(t.shape[0].value) with tf.Session() as sess: #print(sess.run(s0)) print(sess.run(s0, feed_dict={r1 : 3, c2 : 2})) &gt;&gt;&gt; ValueError: None values not supported. I then ran the graph on t.shape.as_list() instead of t.shape[0].value with the error that the shape would be [None, None]. I am running tensorflow 1.10.1. My questions are: why do I get a shape of [None, None] in the second case and how can I obtain the proper shape?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52165976
score: 1
possible better answer: http://stackoverflow.com/a/52165942

http://stackoverflow.com/a/52236419
answers question: http://stackoverflow.com/q/52152380
has body: map in python 3 doesn't pad with None, you'll need to do that yourself. You might want to use zip_longest and maybe starmap. Python 2 docs for map map(function, iterable, ...) Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list. Python 3 docs for map Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52152380
upvote count: 2

http://stackoverflow.com/comment/91267991
has text: @eyllanesc I have Windows 10 (1803 I believe, if relevant) and the same version of PyQt.
comment on: http://stackoverflow.com/q/52155722
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/60914916
score: 2
upvote count: 2
has body: Python Firebase admin SDK: If you use Firebase Admin SDK then you can have admin access to things without worrying about restrictions and rules on your database. Python Firebase: If you use python firebase (normal firebase) then you need to authenticate each time you access your data (Means you can set rules and permissions for your document)
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52190544

http://stackoverflow.com/comment/91340337
comment on: http://stackoverflow.com/q/52171097
score: 0
has text: Something like that https://stackoverflow.com/questions/34981144/split-text-lines-in-scanned-document/48268334#48268334?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52185289
upvote count: 4
has body: I have a df with values: A B C D 0 1 2 3 2 1 2 3 3 9 2 5 3 6 6 3 3 6 7 4 6 7 5 2 df.shape is 6x4, say df.iloc[:,1] pulls out the B column, but len(df.iloc[:,1]) is also = 6 How do I "reshape" df.iloc[:,1]? Which function can I use so that the output is the length of the actual values in the column. My expected output in this case is 3
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52185350
has comment: http://stackoverflow.com/comment/91320383
type: Question
answer count: 2
has title: How to reshape a python vector when some elements are empty
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52185354
downvote count: 1
has comment: http://stackoverflow.com/comment/91321450
favorite count: 0
has answer: http://stackoverflow.com/a/52185354
accepted answer: http://stackoverflow.com/a/52185350
tagged with: python

http://stackoverflow.com/q/52177390
type: UnansweredQuestion
tagged with: python
tagged with: matlab
tagged with: visual-studio
tagged with: c++
has body: My setup: Given some Legacy™ C++ code Using wrappers that use the Python ↔ C/C++ API, this is compiled into a .pyd file There is a bunch of Legacy™ Python code that uses this .pyd file This Python code is then called from MATLAB MATLAB R2018a / Python 3.6 / C++11 / Windows 10 / MSVC 2017 Community This setup is rigid, i.e., all this code is used by 100s of people in all sorts of different contexts; this non-ideal setup is already the best possible trade-off The problem: MATLAB crashes due to an Access Violation® somewhere in the C++ code. Obviously, MATLAB can't "look through" the .pyd binary to determine the root cause, so this is all I have to go on. What I've tried: Using MSVC2017, build the .pyd in Debug mode (setup.py build --debug). In MATLAB: pyversion 'c:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\python.exe' Be really annoyed by having to restart MATLAB before you can actually do that. After restarting MATLAB and running said command, in MSVC: Debug → Attach to Process → select MATLAB.exe Run the MATLAB code that causes the crash. MATLAB/Python complains: Python Error: ImportError: DLL load failed: The specified module could not be found. Try the same as in 1., this time renaming the my_pylib.pyd file to my_pylib_d.pyd (as found here of all places...) MATLAB/Python complains: Python Error: ImportError: cannot import name 'my_pylib' Try the same as 2., this time stating pyversion 'c:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\python_d.exe' (first making sure that a Python3.6 debugging environment has been installed in the MSVC context). Be REALLY annoyed by having to restart MATLAB Every. Fucken. Time. you run that command! Go to The MathWorks Support site and put in a Feature Request to try and get that fixed in R2019a Restart MATLAB, re-attach MSVC to MATLAB.exe and repeat from the top MATLAB/Python still complains: Python Error: ImportError: cannot import name 'my_pylib' Repeat 3., this time forcing MATLAB to also u…
score: 2
answer count: 0
upvote count: 2
type: Question
linked to: http://stackoverflow.com/q/8846480
tagged with: debugging
has comment: http://stackoverflow.com/comment/91323019
has comment: http://stackoverflow.com/comment/91335963
has comment: http://stackoverflow.com/comment/91307546
has comment: http://stackoverflow.com/comment/91309118
downvote count: 0
has comment: http://stackoverflow.com/comment/91323214
favorite count: 0
has title: How to debug C++ code that is called from Python that is called from MATLAB, using the MSVC debugger?

http://stackoverflow.com/q/52262943
type: Question
tagged with: django-models
score: 0
has body: Let's say I have this model and serializer: class Animal(models.Model): id = models.AutoField(primary_key=True) data_url = models.TextField(unique=True) class AnimalSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = '__all__' If I run: animal = Animal.objects.filter(id=1).first() data = serializers.serialize("json", animal) I get a json string that looks like this: [{"model": "zoo.animal", "pk": 1, "fields": {"id": "1", "sound": "woof"}] Now if I run: animal = Animal.objects.filter(id=1).first() animal_serialized = AnimalSerializer(animal) animal = JSONRenderer().render(animal.data) I get a json string that looks like this: b'[{"id":1,"sound":"woof"}]' However, this json string is missing the "model" and "pk" and "fields" dictionaries, its just the fields. How to get make my AnimalSerializer return this data as well, as it does when I run serializers.serialize("json", animal)?
has comment: http://stackoverflow.com/comment/91474498
tagged with: python-3.x
tagged with: serialization
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91477193
has title: How do I include model in Django Model Serializer?
answer count: 0

http://stackoverflow.com/q/52199530
upvote count: 0
has title: Environment Error while installing OpenCV in windows through pip
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: Click to view image I am trying to install openCV for windows. But I keep getting the following error : Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: C:\Users\hp\AppData\Local\Temp\pip-req-tracker-vfx6an4h\e91a5c7a04ed7f6b813b6ebe4c4eddb2cf610ac6d97a6256c8c8f3ef I am using AMD 64 bit processor with Windows 10 and python 3.5.2[MSC v.1900 64bit (AMD64)] on win32 What is the solution?
tagged with: python
type: UnansweredQuestion
downvote count: 2
tagged with: pip
tagged with: opencv
score: -2
has answer: http://stackoverflow.com/a/52200876
type: Question

http://stackoverflow.com/comment/91447811
has text: Ok, I updated to 0.4.4 and added img.format = 'png' now its working like a charm
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52249475
type: AnswerComment

http://stackoverflow.com/comment/91366328
type: QuestionComment
has text: Actually they don't teach CS at my school.
type: Comment
comment on: http://stackoverflow.com/q/52208453
score: 0

http://stackoverflow.com/q/52186250
type: AnsweredQuestion
has body: So I have a Pandas DataFrame with two columns: first is Grade with values 0 to 9 second is Criteria, with values 0 or 1. Grade (0-9/ Criteria(0/1) Grade Criteria 0 0 1 1 1 0 2 2 1 3 2 0 4 5 1 5 2 1 etc I need to count "Criteria rate", which is actually sum of "1"s in Criteria column, divided by appropriate number of rows in Criteria column, but grouped by Grade column values. For example, for Grade = 2 we count sum of 1 in Criteria column and divide it by number of rows with Grade 2: 2/3, so for Grade 2 we get 0.66 approx. In my example, the answer should look like: Grade / Criteria rate Grade Criteria 0 0 1.000000 1 1 0.000000 2 2 0.666667 3 5 1.000000 Any ideas, how to do this? Also the add. question - how to do this, if we have "yes/no" text values in Criteria column? I've searched here, but found only solutions to groupby's, divided by total rows count etc. Thank you!
possible better answer: http://stackoverflow.com/a/52186815
tagged with: percentage
type: Question
accepted answer: http://stackoverflow.com/a/52186303
upvote count: 5
has title: Pandas - show percentage of values in one column, grouped by other column
answer count: 2
has answer: http://stackoverflow.com/a/52186303
score: 5
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/52186815
favorite count: 0
tagged with: python

http://stackoverflow.com/a/52234951
answers question: http://stackoverflow.com/q/52234914
type: Answer
upvote count: 11
score: 11
has body: Yes, you can access the matplotlib.pyplot.axes object like this: import seaborn as sns lm = sns.lmplot(...) # draw a grid of plots ax = lm.axes # access a grid of 'axes' objects Here, ax is an array containing all axes objects in the subplot. You can access each one like this: ax.shape # see the shape of the array containing the 'axes' objects ax[0, 0] # the top-left (first) subplot ax[i, j] # the subplot on the i-th row of the j-th column If there is only one subplot you can either access it as I showed above (with ax[0, 0]) or as you said in your question through (plt.gca())
has comment: http://stackoverflow.com/comment/91418568
has comment: http://stackoverflow.com/comment/91418556
accepted answer of: http://stackoverflow.com/q/52234914
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52125292
score: 1
has comment: http://stackoverflow.com/comment/91201496
upvote count: 1
answers question: http://stackoverflow.com/q/52125260
has body: String finalString = String.Empty; foreach(var item in myInts) { int unicode = item; char character = (char) unicode; string text = character.ToString(); finalString += text; } If you want a little bit of performance gain using String Builder. StringBuilder finalString = new StringBuilder(); foreach(var item in myInts) { char character = (char) item; builder.Append(character) }
type: Answer
has comment: http://stackoverflow.com/comment/91201596
has comment: http://stackoverflow.com/comment/91201505
downvote count: 0

http://stackoverflow.com/comment/91467340
comment on: http://stackoverflow.com/q/52259476
score: 0
type: Comment
type: QuestionComment
has text: @PeterWood, what do you mean by bulk the file with garbage? Thank you so much for your input.

http://stackoverflow.com/a/52248123
score: 3
upvote count: 3
has body: You can use a list comprehension: dict_a = {1: {'a':1, 'b':2, 'c':3}, 2: {'a':4, 'b':5, 'c':6}} res = [(k, tuple(d[k] for d in dict_a.values())) for k in dict_a[1]] [('a', (1, 4)), ('b', (2, 5)), ('c', (3, 6))] Assumes: dict_a is ordered by outer key, which may be automatic in Python 3.6+. Otherwise, use collections.OrderedDict. The keys in each dictionary value of dict_a are the same.
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52248068
answers question: http://stackoverflow.com/q/52248068
type: Answer

pygame
tags question: http://stackoverflow.com/q/52130385
tags question: http://stackoverflow.com/q/52265073
tags question: http://stackoverflow.com/q/52247828
tags question: http://stackoverflow.com/q/52152162
tags question: http://stackoverflow.com/q/52201024
tags question: http://stackoverflow.com/q/52166042
tags question: http://stackoverflow.com/q/52127886
tags question: http://stackoverflow.com/q/52221982
tags question: http://stackoverflow.com/q/52188275
tags question: http://stackoverflow.com/q/52244302
tags question: http://stackoverflow.com/q/52248406
tags question: http://stackoverflow.com/q/52190277
tags question: http://stackoverflow.com/q/52169004
tags question: http://stackoverflow.com/q/52134701
tags question: http://stackoverflow.com/q/52187409
tags question: http://stackoverflow.com/q/52130339
tags question: http://stackoverflow.com/q/52173662
tags question: http://stackoverflow.com/q/52147970
tags question: http://stackoverflow.com/q/52235712
tags question: http://stackoverflow.com/q/52120258
tags question: http://stackoverflow.com/q/52138069
tags question: http://stackoverflow.com/q/52134609
tags question: http://stackoverflow.com/q/52167667
tags question: http://stackoverflow.com/q/52154951
tags question: http://stackoverflow.com/q/52239139
tag name: pygame
tags question: http://stackoverflow.com/q/52188563
tags question: http://stackoverflow.com/q/52119981
tags question: http://stackoverflow.com/q/52262665
tags question: http://stackoverflow.com/q/52228001
tags question: http://stackoverflow.com/q/52174384
tags question: http://stackoverflow.com/q/52210222
tags question: http://stackoverflow.com/q/52113244
tags question: http://stackoverflow.com/q/52134574
tags question: http://stackoverflow.com/q/52206232
tags question: http://stackoverflow.com/q/52213088
tags question: http://stackoverflow.com/q/52261995
tags question: http://stackoverflow.com/q/52141924
tags question: http://stackoverflow.com/q/52157754
tags question: http://stackoverflow.com/q/52209231
tags question: http://stackoverflow.com/q/52197785
type: Tag
tags question: http://stackoverflow.com/q/52128972

http://stackoverflow.com/q/52189200
tagged with: variables
favorite count: 0
tagged with: input
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52190332
has title: PyQT5- Storing user input from a window prompt into a global variable
has body: I have a program that will store user input into a variable, check if it's an IP address and perform functions from there. I want to add a window to make it look nicer and I'm having a hard time storing variables from the windows. I would like to be able to - -Gather user input and store it in a variable -Use that variable in a function to check it if it matches an IP address and if so, execute if statements. Here's example code from a tutorial that I've been playing around with- import sys from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit from PyQt5.QtGui import QIcon class App(QWidget): def __init__(self): super().__init__() self.title = 'IP / Domain' self.left = 10 self.top = 10 self.width = 640 self.height = 480 self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.getInteger() self.getText() self.getDouble() self.getChoice() self.show() def getText(self): userInput, okPressed = QInputDialog.getText(self, "Get text", "Your name:", QLineEdit.Normal, "") if okPressed and text != '': print(userInput) def ipFormatChk(userInput): #input pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\." \ r"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b" if re.match(pattern, userInput) #do something return if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_())
tagged with: pyqt5
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52190332
score: 0
answer count: 1

http://stackoverflow.com/comment/91183046
has text: @astro123 - No, it is `ix` - [`ix-indexer-is-deprecated`](http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated)
comment on: http://stackoverflow.com/a/52116036
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91479753
comment on: http://stackoverflow.com/q/52265837
has text: @CharlesDuffy, you answer correctly and first. If you put yours as an answer, I can tag as correct.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52235280
upvote count: 1
type: Question
score: 1
has answer: http://stackoverflow.com/a/52237970
tagged with: dataframe
answer count: 2
has comment: http://stackoverflow.com/comment/91431780
downvote count: 0
has title: How to perform conditional addition of columns in Pandas DataFrame?
favorite count: 0
possible better answer: http://stackoverflow.com/a/52235704
accepted answer: http://stackoverflow.com/a/52237970
tagged with: pandas
has answer: http://stackoverflow.com/a/52235704
tagged with: python
has body: I have below dataset. And I want to add the salary of each emp depending upon the months emp_worked.For ex as shown in below dataset emp with name 'aaa' worked for 4 months So I want to do addition of columns jan to Apr and stored it in Total_ sal column. `import pandas as pd` data=pd.read_csv("C:\\Users\\hp\\Desktop\\py\\p1.txt",delimiter=',') df=pd.DataFrame(data) print(df) emp_id emp_name months_worked total_sal jan feb mar apr may \ 0 1 aaa 4 NaN 2000 1 2.0 3 4.0 1 2 bbb 3 NaN 1 2 NaN 4 5.0 2 3 bbb 7 NaN 1 2 34343.0 4 NaN 3 4 bbb 12 NaN 1 2 33434.0 4 5.0 jun jul aug sep oct nov dec 0 5555.0 NaN 74343.0 8 9 10.0 NaN 1 643.0 7.0 NaN 9343 10 13431.0 12.0 2 6343.0 7.0 NaN 9 1043 11.0 12.0 3 NaN 7.0 8.0 9 1 NaN 12.0
type: AnsweredQuestion
tagged with: python-3.x

http://stackoverflow.com/comment/91268921
comment on: http://stackoverflow.com/q/52135667
has text: Thanks @Mad Physicist. `param` is the parameter that I am passing to the instance method. I am not able to think why should be using comprehension instead of what I am using, other than syntactic elegance. I, after surfing the web and reading, understood that child process does only copy the class and hence sending results back from child to parent, to me at least, is not trivial as I am a beginner. I am thankful, if you can advise me how can I address this.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/91186940
has text: @Natalie `grades[0]` will get you the first row, so `grades[0][1:]` would get you the set of headers following "Student".
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52116630
type: Comment

http://stackoverflow.com/a/52202405
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/91353719
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52202240
has body: I think what you want is for every instance of a class (i.e. a and b in your code) to have its own list of random numbers, matching the length you specified when you created the instance. To do this, you should set self.myRandomList within init. Here's the change to your original code: import random as random class myClass: def __init__(self, lengthOfList): self.myRandomList = [] for i in range(0,lengthOfList): self.myRandomList.append(random.uniform(-1.0,1.0)) a = myClass(2) #make a list with 2 random numbers b = myClass(1) #make a list with 1 random number print(a.myRandomList) print(b.myRandomList) What you were doing before was setting myRandomList as a class variable, which will always be shared by all instances of the class, rather than an instance variable. See here for more details: https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3 Hope that helps!
has comment: http://stackoverflow.com/comment/91353881
answers question: http://stackoverflow.com/q/52202240
has comment: http://stackoverflow.com/comment/91354252
upvote count: 3

http://stackoverflow.com/comment/91447781
comment on: http://stackoverflow.com/a/52241298
score: 0
type: AnswerComment
has text: The recurrence relation without consider print statement is `T(n)=n * T(n-1)+O(n)`, because: Assume we know T(n-1), then at the T(n) level, we are doing a loop that calls printperm() n times which does each T(n-1) work, and the loop itself at T(n) level is O(n) amount of work, so T(n) = n * T(n-1)+O(n). The solution to this recurrence is T(n)=n!+O(n). Print statement is O(n) which is executed a n! times overall because one print statement per permutation, and there are n! permutations. So total (recursive + print) we get T(n)=n!+O(n)+n*n!. Overall that is O(n*n!) because n*n! dominates.
type: Comment

http://stackoverflow.com/comment/91401372
score: 1
has text: Loops in pandas should always be avoided. In above problem as well it seems you can avoid iterations by filtering at once.
comment on: http://stackoverflow.com/q/52225908
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52132298
has comment: http://stackoverflow.com/comment/130380336
has comment: http://stackoverflow.com/comment/91215219
favorite count: 0
has comment: http://stackoverflow.com/comment/91215245
has comment: http://stackoverflow.com/comment/91215380
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
has body: I'm trying to make a program that rotates and crops an image ROI (without losing a single pixel of the frame) based just on what minAreaRect() returns (from seeing what it can mark with drawContours). Now since I don't understand what the function returns other than the rotation angle(list [0:1]) I'm struggling to make that myself. All I found on the internet was a Stack Overflow question with code that wasn't really explained very well and didn't realy work (atleast for openCV 3.6 not) May I have any clues to what is the return syntax of this function and what is the method and keywords to search for such things, as well as a short little function that can maybe do that rotation and cropping? Since that looks like a quite common and simple thing to achieve.
upvote count: 1
has title: Rotating and cropping a ROI from minAreaRect() OpenCV python
type: Question
tagged with: opencv
downvote count: 0

http://stackoverflow.com/q/52142290
type: UnansweredQuestion
score: -4
tagged with: python
has comment: http://stackoverflow.com/comment/91234861
downvote count: 4
upvote count: 0
has comment: http://stackoverflow.com/comment/91234471
has answer: http://stackoverflow.com/a/52143257
type: Question
tagged with: dataframe
has body: I have a .csv file in the form: ID scholarship amount applicant experience 1 45000 8 2 65000 10 3 38000 11 4 62000 12 5 45000 9 6 58000 11 7 28000 12 8 78000 12 9 52500 7 10 45000 10 The question is write a code that finds maximum number of scholarships that can be offered without exceeding a total value of 500000. Only consider applicants with 10 or more years of experience. I have tried df[df['applicant experience'] &gt;=10] but still I am obtaining records with total scholarship amount above 500000. Please help
tagged with: pandas
answer count: 1
favorite count: 0
has title: Find maximum number of scholarships without exceeding total value of 500000

http://stackoverflow.com/a/52221790
answers question: http://stackoverflow.com/q/52169004
score: 0
type: Answer
has body: The problem was an incorrect file name: "person1.png" instead of "person1.jpg". If anyone has the same problem, try to print the files in the directory and compare them with the file names in your module. How do I list all files of a directory?

http://stackoverflow.com/q/52125887
answer count: 0
type: UnansweredQuestion
type: Question
has title: Why is this boolean expression not allowed as the condition of a while loop in Python?
has comment: http://stackoverflow.com/comment/91202521
linked to: http://stackoverflow.com/q/2603956
has comment: http://stackoverflow.com/comment/91202564
has comment: http://stackoverflow.com/comment/91202896
has comment: http://stackoverflow.com/comment/91202642
has comment: http://stackoverflow.com/comment/91202629
has comment: http://stackoverflow.com/comment/91202900
duplicate of: http://stackoverflow.com/q/2603956
score: 0
tagged with: while-loop
has body: In [1]: n = '4' != 'e' In [2]: n Out[2]: True In [3]: while n = '4' != 'e': File "&lt;ipython-input-12-1aa2b5c52181&gt;", line 1 while n = '4' != 'e': ^ SyntaxError: invalid syntax The expression n = '4' != 'e' has a boolean True value in Python. However, when used in a while loop, Python 2.7 complains to parse it as the loop condition. Why is it so?
tagged with: python

http://stackoverflow.com/comment/91339578
type: AnswerComment
has text: Well, this would likely work, but the [C++ manual](https://en.cppreference.com/w/cpp/language/friend) claims, beginning with C++11 (which I use), types can already be "friends" -- not just functions/classes... Am I misreading it?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52194876

http://stackoverflow.com/q/52129545
score: 3
downvote count: 0
answer count: 0
type: Question
tagged with: discord.py
duplicate of: http://stackoverflow.com/q/46267705
upvote count: 3
linked to: http://stackoverflow.com/q/46267705
has title: Scheduling an async function with the Schedule library. (Using discord.py rewrite)
tagged with: schedule
linked to: http://stackoverflow.com/q/51530012
tagged with: asynchronous
favorite count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/52131356
has body: Firstly, I found a similar thread: How can I run an async function using the schedule library? This did not help me, or the OP of the thread. I ended up with the same error as him, which he stated in a comment of the only answer. My goal is to run a function (which must be async) every x seconds. (Set to seconds for testing purposes. The finished code will use days.) My simplified code to try do this: @bot.event async def schedTest(): print("Scheduled Message Here") @bot.command(pass_context=True) async def announcements(ctx): schedule.every(1).seconds.do( bot.loop.call_soon_threadsafe, schedTest) After executing the command announcements,the result of this is nothing. No error or prints in the output. This is not the same issue as the thread that this was marked as duplicate as. I am trying to get the schedule library to work, not asyncio.sleep. Sleep is not accurate over the duration of a week.
tagged with: python

http://stackoverflow.com/q/52196554
score: 3
has body: I have a series of sine waves that i have loaded in using a custom dataloader. The data is converted to a torch tensor using from_numpy. I then try to load the data using an enumerator over the train_loader. The iterator is shown below. for epoch in range(epochs): for i, data in enumerate(train_loader): input = np.array(data) train(epoch) The error i receive is: RuntimeError: input must have 3 dimensions, got 2 I know i need to have my input data in [sequence length, batch_size, input_size] for an LSTM but i have no idea how to format my array data of 1000 sine waves of length 10000. Below is my training method. def train(epoch): model.train() train_loss = 0 def closure(): optimizer.zero_grad() print(input.shape) output = model(Variable(input)) loss = loss_function(output) print('epoch: ', epoch.item(),'loss:', loss.item()) loss.backward() return loss optimizer.step(closure) I thought i would try add (seq_length, batch_size, input_size) in a tuple but this cant be fed into the network. Further to this my assumption was that the dataloader fed batch size into the system. Any help would be appreciated. edit: Here is my sample data: T = 20 L = 1000 N = 100 x = np.empty((N, L), 'int64') x[:] = np.array(range(L)) + np.random.randint(-4 * T, 4 * T, N).reshape(N, 1) data = np.sin(x / 1.0 / T).astype('float64') torch.save(data, open('traindata.pt', 'wb'))
tagged with: recurrent-neural-network
type: Question
answer count: 1
favorite count: 0
tagged with: lstm
has title: How to load 2D data into an LSTM in pytorch
upvote count: 4
has answer: http://stackoverflow.com/a/52198302
tagged with: pytorch
type: UnansweredQuestion
tagged with: python
downvote count: 1

http://stackoverflow.com/comment/91313796
score: 1
has text: Sorry first post and wasn't entirely sure what was causing the issue. Will keep this in mind on future posts.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52173662

http://stackoverflow.com/comment/93101579
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52178375
has text: Does the error remain if you remove the Flask code?

http://stackoverflow.com/comment/91254010
type: QuestionComment
type: Comment
has text: Hi aydow. Actually, i read the post you mentioned before i posted my own. The post seems does not work for me. I can run my function 'myFunc(a,b)' successfully, but it gives an error 'name 'myFunc' is not defined' when i run 'reload('myFunc)'
comment on: http://stackoverflow.com/q/52151084
score: 0

http://stackoverflow.com/comment/139388385
comment on: http://stackoverflow.com/a/52204298
has text: ignore_index should be set to false to achieve the output you described
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/57798151
has body: I had same problem, realized that i used pip3 to install the package, but I was trying to use it with python which invokes python2. I tried with python3 it works just fine.
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52236797
type: Answer

http://stackoverflow.com/a/52215331
type: Answer
has comment: http://stackoverflow.com/comment/91379675
has comment: http://stackoverflow.com/comment/91379606
has comment: http://stackoverflow.com/comment/91379887
accepted answer of: http://stackoverflow.com/q/52215289
score: 0
has comment: http://stackoverflow.com/comment/91379775
answers question: http://stackoverflow.com/q/52215289
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91379641
has comment: http://stackoverflow.com/comment/91379738
has body: You can implement the consonant check with the in operator instead. Then split the sentence into words and map to the word processing function: consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ" def weird_latin_from_word(english): if english[0] in consonants: return english[1:] + english[0] + 'eeoow' return english + 'meeoow' def weird_latin_from_sentence(sentence): return ' '.join(weird_latin_from_word(w) for w in sentence.lower().split()) so that: print(weird_latin_from_sentence("Toby likes his art")) outputs: obyteeoow ikesleeoow isheeoow artmeeoow
has comment: http://stackoverflow.com/comment/91379960

http://stackoverflow.com/q/52260354
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91468259
linked to: http://stackoverflow.com/q/28225552
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91468455
has comment: http://stackoverflow.com/comment/91468479
duplicate of: http://stackoverflow.com/q/28225552
has body: I would like to be able to use a single "nested_key" variable to get a value from an (arbitrarily deep) set of nested dicts. If I have a dict of dicts I can simply index it like so: a = {"Alice": {"Car": {"Color": "Blue"}}} a["Alice"]["Car"]["Color"] &gt;&gt;&gt; "Blue" But I don't think(?) I can easily make that chain of indexes into a variable and use it in the same way? a = {"Alice": {"Car": {"Color": Blue}}} nested_key = ["Alice"]["Car"]["Color"] # for use in: a[nested_key] &gt;&gt;&gt; TypeError: list indicies must be integer, not str Lists have the slice() object; but is there a way to assign a 'key-like' object to a variable? Otherwise I suppose a recursive_get style function (e.g. https://stackoverflow.com/a/28225660/2588039) is probably my best bet?
score: 1
has comment: http://stackoverflow.com/comment/91468467
has title: Index dict of dicts with a variable
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91468515
has answer: http://stackoverflow.com/a/52260452
answer count: 1
has comment: http://stackoverflow.com/comment/91468848
has comment: http://stackoverflow.com/comment/91468683
has comment: http://stackoverflow.com/comment/91469187
favorite count: 0

http://stackoverflow.com/comment/91469288
score: 1
has text: You retrieve the account you need from the Application.Session.Accounts collection and assign it to the MailItem.SendUsingAccount property. Which part are you having problems with? What have you tried?
type: AnswerComment
comment on: http://stackoverflow.com/a/52207308
type: Comment

http://stackoverflow.com/q/52125153
tagged with: selenium
accepted answer: http://stackoverflow.com/a/52130691
type: Question
has body: Just realized that a login form isn't being submitted despite not throwing an error: from selenium import webdriver driver_path = "path to chromedriver.exe" url_login = "https://www.findacode.com/signin.html" username = 'jd@mailinator.com' password = 'm%$)-Y95*^.1Gin+' #know it's not best practice to share passwords, but this is a trial account and credentials are necessary to appreciate the problem options = webdriver.ChromeOptions() options.add_argument('headless') driver = webdriver.Chrome(executable_path=driver_path, chrome_options=options) driver.get(url_login) form = driver.find_element_by_name('login') form.find_element_by_name('id').send_keys(username) form.find_element_by_name('password').send_keys(password) form.find_element_by_xpath("//input[@value='Sign In']").submit() No error at this point, but login is unsuccessful: driver.title is "Sign In - FindACode.com" but should be "Find-A-Code - ICD 10 Codes, CPT Codes, HCPCS Codes, ICD 9 Codes - Onlne Encoder - Medical Billing and Coding" and the rest of the page source confirms an unsuccessful sign on I tried an explicit wait after calling .submit(): from selenium.webdriver.support.ui import WebDriverWait as wait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By wait(driver, 10).until(EC.visibility_of_element_located((By.ID, "history"))) # history is an element in post login landing page but not in the pre login page But I receive a timeout error: Traceback (most recent call last): File "&lt;input&gt;", line 29, in &lt;module&gt; File "...\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: I tried another explicit wait after calling .submit() title = "Find-A-Code - ICD 10 Codes, CPT Codes, HCPCS Codes, ICD 9 Codes - Onlne Encoder - Medical Billing and Coding" wait(driver, 10).until(EC.title_is(title)) And I receive another ti…
has comment: http://stackoverflow.com/comment/91211258
answer count: 1
has answer: http://stackoverflow.com/a/52130691
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: Login form submit fails without throwing error
has comment: http://stackoverflow.com/comment/91202485
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/52143587
tagged with: python
has body: i have a json file with thease elements: {"created_at":"Sun Jan 03 09:12:55 +0000 2016","id":683576764392579072,"id_str":"683576764392579072","text":"\u067e\u06cc\u0627\u0645 \u062a\u0633\u0644\u06cc\u062a \u0631\u0626\u06cc\u0633 \u0645\u062c\u0644\u0633 \u062e\u0628\u0631\u06af\u0627\u0646 \u062f\u0631 \u067e\u06cc \u0634\u0647\u0627\u062f\u062a \u0634\u06cc\u062e \u0627\u0644\u0646\u0645\u0631 \u007bshahrekhabar\u007d https://t.co/ML75s9CTYX","source":"\u003ca href=\"http://ifttt.com\" rel=\"nofollow\"\u003eIFTTT\u003c/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":4678224625,"id_str":"4678224625","name":"victor ward","screen_name":"victorward983","location":null,"url":null,"description":null,"protected":false,"verified":false,"followers_count":13,"friends_count":0,"listed_count":8,"favourites_count":0,"statuses_count":7262,"created_at":"Wed Dec 30 13:21:18 +0000 2015","utc_offset":null,"time_zone":null,"geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"F5F8FA","profile_background_image_url":"","profile_background_image_url_https":"","profile_background_tile":false,"profile_link_color":"2B7BB9","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http://pbs.twimg.com/profile_images/682190595184394240/0zFJDnmW_normal.jpg","profile_image_url_https":"https://pbs.twimg.com/profile_images/682190595184394240/0zFJDnmW_normal.jpg","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"urls":[{"url":"https://t.co/ML75s9CTYX","expanded_url":"http://bit…
answer count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/91237335
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91237491
tagged with: unicode
has title: load json with encoded unicode object

http://stackoverflow.com/q/52133936
favorite count: 0
tagged with: python-3.x
tagged with: django
tagged with: python
tagged with: git-bash
has comment: http://stackoverflow.com/comment/91218178
has comment: http://stackoverflow.com/comment/91218367
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has body: I am a total python/git bash noob and new to this. Whenever I run command $ python3 manage.py runserver it seems to run it but hangs. I don't' get any output. How can I fix it or troubleshoot it? My directory in which manage.py is located: /c/python34/pythonprograms/superlists Steps I have done: django-admin.py startproject superlists get into the superlists directory python3 manage.py runserver it runs however then it hangs and blinks. I get not output. If anybody has some suggestions, can you please help me out with some simply-explained steps? Not sure how to get output on this one or how to make it work...all my environment variables seem to be good. I have environment variables setup in my settings for python, python (scripts folder), python (geckodriver). Thank you, Roman
has title: Python3 Manage.py Runserver Hangs when Running Through Git Bash
downvote count: 0

http://stackoverflow.com/q/52217438
score: 3
has answer: http://stackoverflow.com/a/52217616
upvote count: 3
has comment: http://stackoverflow.com/comment/91383444
has body: I am working on an exchange rate data, and the result is very weird with unndeed lines appearing in the graph. I have read through different samples, followed the samples and still cannot get rid of these lines. Does anyone know what's wrong with my code? Thank you for your help. df = df'PRICE', 'TIME' start_time = '2018-08-01 19:50:00' end_time = '2018-08-01 20:10:00' df = df[(df['TIME'] &gt; start_time) &amp; (df['TIME'] &lt;= end_time)] df = df.set_index('TIME') plt.figure(figsize = (18,9)) plt.plot(pd.to_datetime(df.index),df["PRICE"]) plt.xlabel('Time',fontsize=18) plt.ylabel('Mid Price',fontsize=18) If any data is needed, I saved the csv file in google drive https://drive.google.com/file/d/1ANybvOKeUYIhXxtm97VNT88SI8z2OWjV/view?usp=sharing
type: Question
has comment: http://stackoverflow.com/comment/91383976
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/52217725
answer count: 2
tagged with: pandas
downvote count: 0
has title: pandas plot time series- strange line appears
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/52217616
has answer: http://stackoverflow.com/a/52217725
type: AnsweredQuestion

http://stackoverflow.com/comment/91298261
has text: I just tried normpath and it hasn't worked.
comment on: http://stackoverflow.com/q/52173523
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52264135
has body: First make sure you've installed sip module by doing pip install sip and then make sure you use the pyqt plugin so the nuitka freezer will know how to scan the pyqt extension modules, ie: nuitka main.py --standalone --recurse-all --plugin-enable=qt-plugins If that doesn't work, make sure to open a github issue at https://github.com/kayhayen/Nuitka/issues filling up properly the issue template and we'll help you there, we're a friendly community, so proper bug reports will be well received ;D
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52248819
downvote count: 0

http://stackoverflow.com/q/52127217
answer count: 2
accepted answer: http://stackoverflow.com/a/52128472
has title: Write buffer in C which is allocated in python using ctypes, and read back again in python
tagged with: python
has body: Problem Statement: Allocate one buffer of given size 16*100 using numpy array in python, and fill that buffer in C with some struct content, and then wanted to read back that buffer in python again. I have one struct defined as follows: sample.c #include &lt;stdio.h&gt; typedef unsigned char uint8_t; typedef short int16_t; typedef unsigned short uint16_t; struct S{ int a; }; struct ins_data { int16_t offset1; int16_t num1; int16_t offset2; int16_t num2; void *buffer; //==&gt; Need to fill this buffer with struct S contents }; struct desc_data { uint8_t id; void *ins_data; }; void access_ins_data(struct ins_data* ptr) { int i = 0; struct S *p = (struct S*)ptr-&gt;buffer; printf("offset1: %d\n", ptr-&gt;offset1); ptr-&gt;offset1 = 12; ptr-&gt;num1 = 13; struct S tt; tt.a = 10; memcpy(p, &amp;tt, sizeof(struct S)); /* Want to fill this buffer in below fashion, but its not even working for single case. * |struct S s1|struct S s2| struct S s3| * */ printf("S.a: %d\n", p-&gt;a); } void printLib() { printf("Oh Yeah.. you are here"); } void foo(void *p) { struct desc_data *ptr = (struct desc_data*)p; printf("id: %d\n", ptr-&gt;id); access_ins_data(ptr-&gt;ins_data); struct ins_data *ss = (struct ins_data *)ptr-&gt;ins_data; struct S *pp = (struct S*)ss-&gt;buffer; printf("foo : %d\n", pp-&gt;a); } Command used to generate .so file: gcc -o sample.so -shared -fPIC sample.c And below is the code for python world: samplePython.py from ctypes import * import numpy as np class S(Structure): pass S._fields_ = [ ('a', c_int32), ] class ins_data(Structure): pass int16_t = c_int16 ins_data._fields_ = [ ('offset1', int16_t), ('num1', int16_t), ('offset2', int16_t), ('num2', int16_t), ('buffer', c_void_p), ] class desc_data(Structure): pass uint8_t = c_uint8 desc_data._fields_ = [ ('id', uint8_t), ('ins_data', c_void_p), ] def get_ins_data(): arr = np.zeros(16*100, dtype='uint8') enc_data = ins_data(-1,0,-1,0) enc_data.buffer = cast(np.ctypeslib.as_ctypes(arr), c_void_p) return enc_dat…
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/52128472
type: Question
tagged with: http://stackoverflow.com/tag/c
possible better answer: http://stackoverflow.com/a/52128148
has answer: http://stackoverflow.com/a/52128148
tagged with: ctypes

http://stackoverflow.com/comment/91283414
comment on: http://stackoverflow.com/q/52166308
type: Comment
has text: Make your layers successively smaller. A factor of 1/2 works well for MNIST. Don't compress to more than 30-50 units.
score: 0
type: QuestionComment

http://stackoverflow.com/q/52250949
tagged with: stderr
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 3
downvote count: 1
has title: Why does `sys.stderr` and `sys.stdout` put a number at the end on the shell, but not in a module - python
type: Question
has answer: http://stackoverflow.com/a/52250986
has body: Basically my question is the title, so for example in shell: &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.stdout.write('Hello') Hello5 (same with stderr) But from a file: import sys sys.stdout.write('Hello') Output: Hello (same with stderr) So why is this happening???
tagged with: stdout
tagged with: printing
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52250986
tagged with: sys

scrapy
tags question: http://stackoverflow.com/q/52141490
tags question: http://stackoverflow.com/q/52128922
tags question: http://stackoverflow.com/q/52171266
tags question: http://stackoverflow.com/q/52196040
tags question: http://stackoverflow.com/q/52140773
tags question: http://stackoverflow.com/q/52203593
tags question: http://stackoverflow.com/q/52228851
tags question: http://stackoverflow.com/q/52235721
tags question: http://stackoverflow.com/q/52153881
tags question: http://stackoverflow.com/q/52113469
tags question: http://stackoverflow.com/q/52121802
tags question: http://stackoverflow.com/q/52133734
tags question: http://stackoverflow.com/q/52255112
tags question: http://stackoverflow.com/q/52133947
tags question: http://stackoverflow.com/q/52240455
tags question: http://stackoverflow.com/q/52259779
tags question: http://stackoverflow.com/q/52237252
tags question: http://stackoverflow.com/q/52258066
tags question: http://stackoverflow.com/q/52191148
tags question: http://stackoverflow.com/q/52158543
tags question: http://stackoverflow.com/q/52156737
tags question: http://stackoverflow.com/q/52253760
tags question: http://stackoverflow.com/q/52114689
tags question: http://stackoverflow.com/q/52216446
tags question: http://stackoverflow.com/q/52234775
tags question: http://stackoverflow.com/q/52188775
tags question: http://stackoverflow.com/q/52212633
tags question: http://stackoverflow.com/q/52236869
tags question: http://stackoverflow.com/q/52150441
tags question: http://stackoverflow.com/q/52259173
tags question: http://stackoverflow.com/q/52234500
tags question: http://stackoverflow.com/q/52239664
tag name: scrapy
tags question: http://stackoverflow.com/q/52121009
tags question: http://stackoverflow.com/q/52225956
tags question: http://stackoverflow.com/q/52241118
tags question: http://stackoverflow.com/q/52187714
tags question: http://stackoverflow.com/q/52182855
tags question: http://stackoverflow.com/q/52185815
tags question: http://stackoverflow.com/q/52243212
type: Tag
tags question: http://stackoverflow.com/q/52173365
tags question: http://stackoverflow.com/q/52218418
tags question: http://stackoverflow.com/q/52251377
tags question: http://stackoverflow.com/q/52245908
tags question: http://stackoverflow.com/q/52246009
tags question: http://stackoverflow.com/q/52157632
tags question: http://stackoverflow.com/q/52137368

http://stackoverflow.com/a/52247516
answers question: http://stackoverflow.com/q/52247376
type: Answer
has body: Using sum and map: sum(map(len, df.keywords)) Sample df = pd.DataFrame({ 'keywords': [['a', 'b', 'c'], ['c', 'd'], ['a', 'b', 'c', 'd'], ['g', 'h', 'i']] }) sum(map(len, df.keywords)) 12 Timings df = pd.concat([df]*10000) %timeit sum(map(len, df.keywords)) 1.87 ms ± 52.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %timeit df.keywords.map(len).sum() 13.5 ms ± 661 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) %timeit df.keywords.str.len().sum() 14.3 ms ± 272 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) Validation &gt;&gt;&gt; sum(map(len, df.keywords)) == df.keywords.map(len).sum() == df.keywords.str.len().sum() True A bit of a disclaimer: using pandas methods on columns that contain lists is always going to be inefficient (which is why using non-pandas' methods is so much faster here), since DataFrames are not meant to store list. You should try to avoid this whenever possible.
upvote count: 7
score: 7
downvote count: 0

http://stackoverflow.com/q/52205673
has comment: http://stackoverflow.com/comment/91361447
has answer: http://stackoverflow.com/a/52206290
has comment: http://stackoverflow.com/comment/91363617
has comment: http://stackoverflow.com/comment/91361361
tagged with: replace
upvote count: 3
linked to: http://stackoverflow.com/q/33404752
has comment: http://stackoverflow.com/comment/91361340
linked to: http://stackoverflow.com/q/4004431
has title: Emoji converter by using python - (\ud83d\udc40) to the actual emoji symbol
answer count: 1
has comment: http://stackoverflow.com/comment/91385876
tagged with: text-files
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: emoji
has body: I have simple (but extremely hard) question. I'm looking for a way to convert a text file which contains this type of emoji code (\ud83d\udc40) and replace it with the one which will contain - actual emoji symbol E.G. with open(OUTPUT, "r+") as infileInsight: insightData = infileInsight.read()\ .replace('\ud83d\udc40','')\ ...... with open(OUTPUT, "w+") as outfileInsight: outfileInsight.write(insightData) Regarding, that it is duplicated: If I do this way: with open(OUTPUT, "r+") as infileInsight: insightData = infileInsight.read()\ .replace('\ud83d\udc40','')\ ...... with open(OUTPUT, "w+") as outfileInsight: outfileInsight.write(insightData.decode('unicode-escape')) I have an error: UnicodeEncodeError: 'ascii' codec can't encode character u'\u2600' in position 30: ordinal not in range(128)
score: 3
has comment: http://stackoverflow.com/comment/91361125
downvote count: 0
has comment: http://stackoverflow.com/comment/91364676
has comment: http://stackoverflow.com/comment/91361181
type: Question

http://stackoverflow.com/comment/91201410
comment on: http://stackoverflow.com/q/52124683
score: 0
type: Comment
type: QuestionComment
has text: @AChampion, so replaced the if statement with dictionary, do I need clear dictionary command after each function call?

http://stackoverflow.com/a/52250290
has body: First, variance is not just the number-mean squared, it is the sum of all number-mean squared divided by n (or n-1) The range to calculate variance should start from 1 : range(1,n+1) var=0 for num in range(1,n+1): var = var +(num- mean)**2 Now variance can be calculated int two ways : by dividing by n or n-1 thus giving two different answers variance1 = (var*1.0) /n variance2 = (var*1.0) /(n-1) Eg : for n=10, variance1=8.25 and variance2=9.166666666666666 n is used when you're calculating population variance, and n-1 while calculating sample variance. Additional details : Also, while using range if your step value is 1, it need not be specified. Use range(0,n+1) instead of range(0,n+1,1) Avoid using the same variable sum for both mean and variance as it will only cause confusion with the formula.
has comment: http://stackoverflow.com/comment/91449430
type: Answer
has comment: http://stackoverflow.com/comment/91448708
accepted answer of: http://stackoverflow.com/q/52250270
answers question: http://stackoverflow.com/q/52250270
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91358474
comment on: http://stackoverflow.com/q/52202403
type: Comment
type: QuestionComment
score: 0
has text: I said that I've used `double **y` for example, but I don't think that's relevant. But the problem are the arrays on stack. to correct that you could either declare some `static` vars, either allocate them on heap (but then you'd be responsible to freeing them). Also I don't think passing `byref(c_double())` would do the trick.

http://stackoverflow.com/q/52256099
score: 4
has title: Pandas: extract values from column, according to value of another column, and separate into separate dataframes
has body: I have a dataframe indexed by date, with columns of flood size (0-3), and precipitation (ppt): Size ppt date 2017-09-11 0.0 0.000000 2017-09-12 0.0 0.000000 2017-09-13 0.0 0.000000 2017-09-14 1.0 34.709998 2017-09-15 0.0 0.000000 2017-09-16 0.0 0.000000 2017-09-17 0.0 0.000000 2017-09-18 0.0 0.600000 2017-09-19 3.0 157.439998 I need to separate the data according to whether a flood occurred ('Size'=1,2 or 3), or no flood occurred ('Size'=0), to give me two separate sets of precipitation data associated with flood or no flood. I appreciate this is probably quite basic, but I can't seem to find the right answers... Thanks!
has answer: http://stackoverflow.com/a/52256958
has answer: http://stackoverflow.com/a/52256856
has answer: http://stackoverflow.com/a/52256139
upvote count: 4
possible better answer: http://stackoverflow.com/a/52256856
answer count: 3
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52256139
type: Question
tagged with: python

http://stackoverflow.com/comment/91206562
type: AnswerComment
comment on: http://stackoverflow.com/a/52124552
score: 0
type: Comment
has text: Awesome, this is so helpful. I did not understand that FeatureUnion parallelizes its input. StandardScaler is another piece of the puzzle I'm still wrapping my head around. I've read that a lot of classifiers require it to normalize the data, so I kept it for that reason

http://stackoverflow.com/comment/91281074
comment on: http://stackoverflow.com/a/52160234
score: 0
type: AnswerComment
type: Comment
has text: Hm. This is quite weird. If I am right it should stay same, since you are not creating new data. Does it stop going up after a few minutes?

http://stackoverflow.com/comment/91483616
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52260968
score: 0
has text: hi, any finding on this? thanks.

http://stackoverflow.com/comment/91289526
comment on: http://stackoverflow.com/a/52167439
has text: so if i want to pass all three what should i do ?
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/91427668
score: 0
comment on: http://stackoverflow.com/a/52239463
has text: It does not appear to work... The first approach returns (as expected): "TypeError: unsupported operand type(s) for +: 'int' and 'str'". The second one never identifies an all null string (it always returns true).
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91218533
type: QuestionComment
comment on: http://stackoverflow.com/q/52134169
has text: What have you tried yourself? Where exactly are you stuck?
score: 0
type: Comment

http://stackoverflow.com/q/52199258
score: -3
has body: So I have many items in listbox and I want when user clicks on a certain item in the listbox, it should display the corresponding window. So for example, if the user clicks the first item in the listbox, it should display window_1, if the user clicks the second item it should display window_2 and so on... How can I achieve that with tkinter?
upvote count: 0
tagged with: user-interface
answer count: 1
has comment: http://stackoverflow.com/comment/91355561
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91356044
has title: How to open new window when user clicks specific item in listbox with Python tkinter
accepted answer: http://stackoverflow.com/a/52204573
has comment: http://stackoverflow.com/comment/91358202
tagged with: python
has comment: http://stackoverflow.com/comment/91356125
type: AnsweredQuestion
tagged with: tkinter
downvote count: 3
type: Question
has answer: http://stackoverflow.com/a/52204573

http://stackoverflow.com/comment/91211784
score: 1
comment on: http://stackoverflow.com/q/52130109
type: QuestionComment
type: Comment
has text: Have you multiple Python versions on your computer and numpy is only in one of them installed?

http://stackoverflow.com/comment/91432731
score: 2
type: Comment
has text: Why `.transform('cumsum')`? [`.cumsum()` also exists as it own function.](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cumsum.html)
comment on: http://stackoverflow.com/a/52239342
type: AnswerComment

http://stackoverflow.com/a/52171909
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/52171234
accepted answer of: http://stackoverflow.com/q/52171234
type: AcceptedAnswer
downvote count: 0
has body: I think this is due to where in the overall stack the Python REPL exists, causes exit() to not actually exit the JVM that Spark is inside of. The exception you are looking for to exit a spark job is probably SparkException - https://github.com/apache/spark/blob/master/core/src/main/scala/org/apache/spark/SparkException.scala Alternatively, in Databricks, you can use dbutils.notebook.exit() https://docs.databricks.com/user-guide/notebooks/notebook-workflows.html#notebook-workflows
type: Answer

http://stackoverflow.com/comment/91226113
score: 1
has text: A better way is to use `math.trunc(number * 100) / 100`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52138175

http://stackoverflow.com/comment/91383243
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52217113
type: QuestionComment
has text: nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2013 NVIDIA Corporation Built on Wed_Jul_17_18:36:13_PDT_2013 Cuda compilation tools, release 5.5, V5.5.0

http://stackoverflow.com/comment/104003827
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52541326
has text: Please check with the latest GRASS GIS 7.8.1. More Python 3 cleanup has been done...
type: AnswerComment

http://stackoverflow.com/comment/91343557
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52196937
has text: @AkashBadam Iread it.But I cannot find how I should write codes to do my ideal things.

http://stackoverflow.com/comment/91247769
score: 0
type: Comment
type: QuestionComment
has text: A screen shot of an Excel sheet doesn't really reveal what bytes are in the CSV file you are trying to import. See the [Stack Overflow `character-encoding` tag info page](/tags/character-encoding/info) for troubleshooting tips and perhaps [edit] your question to show us the actual bytes around the error.
comment on: http://stackoverflow.com/q/52146463

http://stackoverflow.com/a/52175584
has comment: http://stackoverflow.com/comment/91301965
score: 1
has comment: http://stackoverflow.com/comment/91302020
has body: Try it by making three boolean masks, one for each condition, and then merging them with np.logical_and im = #define the image suitably mask = np.logical_and.reduce((im[:,:,0]&lt;100,im[:,:,1]&lt;100,im[:,:,2]&gt;100)) im[mask] # returns all pixels satisfying these conditions This is fast. It is based upon two numpy capabilities: broadcasting and masking. You can and should read about these in the numpy documentation. You only need for loops for relatively complex tasks. edit: if you want the indices of the pixels, do i,j = np.where(mask) Then the pixel values are im[i,j]
has comment: http://stackoverflow.com/comment/91302047
answers question: http://stackoverflow.com/q/52175284
has comment: http://stackoverflow.com/comment/91301989
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91301999
has comment: http://stackoverflow.com/comment/91302013
type: Answer
has comment: http://stackoverflow.com/comment/91302117
has comment: http://stackoverflow.com/comment/91302100
accepted answer of: http://stackoverflow.com/q/52175284
upvote count: 1

http://stackoverflow.com/comment/91197576
score: 0
type: QuestionComment
type: Comment
has text: @Carcigenicate I revised code.
comment on: http://stackoverflow.com/q/52123099

http://stackoverflow.com/comment/91418429
score: 0
has text: Is there any difference between `category1` and `category2` in terms of fields?
comment on: http://stackoverflow.com/q/52234834
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91217814
type: Comment
has text: I rewrote the script to use pd.read_sql() as you stated, but the memory usage results were the same. By the way I got pd.read_sql() to work without using SQLAlchemy.
comment on: http://stackoverflow.com/a/52133460
type: AnswerComment
score: 0

http://stackoverflow.com/a/52223593
downvote count: 0
has body: Well, there are several issues with this code: You modify the original n at the beginning (n //= 10). This basically causes n to always be one digit. Use another variable instead: m = n while m // 10 &gt; 0: l += 1 m //= 10 Your recursive call doesn't update n, so you enter an infinite loop: while n &lt;= maxprime: dominant_prime_finder() Replace with: if n &lt;= maxprime: dominant_prime_finder(maxprime, n + 1) Even after fixing these issues, you'll cause a stack overflow simply because the dominant prime numbers are very far apart (2, 5, 3733, 59399...). So instead of using a recursive approach, use, for example, a generator: def dominant_prime_finder(n=1): while True: l = 1 #length of the current number m = n while m // 10 &gt; 0: l += 1 m //= 10 if test_prime(n): is_dominant_prime = True index_smaller = n while l &gt; 1 and index_smaller &gt; 9: index_smaller //= 10 if not test_prime(index_smaller): is_dominant_prime = False break for i in range(1,10): if test_prime(i*10**l + n): is_dominant_prime = False break if is_dominant_prime: yield n n = n + 1 g = dominant_prime_finder() for i in range(1, 10): # find first 10 dominant primes print(g.next())
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52222756
score: 2

http://stackoverflow.com/a/52118453
score: 0
has body: Assuming your list is called urls: def remove_special_chars(url, char_list=None): if char_list is None: # Build your own default list here char_list = ['#', '%'] for character in char_list: if url.endswith(character): return remove_special_chars(url[:-1], char_list) return url urls = [remove_special_chars(url) for url in urls] If you want to get rid of a special set of characters just change either the default value or pass a proper list as an argument
has comment: http://stackoverflow.com/comment/91191508
type: Answer
has comment: http://stackoverflow.com/comment/91250089
has comment: http://stackoverflow.com/comment/91191311
answers question: http://stackoverflow.com/q/52118382

http://stackoverflow.com/comment/91282897
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52151005
has text: `www.pastebin.com`, then paste the generated link here
score: 0

speed-test
tags question: http://stackoverflow.com/q/52172346
tag name: speed-test
type: Tag

http://stackoverflow.com/comment/91279479
comment on: http://stackoverflow.com/a/52165001
type: AnswerComment
type: Comment
has text: Didnt see that class. Good catch ;)
score: 1

http://stackoverflow.com/comment/91469229
score: 0
type: AnswerComment
type: Comment
has text: @CarlsonBimbuh, it will depend on the number of samples you have, for short number of samples yours will be better, since you are avoiding some checks, but at some point it will turn around. I dont think there is any solucion that runs in a better `bigO` than yours (this solution still runs in the same time complexity), But you can get many python ideas from this code to improve yours.
comment on: http://stackoverflow.com/a/52260612

http://stackoverflow.com/comment/91381210
type: QuestionComment
comment on: http://stackoverflow.com/q/52202630
has text: It looks like your file content is being encoded twice - initially utf-8, then latin-1. I'd imagine this is happening in the browser, but don't have any time to test right now.
score: 0
type: Comment

http://stackoverflow.com/a/52265894
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: sys.argv [doc] is a the list of parameters passed to the program, including the program itself as first parameter (so sys.argv[0] is the name of the program). We thus can use sys.argv[1] and sys.argv[2] to pass the two extra parameters: if __name__ == "__main__": print(list(breath_first_search(graph, sys.argv[1], sys.argv[2]))) Or we can first do some proper checking and sequence unpacking to make it more elegant: if __name__ == "__main__": if len(sys.argv) != 3: print('Program requires two parameters') sys.exit(1) __, a, b = sys.argv print(list(breath_first_search(graph, a, b)))
answers question: http://stackoverflow.com/q/52265837
type: Answer
accepted answer of: http://stackoverflow.com/q/52265837

http://stackoverflow.com/a/52147767
answers question: http://stackoverflow.com/q/52146661
score: 0
type: Answer
has body: A recursive approach: def split_polygons(s): if s == '': # base case return [] start, rest = s.split(',', 1) head, tail = map(lambda x: x.strip(', '), rest.split(start, 1)) poly = start + ',' + head + start # reconstruct the first polygon return [poly] + split_polygons(tail) &gt;&gt;&gt; p = '17.17165756225586 -28.102264404296875,17.184370040893555 -28.200496673583984,17.1986083984375 -28.223613739013672,17.17165756225586 -28.102264404296875, 28.865726470947266 -28.761619567871094,28.80694007873535 -28.75750160217285,28.792499542236328 -28.706947326660156, 28.865726470947266 -28.761619567871094' &gt;&gt;&gt; split_polygons(p) ['17.17165756225586 -28.102264404296875,17.184370040893555 -28.200496673583984,17.1986083984375 -28.22361373901367217.17165756225586 -28.102264404296875', '28.865726470947266 -28.761619567871094,28.80694007873535 -28.75750160217285,28.792499542236328 -28.70694732666015628.865726470947266 -28.761619567871094']

http://stackoverflow.com/comment/91338508
score: 0
type: Comment
has text: @Alpha this produces your expected output.
type: AnswerComment
comment on: http://stackoverflow.com/a/52193239

http://stackoverflow.com/comment/91381897
type: Comment
type: AnswerComment
has text: Thank you for your contribution! So I am not sure if this would solve my problem and my post was not too clear I guess. When the new tab is created by clicking on the second one, it shall look exactly like the second tab, so take over every label, textinput, button, StackLayout, ScrollView etc. And I will have way more widgets in the actual tab so I don't know if it is handy to create variables for all of them.
comment on: http://stackoverflow.com/a/52212378
score: 0

http://stackoverflow.com/q/52225981
has comment: http://stackoverflow.com/comment/91403310
has comment: http://stackoverflow.com/comment/91402449
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52239192
tagged with: matplotlib
score: 0
has answer: http://stackoverflow.com/a/52239192
tagged with: pandas
has comment: http://stackoverflow.com/comment/91403110
answer count: 1
linked to: http://stackoverflow.com/q/35099130
has comment: http://stackoverflow.com/comment/91401592
has title: Create a temporal plot of events with dashed lines with matplotlib & pandas
has body: I'm trying to create a graph of dashed lines that represent the length of an event for each of my hashes. my dataframe is as follows: hash event start end 0174FAA018E7FAE1E84469ADC34EF666 baseball 00:00:00:000 00:00:00:500 0174FAA018E7FAE1E84469ADC34EF666 baseball 00:00:01:000 00:00:01:500 0174FAA018E7FAE1E84469ADC34EF666 cat 00:00:01:500 00:00:02:500 AF4BB75F98579B8C9F95EABEC1BDD988 baseball 00:00:01:000 00:00:01:500 AF4BB75F98579B8C9F95EABEC1BDD988 cat 00:00:01:500 00:00:02:500 AF4BB75F98579B8C9F95EABEC1BDD988 cat 00:00:03:200 00:00:05:250 AF4BB75F98579B8C9F95EABEC1BDD988 cat 00:00:03:000 00:00:04:350 something similar to the answer here: Change spacing of dashes in dashed line in matplotlib where the hashes are on the y-axis and there are time intervals on the x-axis with event types color coded and broken up by blank space if there is no event for that time interval. this is what I've tried so far but it's not working: fig,ax = plt.subplots() ax.plot([0, df.end], [df.hash], linestyle='--', dashes=(5, 5)) see below for example
tagged with: python
has comment: http://stackoverflow.com/comment/91403170

http://stackoverflow.com/comment/91339145
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52194608
type: Comment
has text: Thanks a lot, it's working perfectly. Any good reason to let requests do the job? I created a dictionary, and your better option seems pretty much identical

http://stackoverflow.com/q/52249270
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
upvote count: 0
has body: I'm working on this Magic 8 Ball assignment for my class, and I am having some issues with the final part of the assignment. The original code was this: import random import time question = input('What is your question? ') if 'Why?' in question or 'Why' in question or 'why' in question: print('Why not?') else: randomResponse = random.randint(1,4) if randomResponse == 1: print('...the probabilities are in your favor...') if randomResponse == 2: print('...make no definite plans...') if randomResponse == 3: print('...the answer is hazy...') if randomResponse == 4: print('...you already know the answer...') The assignment is basically to do this: 1) As is, the code only asks for one question and provides an answer. Alter the code so that it contains a loop to keep asking questions and providing answers until the user has no more questions. 2) The only key word the program looks for in the user's question is 'Why'. Alter the program so it checks for at least three more keywords and provides answers specific to that key word. 3) Modify the code so the generic answers are determined in a function, The header for the function is def generalResponse(question): I've gotten #1 and #2 to work, but #3 is giving me a little bit of a headache since I cannot seem to get my program to escape out of the while loop when I create a separate function for my general responses. Here is my code so far: import random import time question = input('What is your question?\nIf you are finished asking questions, type "Done".') def generalResponse(question): question = question randomResponse = random.randint(1,4) if question == "Done": exit() elif randomResponse == 1: print('...the probabilities are in your favor...') question = input('What is your next question?\nIf you are finished asking questions, type "Done".') elif randomResponse == 2: print('...make no definite plans...') question = input('What is your next question?\nIf you are finished asking questions, type "Done".') elif randomRespons…
type: Question
has comment: http://stackoverflow.com/comment/91446770
score: -1
has title: Magic 8 Ball Program Looping Not Working As Expected
has answer: http://stackoverflow.com/a/52249356
accepted answer: http://stackoverflow.com/a/52249356
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/52209035
type: AnsweredQuestion
score: 1
tagged with: python-unittest
upvote count: 1
has title: Python not able to find tests when test files are in different module
accepted answer: http://stackoverflow.com/a/52209903
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/52210106
downvote count: 0
has answer: http://stackoverflow.com/a/52210106
tagged with: python-2.7
has body: I have a directory structure like below horizontalupgrade common/ __init__.py upgradestate.py tests/ common/ __init__.py testupgradestate.py Content of testupgradestate.py import unittest from upgradestate import UpgradeState class UpgradeStateTest(unittest.TestCase): def setUp(self): print "Setup Called" def test_copy(self): u = UpgradeState("") print "test_copy Called" if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(UpgradeStateTest) runner = unittest.TextTestRunner() runner.run(suite) But on trying to execute the tests python is not able to find the tests (venv) dmanna-a01:horizontalupgrade dmanna$ python -m unittest discover -v ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK But if I make my directory structure like below horizontalupgrade common/ __init__.py upgradestate.py testupgradestate.py Then the tests are running fine (venv) dmanna-a01:horizontalupgrade dmanna$ python -m unittest discover -v test_copy (common.testupgradestate.UpgradeStateTest) ... Setup Called test_copy Called ok ---------------------------------------------------------------------- Ran 1 tests in 0.000s OK Can someone let me know what I am doing wrong? How can I make the tests run from a different test package? Python - 2.7
favorite count: 0
has answer: http://stackoverflow.com/a/52209903
tagged with: python

http://stackoverflow.com/comment/91510347
score: 0
type: Comment
type: QuestionComment
has text: @NedU From what I understand you want to access mousePressEvent or at least the right click, left click and set the text, am I right ?. On the other hand I see it difficult to implement what you want using the QtWidgets, my idea is to create all that behavior in QML and expose the properties to python and for that I could use QQuickWidget.
comment on: http://stackoverflow.com/q/52266968

http://stackoverflow.com/comment/91364393
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52207221
has text: I tried this but I am getting the following TypeError: cannot unpack non-iterable int object
type: AnswerComment

http://stackoverflow.com/a/52251494
answers question: http://stackoverflow.com/q/52251325
has comment: http://stackoverflow.com/comment/91460275
score: 0
has comment: http://stackoverflow.com/comment/91452978
has body: From the docs: Calling a coroutine does not start its code running – the coroutine object returned by the call doesn’t do anything until you schedule its execution. There are two basic ways to start it running: call await coroutine or yield from coroutine from another coroutine (assuming the other coroutine is already running!), or schedule its execution using the ensure_future() function or the AbstractEventLoop.create_task() method. As @dirn's answer implies, ensure_future by itself does not start the task unless there is an event loop already running. However, the subsequent loop kickoff with run_until_complete does start the task.
type: Answer

http://stackoverflow.com/q/52144469
tagged with: tkinter
type: Question
tagged with: label
score: 0
has answer: http://stackoverflow.com/a/52144616
accepted answer: http://stackoverflow.com/a/52144616
answer count: 1
has title: New window label
has body: how do I position my label which says "Question One" in my def new_window() function. As you run it the label is being positioned at the bottom, And i want it to be applied on the top. from tkinter import * from tkinter import ttk #User Interface Code root = Tk() # Creates the window root.title("Quiz Game") def new_window(): newWindow = Toplevel(root) display = Label(newWindow, width=150, height=40) message = Label(newWindow, text="Question One", font = ("Arial", "24")) display.pack() message.pack() display2 = Label(root, width=100, height=30, bg='green') button1 = Button(root, text ="Continue", command=new_window, width=16, bg="red") message_label1 = Label(text="A Quiz Game", font = ("Arial", "24"), padx=40, pady=20) message_label2 = Label(root, text="Click 'Continue' to begin.", wraplength=250) display2.pack() button1.pack() message_label1.pack() message_label2.pack() root.mainloop() # Runs the main window loop
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/122183006
type: AnswerComment
comment on: http://stackoverflow.com/a/58978449
has text: Regarding the encoding of `b'ARROW:schema'`: https://stackoverflow.com/questions/61707170/how-to-read-the-arrow-parquet-key-value-metadata
type: Comment
score: 1

http://stackoverflow.com/q/52227266
score: 2
type: AnsweredQuestion
has body: I have a dictionary that looks like this: global_dict_names=dict{'com':'owb_com','cur':'cur_con','cty':'gds_cty','cur':'gds_cur'} My dataframe looks like this: com12 cur34 cty56 cur78 a b c d b c d e I would like my dataframe to look like this: owb_com12 cur_con34 gds_cty56 gds_cur78 a b c d b c d e My current code looks like this: GDS2018_labels.columns = [global_dict_names.get(x[:3], x) for x in GDS2018_labels.columns] This current code matches the first three characters of the column names with the keys from the dictionary. The problem with this code is that it replaces the entire column name, but I only want to replace the substring of the column name that matches with the key. How can I correct this?
possible better answer: http://stackoverflow.com/a/52227324
has answer: http://stackoverflow.com/a/52227324
has answer: http://stackoverflow.com/a/52227362
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91404127
tagged with: dataframe
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52227362
downvote count: 0
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/91404083
upvote count: 2
tagged with: python
tagged with: dictionary
has title: How to only replace substring not entire string?
has comment: http://stackoverflow.com/comment/91404053

http://stackoverflow.com/q/52119037
has answer: http://stackoverflow.com/a/52139261
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
type: UnansweredQuestion
has body: I am facing a performance issue of pandas rolling(expanding) 10 years history record zscore calculation. It is too slow for single recent day zscore, it need 17seconds for calculate to whole history, it need around 30 minutes.(I has already resample this history record to weekly level to downsize to total record. If you are any advise to speed up my lastz function, pls feel free to share you idea. Here is the detail. 1. Data set. a 10 years stock record which has been resampled to balance the size &amp; accuracy. Total size is (207376, 8) which covered about 500 index data for last 10 years. Here is the sample: &gt; Close PB1 PB2 PE1 PE2 TurnoverValue TurnoverVol ROE &gt;ticker tradeDate &gt;000001 2007-01-07 2678.526489 3.38135 2.87570 34.423700 61.361549 7.703712e+10 1.131558e+10 0.098227 &gt;2007-01-14 2755.759814 3.45878 3.09090 35.209019 66.407800 7.897185e+10 1.116473e+10 0.098236 &gt;2007-01-21 2796.761572 3.49394 3.31458 35.561800 70.449658 8.416415e+10 1.129387e+10 0.098250 I want to analyze the zscore changing in history and to forecast to future. So, lastz function defined as below The functions need speed up: ts_start=pd.to_date("20180831") @numba.jit def lastz(x): if x.index.max()[1]&lt;ts_start: return np.nan else: freedom = 1 # it is sample, so the sample std degree of freedome should not be 0 but 1 nlimit_interpolate = int(len(x)/100) #1% fill allowed #print(nlimit_interpolate, len(x)) x=x.interpolate(limit=nlimit_interpolate+1 ) # plus 1 in case of 0 or minus x=x.loc[x.notnull()] Arry=x.values zscore = stats.zmap(Arry[-1],Arry,ddof=freedom) return zscore weekly = weekly.sort_index() %prun -s cumtime result = weekly.groupby(level="ticker").agg(lastz) Here is the prun results for single calling: 13447048 function calls (13340521 primitive calls) in 17.183 seconds Ordered by: cumulative time &gt; ncalls tottime percall cumtime percall &gt; filename:lineno(function) &gt; 1 0.000 0.000 17.183 17.183 {built-in method builtins.exec} &gt; 1 0.000 0.000 17.1…
tagged with: python
has comment: http://stackoverflow.com/comment/91227866
tagged with: performance
score: 0
has comment: http://stackoverflow.com/comment/91228035
type: Question
has title: group by ,multiindex, timeseris zscore calcuation slow (17 seconds) , need you clue to speed up

http://stackoverflow.com/a/52265289
has comment: http://stackoverflow.com/comment/91479450
accepted answer of: http://stackoverflow.com/q/52265195
upvote count: 2
answers question: http://stackoverflow.com/q/52265195
has comment: http://stackoverflow.com/comment/91479401
has comment: http://stackoverflow.com/comment/91478784
score: 2
has comment: http://stackoverflow.com/comment/91478753
type: AcceptedAnswer
downvote count: 0
has body: Your current setup class A: def run(self): exit = False def walk(): global exit exit = True walk() print(exit) a = A() a.run() # False print(exit) # True prints False because the exit you print inside run lives in the scope of run, it is not a global variable. You are actually setting a global variable exit in walk - see the second call to print giving True. What you want instead of global is the nonlocal keyword which lets you modify free variables. Let's examine what happens without global first, however. class A: def run(self): exit = False def walk(): exit = True walk() print(exit) a = A() a.run() # False The code prints False because run does not care about the creation of local variables that are assigned in walk. With the addition of nonlocal however class A: def run(self): exit = False def walk(): nonlocal exit exit = True walk() print(exit) a = A() a.run() # True the code will output True, because exit = True is now setting the variable exit in the enclosing, nonlocal scope of run. The key topics you should research for additional context are closures and free variables.
type: Answer

http://stackoverflow.com/q/52121506
answer count: 0
has comment: http://stackoverflow.com/comment/91317447
tagged with: selenium
linked to: http://stackoverflow.com/q/48028782
type: Question
has comment: http://stackoverflow.com/comment/91200492
has comment: http://stackoverflow.com/comment/91249858
has comment: http://stackoverflow.com/comment/91207927
has comment: http://stackoverflow.com/comment/91200483
has comment: http://stackoverflow.com/comment/91200240
score: 0
has comment: http://stackoverflow.com/comment/91194350
has comment: http://stackoverflow.com/comment/91206228
has title: Error while opening link using python and selenium
has body: Trying to open google in browser using python and selenium, gave me following errors:(Image of errors) DevTools listening on ws://127.0.0.1:57033/devtools/browser/45f6818b-0d1e-4b81-9 637-861b579c7470 [0901/085753.496:ERROR:gl_surface_egl.cc(863)] eglInitialize D3D9 failed with er ror EGL_NOT_INITIALIZED [0901/085753.496:ERROR:gl_initializer_win.cc(232)] GLSurfaceEGL::InitializeOneOf f failed. [0901/085753.502:ERROR:viz_main_impl.cc(201)] Exiting GPU process due to errors during initialization [7188:10216:0901/085753.819:ERROR:gpu_process_transport_factory.cc(1016)] Lost U I shared context. [0901/085753.912:ERROR:command_buffer_proxy_impl.cc(113)] ContextResult::kFatalF ailure: Shared memory handle is not valid [0901/085753.962:ERROR:command_buffer_proxy_impl.cc(113)] ContextResult::kFatalF ailure: Shared memory handle is not valid It starts chrome browser, also opens the link, but it is giving error in back... print("Starting...") from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import Select print("Opening...") driver = webdriver.Chrome() driver.get('https://google.com')
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91200414
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91583108
has comment: http://stackoverflow.com/comment/91207726
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
has comment: http://stackoverflow.com/comment/91196577

http://stackoverflow.com/q/52258557
has body: How i can save or download this picture with python [binary]
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/91465657
has comment: http://stackoverflow.com/comment/117720695
tagged with: python
score: -2
upvote count: 3
has comment: http://stackoverflow.com/comment/91464435
has answer: http://stackoverflow.com/a/52280162
has comment: http://stackoverflow.com/comment/91465151
answer count: 1
linked to: http://stackoverflow.com/q/33870538
linked to: http://stackoverflow.com/q/2323128
downvote count: 5
type: UnansweredQuestion
has title: seve picture 'data:image/jpeg;base64' with python

http://stackoverflow.com/comment/91424263
score: 0
type: Comment
type: QuestionComment
has text: Thanks for the heads up @JohnHanley, already confirmed.
comment on: http://stackoverflow.com/q/52228704

http://stackoverflow.com/a/63419080
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52157535
upvote count: 1
score: 1
has body: trio provides a better way to do this with nursery objects: async with trio.open_nursery() as nursery: nursery.start_soon(long_task) # Task will run in background await short_task() # Wait for background tasks to finish
answers question: http://stackoverflow.com/q/52157535

http://stackoverflow.com/q/52182547
score: 0
has comment: http://stackoverflow.com/comment/91316365
has comment: http://stackoverflow.com/comment/91316291
has comment: http://stackoverflow.com/comment/91317732
has comment: http://stackoverflow.com/comment/91315919
has comment: http://stackoverflow.com/comment/91317035
has comment: http://stackoverflow.com/comment/91316475
has comment: http://stackoverflow.com/comment/91316131
has comment: http://stackoverflow.com/comment/91318453
type: UnansweredQuestion
has title: Matplotlib figsize behaving strange in WXAgg
tagged with: python
has comment: http://stackoverflow.com/comment/91315331
has comment: http://stackoverflow.com/comment/91317181
has comment: http://stackoverflow.com/comment/91315858
answer count: 0
tagged with: matplotlib
type: Question
has body: Im trying to resize a figure to A4 paper size to save it as pdf. This gives strange behavior when using WXAgg. Here is an example: import matplotlib as mpl mpl.use("WXAgg") import numpy as np import matplotlib.pyplot as plt # data to plot x = np.arange(0, 10, 0.005) y = np.sin(x) # plot the data fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(x, y) # resize figure and immediatly print it's size page_width, page_height = (8.2765, 11.70475) #A4 fig.set_size_inches(page_width, page_height) print fig.get_size_inches() The output I get is [ 8.27 7.59], not as expected. When I comment out the mpl.use("WXAgg"), it works fine. The output then is [ 8.2765 11.70475] as expected. EDIT: Apparently this has something to do with the size of the screen. I changed screens (plugged in a monitor to my laptop) and the output changed to [ 8.27 9.39] What is happening here? And how do I get the right figure size with WXAgg? Some information about my system: OS: macOS High Sierra 10.13.1 python: 2.7.13 Matplotlib: 2.2.3
has comment: http://stackoverflow.com/comment/91316927
has comment: http://stackoverflow.com/comment/91315976
has comment: http://stackoverflow.com/comment/91315803

http://stackoverflow.com/q/52253357
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52253517
has answer: http://stackoverflow.com/a/52253538
accepted answer: http://stackoverflow.com/a/52253538
has comment: http://stackoverflow.com/comment/91454219
type: Question
has comment: http://stackoverflow.com/comment/91454663
tagged with: string
has body: I am trying to output the list as below but the only list I was able to create is a list of chars. Could someone please point me to the right direction please. I cannot use regex here. Content of doc.txt file: Testing tags only Code: with open('doc.txt', 'r') as f: empty_tag_list = [] # loop through all lines using f.readlines() method for line in f.readlines(): new_line = [] # this is how you would loop through each alphabet isTag = False for chars in line: if chars =="<": isTag = True if isTag ==True: empty_tag_list.append(chars) if chars ==">": isTag = False empty_tag_list.append(new_line) empty_tag_list.remove("<") empty_tag_list.remove(">") print(empty_tag_list) Output: ['h', 't', 'm', 'l', [], 'h', 'e', 'a', 'd', [], 't', 'i', 't', 'l', 'e', [], '/', 't', 'i', 't', 'l', 'e', [], '/', 'h', 'e', 'a', 'd', [], 'b', 'o', 'd', 'y', [], '/', 'b', 'o', 'd', 'y', [], '/', 'h', 't', 'm', 'l', []] How can I have the output as : [html,head,title,/title,/head,body,/body,/html]
score: 0
possible better answer: http://stackoverflow.com/a/52253517
answer count: 3
has answer: http://stackoverflow.com/a/52253719
upvote count: 1
downvote count: 1
tagged with: python
favorite count: 0
tagged with: python-3.x
has title: Python how to split and join chars of characters in a list

http://stackoverflow.com/comment/91382048
type: QuestionComment
has text: You are missing a close parentheses at the right side of `ny_vare1_pris = float(input("Hvor mye koster varen? ")`. Python (and other compilers) only report a syntax error on the line it is detected, not necessarily the line in error.
score: 9
type: Comment
comment on: http://stackoverflow.com/q/52216652

http://stackoverflow.com/comment/91458436
type: Comment
type: AnswerComment
has text: Can you comment on why `int` conversion is required? The docs say that ranks are 1 to *n*. So I believe `rank` should only ever output integers. For dense specifically, `rank always increases by 1 between groups`.
score: 0
comment on: http://stackoverflow.com/a/52255586

http://stackoverflow.com/q/52143556
favorite count: 0
tagged with: python
has body: I am trying to calculate one-step, two-step transition probability matrices for a sequence as shown below : sample = [1,1,2,2,1,3,2,1,2,3,1,2,3,1,2,3,1,2,1,2] import numpy as np def onestep_transition_matrix(transitions): n = 3 #number of states M = [[0]*n for _ in range(n)] for (i,j) in zip(transitions,transitions[1:]): M[i-1][j-1] += 1 #now convert to probabilities: for row in M: s = sum(row) if s &gt; 0: row[:] = [f/s for f in row] return M one_step_array = np.array(onestep_transition_matrix(sample)) My question, how do we calculate two step transition matrix. because when I manually calculate the matrix it is as below : two_step_array = array([[1/7,3/7,3/7], [4/7,2/7,1/7], [1/4,3/4,0]]) However. np.dot(one_step_array,one_step_arrary) gives me a result which is different and as follows : array([[0.43080357, 0.23214286, 0.33705357], [0.43622449, 0.44897959, 0.11479592], [0.20089286, 0.59821429, 0.20089286]]) Please let me know which one is correct.
score: 2
type: AnsweredQuestion
has title: Markov Transition Probability Matrix Implementation in Python
downvote count: 0
tagged with: scipy
type: Question
tagged with: markov
has answer: http://stackoverflow.com/a/52143886
accepted answer: http://stackoverflow.com/a/52143886
upvote count: 2
tagged with: numpy
tagged with: matrix
answer count: 1

http://stackoverflow.com/comment/91375379
type: Comment
has text: Getting the same error : ImportError: cannot import name 'WordCloud'
comment on: http://stackoverflow.com/q/52212770
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91274600
has text: @mikuszefski Nice hint! I will try to test it. Concerning the indentation, I have written all the code after 4 spaces. Don't know why it looks like that!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52146955

http://stackoverflow.com/comment/91364665
comment on: http://stackoverflow.com/a/52142873
score: 0
type: AnswerComment
has text: you could just pass in your `df` as in `train_test_split(df, test_size=0.3, shuffle=False)`
type: Comment

http://stackoverflow.com/q/52267157
downvote count: 0
has answer: http://stackoverflow.com/a/52267219
favorite count: 0
tagged with: series
has title: How to find values that occur specific number of times in Pandas Series?
accepted answer: http://stackoverflow.com/a/52267174
tagged with: python
answer count: 4
type: AnsweredQuestion
upvote count: 3
possible better answer: http://stackoverflow.com/a/52267204
has answer: http://stackoverflow.com/a/52267236
has answer: http://stackoverflow.com/a/52267204
type: Question
has body: Given the following Series: sr = pd.Series([5, 5, 5, 6, 6, 6, 7, 7, 8, 8, 8]) I want to find the values that occur 3 times. This is my solution which seems to work but looks very strange: (sr.value_counts() == 3)[sr.value_counts() == 3].index.values Is there any other/obvious way I am missing?
tagged with: counter
has answer: http://stackoverflow.com/a/52267174
tagged with: pandas
score: 3

http://stackoverflow.com/q/52258367
has comment: http://stackoverflow.com/comment/91464681
tagged with: unit-testing
type: Question
has title: Python Unittest: Assert information sought for negative test case
has comment: http://stackoverflow.com/comment/91464218
score: 1
tagged with: python-unittest
tagged with: testcase
has body: my case is a bit more complicated. I have several tests that check for certain login procedures on routers and switches. Setup: import testcore (package that used Paramiko) from testcore.control.ssh import SSH import unittest from test import support import logging import os Here can you see one of my testcases: def test_create_user_ENFORCE_2(self): if self.s.login(): q=self.s.query('account') self.assertIsNotNone(q, 'missing answer') #self.assertEqual('\r\n', q, 'unexpected result') # switch to prompt account q=self.s.query('add 15 testuser_ENFORCE_P1 ') self.assertIsNotNone(q, 'missing answer') #self.assertEqual('\r\n', q, 'unexpected result') self.assertTrue('class str') #self.assertTrue('The Password does not comply' != '\r\n\rERROR! The Password does not comply[240 chars]ar\n') #self.assertIs : True('The Password does not comply', q, 'add 15 testuser_ENFORCE_P1') print(type(q)) q=self.s.query('logout') self.s.close() The test works as it should. He starts a login on the respective router / switch and executes a command on the prompt. The problem is this: The test should check if I u.a. Special characters can use as a password. If so, the test is failed. The positive test would be that I can not create an account that contains special characters. The only help after the current issue, I receive the following message on the router / switch 'The Password does not comply' != '\r\n\rERROR! The Password does not comply[240 chars]ar\n' How and with which assert can I do the most?
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52270956
type: UnansweredQuestion

http://stackoverflow.com/a/65729756
has body: Regenerate CA file using openssl with stronger hash(such as sha256 ) to sing like this: openssl genrsa -out private/cakey.pem 3072 openssl req -new -sha256 -key private/cakey.pem -out private/ca.csr -subj "/C=CN/ST=envoy-test/L=envoy-test/O=envoy-test/OU=envoy-test/CN=envoy-test" openssl x509 -req -days 3650 -sha256 -extensions v3_ca -signkey private/cakey.pem -in private/ca.csr -out certs/ca.cer
answers question: http://stackoverflow.com/q/52218876
downvote count: 0
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/comment/91275237
type: AnswerComment
comment on: http://stackoverflow.com/a/52162730
score: 0
type: Comment
has text: That is logical, the `author` is not part of your form, but required, since it can not be `None`/`NULL`.

http://stackoverflow.com/q/52199998
has body: The function calls in search_a_record, which in turn calls in find_a_record and display_a_record The self.__records is the list of Contact objects: : [Contact(John,7589943,john@amail.com), Contact(Kelly,4344345,kelly@bmail.com), Contact(Nicky,8774104,nicky@cmail.com), Contact(Sam,5723943,sam@dmail.com)] The items in self.__records are stored as "Contact" objects. If the name is in the "Phonebook" then the "Contact" object needs to be returned by the find_a_record function. I am iterating over the object and comparing the name but getting error, what am I doing wrong? 1. Look up a contact 2. Add a new contact 3. Change an existing contact 4. Delete a contact 5. Display all contacts 6. Quit the program ------------------------------------------------ Enter your choice: 1 ------------------------------------------------ Enter the name: John Traceback (most recent call last): File "/Users/rizwanrenesa/Documents/A1/A1Q1Resource/A1Q1rene001.py", line 91, in &lt;module&gt; main() File "/Users/rizwanrenesa/Documents/A1/A1Q1Resource/A1Q1rene001.py", line 87, in main menu(contacts) File "/Users/rizwanrenesa/Documents/A1/A1Q1Resource/A1Q1rene001.py", line 59, in menu contacts.search_a_record() File "/Users/rizwanrenesa/Documents/A1/A1Q1Resource/PhoneBook.py", line 82, in search_a_record name = input("Enter the name: ") File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'John' is not defined class Contact: def __init__(self, name, phone, email): self.__name = name # the full name self.__phone = phone # the phone number self.__email = email # the email address def get_name(self): return self.__name #Finds a record def find_a_record(self, name): for contact in self.__records: # type: object if contact.get_name() == name: return contact return None def display_a_record(self, item): print("Name:{}".format(item.get_name())) print("Phone:{}".format(item.get_name())) print("Email:{}".format(item.get_name())) # This function searches and displays a contact record. def sea…
type: AnsweredQuestion
score: 1
upvote count: 1
has title: Iterating over python object is 2.7. Showing error not found
type: Question
has comment: http://stackoverflow.com/comment/91349031
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91352164
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/52200177
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52200177

http://stackoverflow.com/a/56033831
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52145452
accepted answer of: http://stackoverflow.com/q/52145452
score: 0
has body: Today I hit this issue again, and I deleted the original file, created a new one, and typed the sql command. Everything works like a charm now. My guess is that the original file contains some invisible characters which caused this issue. But why they exist there still puzzled me.

http://stackoverflow.com/q/52220426
type: AnsweredQuestion
type: Question
possible better answer: http://stackoverflow.com/a/71240295
has answer: http://stackoverflow.com/a/71240295
tagged with: scikit-learn
has body: I have the following function that uses a specific method of sklearn.preprocessing. from sklearn import preprocessing def process (data): method = preprocessing.MinMaxScaler() tranf = method.fit_transform(data) return tranf What I would like to have is a function that is able to call any method from sklearn.preprocessing. It would look this. from sklearn import preprocessing def process (data, whichmethod): method = preprocessing.whichmethod() tranf = method.fit_transform(data) return tranf Please educate me on python and apologies, since I do get the feeling that this is super simple.
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52220555
has title: Scikit-learn methods inside functions
accepted answer: http://stackoverflow.com/a/52220555
tagged with: python

http://stackoverflow.com/comment/91482237
type: Comment
has text: Can you explain or give a reference to how a function works in `loc[]`?
type: AnswerComment
comment on: http://stackoverflow.com/a/52267219
score: 0

http://stackoverflow.com/comment/91245320
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52115952
has text: sorry missed the import function. I have imported the file in my unit test code as updated now..

http://stackoverflow.com/comment/91243768
has text: So still you can use the first part to iterate through all files in the folder using os and then apply something according to your need.
type: Comment
comment on: http://stackoverflow.com/a/52141097
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91472688
type: QuestionComment
has text: The book said that because the file is not exe, I needed to type the quoted line to finish the installment process.
comment on: http://stackoverflow.com/q/52261995
score: 0
type: Comment

http://stackoverflow.com/a/52204820
has comment: http://stackoverflow.com/comment/91515043
type: Answer
has comment: http://stackoverflow.com/comment/91361818
has comment: http://stackoverflow.com/comment/91476891
has comment: http://stackoverflow.com/comment/91501213
has body: If I try your code, and then list the attributes you have: import requests url = ("https://www.example.com/profile/10100") headers = {"user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"} r = requests.get(url, headers=headers) dir(r) ['attrs', 'bool', 'class', 'delattr', 'dict', 'dir', 'doc', 'enter', 'eq', 'exit', 'format', 'ge', 'getattribute', 'getstate', 'gt', 'hash', 'init', 'iter', 'le', 'lt', 'module', 'ne', 'new', 'nonzero', 'reduce', 'reduce_ex', 'repr', 'setattr', 'setstate', 'sizeof', 'str', 'subclasshook', 'weakref', '_content', '_content_consumed', '_next', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers', 'history', 'is_permanent_redirect', 'is_redirect', 'iter_content', 'iter_lines', 'json', 'links', 'next', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url'] I don't see html, that's why you get an attr error. Now the important part, if you check r.status_code (the response status code) In [107]: r.status_code Out[107]: 404 Which is a not found error, basically your specified url does NOT exist, or at least it is not visible for me.
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91417782
has comment: http://stackoverflow.com/comment/91358869
has comment: http://stackoverflow.com/comment/91501292
accepted answer of: http://stackoverflow.com/q/52204743
has comment: http://stackoverflow.com/comment/91507558
upvote count: 1
answers question: http://stackoverflow.com/q/52204743
type: AcceptedAnswer

http://stackoverflow.com/comment/91438888
type: QuestionComment
comment on: http://stackoverflow.com/q/52245309
score: 0
has text: You are using multiprocessing. It is different than multithreading. Threads are sharing memory, processes are not. For pure python parallel program, you want to use multiprocessing because of the Global Interpreter Lock (GIL). Not knowing selenium, I do not know why this error was raised, but could you tell us which line raised it, the `zip()` or the `map()`?
type: Comment

http://stackoverflow.com/a/52153953
downvote count: 0
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/52151553
has body: @ikolim is correct, but there is a very ugly and not recommended way to accomplish what you want: import weakref old = Label() self.ids.add_widget(old) self.ids['old'] = weakref.ref(old) This actually adds the old id to the dictionary (assuming self is the correct container). A better way would be to just keep a reference to the old Label.
type: Answer

http://stackoverflow.com/comment/91384488
type: QuestionComment
comment on: http://stackoverflow.com/q/52217866
has text: in which line you are getting error?
score: 0
type: Comment

http://stackoverflow.com/a/52236664
accepted answer of: http://stackoverflow.com/q/52234614
answers question: http://stackoverflow.com/q/52234614
type: Answer
has comment: http://stackoverflow.com/comment/91429467
has comment: http://stackoverflow.com/comment/91437752
upvote count: 1
score: 1
has body: You can utilize py_to_asm (disclamer: I wrote the library) to generate x86-64 assembly with at&amp;t syntax. You can create assembly programs by creating an instance of the py_to_asm.Asm class with a contextmanager or through simple instantiation. By using the contextmanager, a main label can be created: import py_to_asm with py_to_asm.Asm(_label_name = '_main', is_main=True) as asm: #assembly to add two values asm.mov(asm.register.EAX, asm.integer(2)) asm.mov(asm.register.EDX, asm.integer(5)) asm.add(asm.register.EAX, asm.register.EDX) print(asm) Output: .data .text .globl _main _main: pushq %rbp movq %rsp, %rbp subq $16, %rsp movl $2, %eax movl $5, %edx addl %edx, %eax leave ret You can also instantiate the py_to_asm.Asm class merely to create variables, registers, and values: _asm = py_to_asm.Asm() all_registers = _asm.register.__class__.registers register_storage = _asm.register.EAX.__class__.converter eax = _asm.register.EAX edx = _asm.register.EDX val = _asm.integer(2) print(all_registers) print(register_storage) print(eax, edx, val) Output: ['RAX', 'RCX', 'RDX', 'RBX', 'RSP', 'RBP', 'RSI', 'RDI', 'EAX', 'ECX', 'EDX', 'EBX', 'ESP', 'EBP', 'ESI', 'EDI', 'AX', 'CX', 'DX', 'BX', 'SP', 'BP', 'SI', 'DI', 'AH', 'AL', 'CH', 'CL', 'DH', 'DL', 'BH', 'BL'] {'RAX': 64, 'RCX': 64, 'RDX': 64, 'RBX': 64, 'RSP': 64, 'RBP': 64, 'RSI': 64, 'RDI': 64, 'EAX': 32, 'ECX': 32, 'EDX': 32, 'EBX': 32, 'ESP': 32, 'EBP': 32, 'ESI': 32, 'EDI': 32, 'AX': 16, 'CX': 16, 'DX': 16, 'BX': 16, 'SP': 16, 'BP': 16, 'SI': 16, 'DI': 16, 'AH': 8, 'AL': 8, 'CH': 8, 'CL': 8, 'DH': 8, 'DL': 8, 'BH': 8, 'BL': 8} %eax %edx $2 To create an executable from the assembly generated, first write the generated contents to a file: with asm.write('garbage_code.s'): pass Then, in terminal/command line, run: gcc garbage_code.s -o garbage_executable garbage_executable is now the name of the executable file.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91280246
type: Comment
comment on: http://stackoverflow.com/a/52164805
has text: If I do something like `file:///D:\results`, where D is the drive label on Windows and results folder is accessible to python script, it raises an `OSError` because the filename which open method uses is `/D:\\results\\.abc-xxx-xxx-xxx`. Does it work for you? Moreover, I'm not using the windows subsystem as well. It might be you're running this under linux, maybe?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91291306
type: Comment
has text: Thank you. Does this mean the directory that contains all the files related to the package? Could you tell me how I find this?
type: AnswerComment
comment on: http://stackoverflow.com/a/52157889
score: 0

http://stackoverflow.com/q/52173787
type: AnsweredQuestion
tagged with: openai-gym
has answer: http://stackoverflow.com/a/52174002
type: Question
tagged with: anaconda
has body: I am trying to use the retro module and I jupyter notebooks I seemed to install it with a !pip install retro where it went thru the download/install ok. But when I try to import retro I get an error ` Traceback (most recent call last): File "/home/benbartling/anaconda3/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-1-81066d3a41c5&gt;", line 1, in &lt;module&gt; import retro File "/home/benbartling/anaconda3/lib/python3.6/site-packages/retro/__init__.py", line 206 print "%s: %s" % (key, value) ^ SyntaxError: invalid syntax Would anyone have any ideas? Thank you
upvote count: 5
has title: python openAI retro module
score: 5
accepted answer: http://stackoverflow.com/a/52174002
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/91453334
type: QuestionComment
has text: @101 to clarify - CompileImages is a function which then runs another function which in turn starts Opening and Pasting images into each other using PIL. The issue isn't with these functions at all other than that they lock up the interface while they do their work. Can I use a time delay to ensure the SwapImages line is 100% executed before the next line is?
comment on: http://stackoverflow.com/q/52251549
score: 0
type: Comment

http://stackoverflow.com/q/52145707
upvote count: 1
has comment: http://stackoverflow.com/comment/91241375
linked to: http://stackoverflow.com/q/44958544
tagged with: python
has comment: http://stackoverflow.com/comment/91272780
favorite count: 0
has comment: http://stackoverflow.com/comment/91716407
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91281085
has comment: http://stackoverflow.com/comment/138492290
tagged with: exchange-server
has title: Python Exchangelib / How to access public folders
tagged with: public-folders
score: 1
type: Question
has body: I'm having some problems trying to connect to a public folder with exchangelib. I'm using Python 3.6 and exchangelib 1.11.4. I'm already connected and I'm able to load mails from the inbox. I'm trying to access the public folders like this: account.public_folders_root.children My problem is that children returns a FolderCollection, and if I call the .len() method it always returns 0, so the FolderCollection is empty; it doesn't find any child folders. If I execute the following: account.public_folders_root.absolute it returns: /IPM_SUBTREE. I'm not sure if that's the right path for my public folders.
downvote count: 0
tagged with: exchangelib
has comment: http://stackoverflow.com/comment/91273014

http://stackoverflow.com/comment/119741313
type: Comment
has text: This is not really a solution and your answer is out of scope. So what you're implying is that "no it's not possible because Pandas did not build an interface to interact the index like a column". If yes, then let this be the answer. Now a natural followup question is why not? We've seen other software being able to do this like SQL .
score: 5
type: AnswerComment
comment on: http://stackoverflow.com/a/52139621

http://stackoverflow.com/comment/91228074
type: QuestionComment
type: Comment
has text: Presumably `nullstelle(f,a,b,counter,TOL)` should be `return nullstelle(f,a,b,counter,TOL)`
comment on: http://stackoverflow.com/q/52139225
score: 1

http://stackoverflow.com/a/52251065
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52250852
downvote count: 0
has comment: http://stackoverflow.com/comment/91667714
answers question: http://stackoverflow.com/q/52250852
has comment: http://stackoverflow.com/comment/91667670
has body: try using CountVectorizer from sklearn.feature_extraction.text import CountVectorizer clf = CountVectorizer() X_train_one_hot = clf.fit(X_train) X_test_one_hot = clf.transform(X_test) bnbc = BernoulliNB(binarize=None) bnbc.fit(X_train_one_hot, y_train) score = bnbc.score(X_test_one_hot, y_test) print("score of Naive Bayes algo is :" , score) Also you can try using TfidfVectorizer in case if you are going to use TfIdf featurization of text.
has comment: http://stackoverflow.com/comment/91450080
score: 1
has comment: http://stackoverflow.com/comment/91450147
upvote count: 1

http://stackoverflow.com/comment/91470428
has text: You can test for existence. If `unicode_literals` has been imported for example, is is defined whereas null if not imported.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52261195

http://stackoverflow.com/comment/91318379
has text: your function is missing the optional `return` statement so it returns the default `None`. if the `print` happens inside the function, remove it from outside and just do `remove_capitals("A1B2C3D")`. Otherwise, instead of printing inside, return it and print it outside.,
comment on: http://stackoverflow.com/q/52184372
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/comment/91190597
score: 3
has text: What error are you getting? Is the problem the non-ASCII quotes you are using here?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52119760

http://stackoverflow.com/comment/91263038
comment on: http://stackoverflow.com/q/52156319
score: 2
has text: What issues are you currently having implementing this?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52248391
downvote count: 3
has answer: http://stackoverflow.com/a/52248681
has body: So I'm trying to allow my user to input \n in a string, to designate a new line. However for some reason that is translated into '\\n'. So I can do: inp = input().replace("\\n", "\n") but that seems a little cumbersome; is there a better way?
accepted answer: http://stackoverflow.com/a/52248681
type: Question
has comment: http://stackoverflow.com/comment/91445277
has comment: http://stackoverflow.com/comment/91444697
tagged with: newline
has comment: http://stackoverflow.com/comment/91445113
has title: Is there a way to stop input() from escaping \n?
score: 0
linked to: http://stackoverflow.com/q/51646673
has comment: http://stackoverflow.com/comment/91444661
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91445337
tagged with: python-3.x
tagged with: input
tagged with: python
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/comment/91273452
comment on: http://stackoverflow.com/q/52161826
has text: Ah so the redirect wouldn't work from the function I call? I have to initiate it directly in the view?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91196888
score: 1
has text: @divibisan you don't make askers' code testable! You don't even make it _runnable_. You'll never know if you're making part or all of the problem disappear.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52121773

http://stackoverflow.com/comment/91477478
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52264668
type: Comment
has text: You are technically correct...it is a mistake in my question, I actually wanted the positive distance..that means `mod(index1-a)`..sorry my bad..your answer is quite nice

http://stackoverflow.com/comment/91423770
type: Comment
type: QuestionComment
has text: @user9074332 I tried mockaroo, however I am limited to only a 1000 rows, but it was what I am looking for. Checking out faker thank you .
comment on: http://stackoverflow.com/q/52236463
score: 0

http://stackoverflow.com/q/52190685
has comment: http://stackoverflow.com/comment/91331767
type: Question
score: 2
has title: Regex: Negating entire word instead of 1 character
answer count: 1
has comment: http://stackoverflow.com/comment/91331673
has comment: http://stackoverflow.com/comment/91331183
has comment: http://stackoverflow.com/comment/91331723
has body: If I do [^>] it negates characters that look like >. How do I negate an entire word? I.e. I want to do something like [^people] to ignore the entire word people? Edit #1: better example a bunch of other text before this select col_1, col_2, from dbo.table a bunch of other text after this Right now, it only returns this: <property datatype = ""system.string"" description=""the sql command to be executed."" name=""sqlcommand But I want it to return this: select col_1, col_2, from dbo.table
tagged with: python
has comment: http://stackoverflow.com/comment/91331135
tagged with: regex
has comment: http://stackoverflow.com/comment/91332156
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52190756
downvote count: 1
has comment: http://stackoverflow.com/comment/91332671
has comment: http://stackoverflow.com/comment/91332112
has comment: http://stackoverflow.com/comment/91331413
upvote count: 3
has comment: http://stackoverflow.com/comment/91331166

http://stackoverflow.com/a/52212608
has body: Change this line: GPIO.add_event_detect(inbutton, GPIO.FALLING, callback=zest(), bouncetime=1000) to this: GPIO.add_event_detect(inbutton, GPIO.FALLING, callback=zest, bouncetime=1000) As you have it, the callback is called once when registering it and registered callback is saved as None since that is what was returned by zest(). The callback also needs to accept a single argument: channel. So change your function definition to: def zest(channel):
has comment: http://stackoverflow.com/comment/91374996
has comment: http://stackoverflow.com/comment/91407656
has comment: http://stackoverflow.com/comment/91375180
answers question: http://stackoverflow.com/q/52212539
type: Answer
score: 0

http://stackoverflow.com/q/52123501
downvote count: 0
tagged with: string
has answer: http://stackoverflow.com/a/52123573
type: Question
tagged with: python
tagged with: regex
favorite count: 0
upvote count: 2
answer count: 2
accepted answer: http://stackoverflow.com/a/52123573
possible better answer: http://stackoverflow.com/a/52123602
has answer: http://stackoverflow.com/a/52123602
has body: I have a string with placeholders and I want to attach an index to wach of the placeholders. e.g. 'This @placeholder is @placeholder' Should become 'This @param0 is @param1' Assuming I have a list of params with 2 values(matches the number of time @placeholder occurs) . One optional solution would be. result = '' parts = my_text.split('@placeholder') for i in range(0, len(params)): result += '{}@param{}'.format(parts[i], i) return result Another option is to keep replacing the placeholder with the current index, but this means scanning the string len(params) times. for i in range(0, len(params)): my_text = my_text.replace('@placeholder', '@param{}'.format(i), 1) is there a better solution for doing this in python?
has title: Replace every occurrence of a string with the number of times it has occurred so far
tagged with: replace
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/52140654
has answer: http://stackoverflow.com/a/52141097
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91254837
tagged with: openpyxl
tagged with: excel
has title: Taking Same Worksheet from a Folder of xlsm Files with Python
has body: I'm new to pandas/python and Ive come up with the following code to extract data from a specific part of a worksheet. import openpyxl as xl import pandas as pd rows_with_data = [34,37,38,39,44,45,46,47,48,49, 50,54,55,57,58,59,60,62,63,64,65,66,70,71,72,76,77, 78,79,80,81,82,83,84,88,89,90,91,92] path = r'XXX' xpath = input('XXX') file = r'**.xlsm' xfile = input('Change file name, current is ' + file + ' :') sheetname = r'Summary' wb = xl.load_workbook(filename = xpath + '\\' +file, data_only = True) sheet = wb.get_sheet_by_name(sheetname) rows = len(rows_with_data) line_items = [] for i in range(rows) : line_items.append(sheet.cell(row = rows_with_data[i], column = 13).value) period = [] for col in range(17,35): period.append(sheet.cell(row = 20, column = col).value) print(line_items) vals = [] x = [] for i in range(rows): if i != 0: vals.append(x) x = [] for col in range(17,35): x.append(sheet.cell(row = rows_with_data[i], column = col).value) vals.append(x) all_values = {} all_values['Period'] = period for i in range(rows): print(line_items[i]) all_values[line_items[i]] = vals[i] print(all_values) period_review = input('Enter a period (i.e. 2002): ') item = input('Enter a period (i.e. XXX): ') time = period.index(period_review) display_item = str(all_values[item][time]) print(item + ' for ' + period_review + " is " + display_item) Summary_Dataframe = pd.DataFrame(all_values) writer = pd.ExcelWriter(xpath + '\\' + 'values.xlsx') Summary_Dataframe.to_excel(writer,'Sheet1') writer.save() writer.close() I have the same worksheet (summary results) across a library of 60 xlsm files and I'm having a hard time figuring out how to iterate this across the entire folder of files. I also want change this from extracting specific rows to taking the entire "Summary" worksheet, pasting it to the new file and naming the worksheet by its filename ("Experiment_A") when pasted to the new excel file. Any advice?
type: Question
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91241681
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/91275973
has text: Can you write how to work with the loop ?What changed needed?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52163201

http://stackoverflow.com/comment/91327959
type: QuestionComment
comment on: http://stackoverflow.com/q/52188866
has text: PEP 8 is a guideline. You are free to follow it or not. In general following it will make things easier but as the PEP 8 itself points out: you project requirements should have precedence over the PEP rules. So if you have a **specific** question about a rule, please ask. If you just want to hear some opinions on the rules there, then sorry but SO is not the right place for it.
score: 1
type: Comment

http://stackoverflow.com/q/52169733
accepted answer: http://stackoverflow.com/a/52169772
tagged with: if-statement
tagged with: pandas
score: 3
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52169901
has answer: http://stackoverflow.com/a/52169772
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/52170126
possible better answer: http://stackoverflow.com/a/52170086
type: AnsweredQuestion
has title: Python Pandas if column id value greater
has answer: http://stackoverflow.com/a/52170086
has body: I have what i think is a simple quesiton, but I am not sure how to implement. I have the following dataframe: ID Value 1 100 2 250 3 300 4 400 5 600 7 800 I would like to look at 2 id's: 3 &amp; 5 and then drop the one with the lower value. So i am assuming I would use something like the following code, but again, i am not sure how to implement,nor am i sure how to utilize the inequality to point towards the value while directing my function at a very specific pair of id's. def ChooseGreater(x): if df['id'] == 3 &gt; df['id'] ==5 return del df['id']==5 else: return del df['id']==3 Thank you!
upvote count: 3
type: Question

colorbar
tags question: http://stackoverflow.com/q/52205416
tags question: http://stackoverflow.com/q/52114655
tags question: http://stackoverflow.com/q/52269771
tags question: http://stackoverflow.com/q/52239625
tag name: colorbar
tags question: http://stackoverflow.com/q/52165938
type: Tag
tags question: http://stackoverflow.com/q/52209778

http://stackoverflow.com/comment/91178630
has text: How about (2) btw.. I put a conditional check, which leaves out loading of app module whenever main.py is run in child process. But still app module, and hence middleware module is getting loaded. How is this possible?
comment on: http://stackoverflow.com/q/52113978
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91263460
has text: Hmm, you're right. But the idea still works, I think. If `sys.argv` is either `['']` or `['-']`, you know PYTHONSTARTUP is executed.
type: Comment
comment on: http://stackoverflow.com/q/52156289
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91467195
has text: You need to read https://stackoverflow.com/help/how-to-ask before asking a question. Were here to help, not teach. Please add your code from what you've already attempted and the issue that is coming up from your code. I would be happy to help you at that point.
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52259882

http://stackoverflow.com/comment/91338236
type: QuestionComment
has text: Potentially float numbers or strictly integers?
comment on: http://stackoverflow.com/q/52194235
score: 0
type: Comment

http://stackoverflow.com/comment/91189267
type: Comment
type: QuestionComment
has text: for i in tag[0].find_all('li'): e = i.text
score: 1
comment on: http://stackoverflow.com/q/52119110

http://stackoverflow.com/a/52129178
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91208792
downvote count: 0
has comment: http://stackoverflow.com/comment/91208773
type: Answer
answers question: http://stackoverflow.com/q/52129128
has body: You can't have a default that involves a query on the database. That will always be executed on first import, so the migration that creates the table will never have a chance to run. Remove the default.

http://stackoverflow.com/q/52231715
has body: I have n number of dates defined in this below model in the database, these are directly inserted by admin, not by modelforms or anything. class Calendar(models.Model): date = models.DateField() occasion = models.CharField(max_length = 20) the form that has the date fields, class LeaveRequestForm(ModelForm): class Meta: fields = (... "from_date", "to_date" ...) model = Leave widgets = { ... 'from_date' : DateInput(attrs={'class': 'datepicker'}), 'to_date' : DateInput(attrs={'class': 'datepicker'}), ... } I have this datepicker script which disable weekends, &lt;script&gt; $(document).ready(function() { $('.datepicker').datepicker( { minDate : 0, beforeShowDay : $.datepicker.noWeekends } ); }); &lt;/script&gt; Now I want to disable the dates defined in the database + weekends as well. How do I do that? update : var array = {{ {% for x in disabled_dates %} {{x.dates}} {% endfor %} }} $('datepicker').datepicker({ beforeShowDay: function(date){ var string = jQuery.datepicker.formatDate('yy-mm-dd', date); return array.indexOf(string) != -1 ? [false] : $.datepicker.noWeekends(date); } }); No luck yet!
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91416784
has answer: http://stackoverflow.com/a/52234721
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/91417741
has comment: http://stackoverflow.com/comment/91417841
type: Question
has comment: http://stackoverflow.com/comment/91417821
tagged with: javascript
has comment: http://stackoverflow.com/comment/91416933
has title: django : How to disable dates in datepicker, based on the entries form db?
linked to: http://stackoverflow.com/q/15400775
answer count: 1
downvote count: 0
score: 1
tagged with: jquery
favorite count: 0
linked to: http://stackoverflow.com/q/14484159

http://stackoverflow.com/q/52182322
has body: I am working with the FacetGrid example presented here that results in the plot below. In my data set, there is quite a lot of plots, and it would be convenient to have the x axis labels repeated for each facet, not only at the bottom. For this example, the values 62, ..., 76 should be repeated for each of the A-J facets.
tagged with: matplotlib
type: Question
has answer: http://stackoverflow.com/a/52184614
upvote count: 20
has answer: http://stackoverflow.com/a/52182623
accepted answer: http://stackoverflow.com/a/52184614
answer count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/52182623
has title: Repeating x axis labels for all facets using FacetGrid in seaborn
favorite count: 0
tagged with: facet-grid
score: 20
tagged with: seaborn
has answer: http://stackoverflow.com/a/78706969
tagged with: python
tagged with: plot
type: AnsweredQuestion

http://stackoverflow.com/q/52245414
answer count: 1
has comment: http://stackoverflow.com/comment/91577741
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91506736
tagged with: pyinstaller
type: UnansweredQuestion
has title: Compare two PyInstaller generated Linux executables in Python
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/52323144
has comment: http://stackoverflow.com/comment/91576538
has comment: http://stackoverflow.com/comment/91597694
upvote count: 7
has comment: http://stackoverflow.com/comment/91521525
has body: The problem is quite simple, but I don't see any sample. I need to compare two executables generated by PyInstaller and determine which one is newer (but not by simple timestamp). Timestamp might be newer, but the content stays the same. I need to replace the old file only if both timestamp is newer and the content is different. Any example solution? For example simple version tag in PyInstaller (strange but can't find much info on it, in manual it says only about using Windows version files) update: Linux executables Have access to files generation process. it is cli app and best is not to use vcs, some simple solution. actual comparison process will take place in a Python script tried filecmp as suggested - it returns False even for the same build generated 2 times (with shallow=False flag). Best option as to my point of view is to compare content &amp; timestamp. if timestamp is newer and the content is different => means new version.
type: Question
has comment: http://stackoverflow.com/comment/91628470
has comment: http://stackoverflow.com/comment/91548137
score: 6
has comment: http://stackoverflow.com/comment/91585244
has comment: http://stackoverflow.com/comment/91506980

http://stackoverflow.com/a/52217824
upvote count: 2
has body: Are you still use pytorch 0.3? if yes, the following snippet may help tensor = var.data
accepted answer of: http://stackoverflow.com/q/52217422
answers question: http://stackoverflow.com/q/52217422
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/q/52162549
downvote count: 1
has comment: http://stackoverflow.com/comment/91274576
linked to: http://stackoverflow.com/q/13638898
accepted answer: http://stackoverflow.com/a/52162586
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/91274585
has title: how to incorporate 'if' condition into for loop statement
type: AnsweredQuestion
favorite count: 0
has answer: http://stackoverflow.com/a/52162666
has body: data = [(1,'hi'),(2,'hello'),(3,'hi'),(4,'hi'),(5,'hello'),(6,'hello'), (7,'hi'),(8,'hello')] new_data = [] for i in data: if i[1] == 'hi': new_data.append(i) print(new_data) output:[(1, 'hi'), (3, 'hi'), (4, 'hi'), (7, 'hi')] i am a beginner in python. i want the same output but want to reduce the amount of code in the'For' loop and be more efficient.
type: Question
has answer: http://stackoverflow.com/a/52162586
tagged with: python
possible better answer: http://stackoverflow.com/a/52162666
score: 0
answer count: 2
upvote count: 1

http://stackoverflow.com/comment/91429686
type: Comment
type: QuestionComment
has text: I would like to remove all array([0, 0])
comment on: http://stackoverflow.com/q/52240476
score: 0

http://stackoverflow.com/comment/97811221
comment on: http://stackoverflow.com/a/52233771
type: Comment
has text: You forgot to include the actual call to `convexHull` (which in this case is done as `hull = cv2.convexHull(cont)`
type: AnswerComment
score: 2

http://stackoverflow.com/q/52148265
favorite count: 0
has title: Reading in binary file with dtype causes ValueError
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
tagged with: numpy
has body: I have a binary file that I want to read in with a python routine. In order to do so a dtype object is created, which describes how the data looks like. The dtype object that should be created is a dictionary of the form {'field1': ..., 'field2': ..., ...}. The obj then is a tuple of (data-type, offset) - (see numpy documentation). The error now occurs if offset exceeds the range of a C int during creation of the dtype. A minimal example to reproduce the error: dict_tmp = dict() offset = 2281832888 dict_tmp['/timedisc/pressure'] = ('(4096, 4096)&gt;f8', offset) dtype = np.dtype(dict_tmp) ValueError: integer won't fit into a C int If I reduce the offset below the range of a 32bit integer the error vanishes of course. I already tried to cast the offset value to an int64 or uint32 by hand, but this was also not working. As far as I can see the dtype is part of multiarray in numpy and at this point I am a bit lost. Is there any possibility to load the data and circumvent the error?
upvote count: 2
has answer: http://stackoverflow.com/a/52167641
accepted answer: http://stackoverflow.com/a/52167641
answer count: 1

http://stackoverflow.com/a/52216461
answers question: http://stackoverflow.com/q/52216040
score: 1
upvote count: 1
has body: Since you didn't provide details of your program, I'll assume you are wondering if numpy.ndarray is faster than using normal python loop. Yes, it IS much faster. It's called vectorization. It's faster because: It'll be executed by the precompiled C/C++ library and thus faster than executing python script It takes advantage of the architecture of modern CPU. See: link That said, it also depends on what you want to do with it. If you are performing math/matrix operations, than vectorization also provides better readability (since it just looks similar to the equation) and more boost since the operations are mostly numerical. If the operations are not numerical, than you'll get less boost and thus can do it the python way.
downvote count: 0
type: Answer

http://stackoverflow.com/a/52194340
downvote count: 0
answers question: http://stackoverflow.com/q/52194235
type: Answer
has body: Here is one way to do it with list comprehensions: mostFrequentNumber = L[max([(L.count(d), i) for i, d in enumerate(L)])[1]] To break it down: We iterate an enumerated version of the list: i, d in enumerate(L), which will produce tuples with the value and index. Then we create a list of tuples with the count of d and the index, i: (L.count(d), i). We use the Max function to get the one with the highest count. Then we index the list L using the highest value at index [1] in the tuple. This input: L = [1, 1, 1, 2, 3, 4] will then produce 1 as a result, although may not be the most efficient.
score: 1
upvote count: 1

http://stackoverflow.com/a/52162730
has comment: http://stackoverflow.com/comment/91275082
has comment: http://stackoverflow.com/comment/91274934
has comment: http://stackoverflow.com/comment/91275237
has comment: http://stackoverflow.com/comment/91275701
has comment: http://stackoverflow.com/comment/91274979
score: 0
has body: Your form ProjectForm should be a subclass of forms.ModelForm instead of forms.Form class ProjectForm(forms.ModelForm): first_name = forms.CharField(max_length=30, required=True, help_text='Required.') last_name = forms.CharField(max_length=30, required=True, help_text='Required.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') project_name = forms.CharField(max_length=30, required=True, help_text='Required') project_description = forms.CharField(max_length=10000, required=True, help_text='Required.') project_notes = forms.CharField(max_length=1000, required=False, help_text='Optional.') class Meta: model = Project fields = ('first_name', 'last_name', 'email', 'project_name', 'project_description', 'project_notes') Update To add author which is a non nullable ForeignKey, you should add author object before the changes are committed to a database. def project_new(request): if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): project = form.save(commit=False) project.author = request.user project.published_date = timezone.now() project.save() return redirect('blog/project_detail.html', pk=project.pk)
type: Answer
answers question: http://stackoverflow.com/q/52162674

http://stackoverflow.com/q/52128922
tagged with: python
has title: Scrapy: how scrape second HTML page requested through AJAX call
has body: I am new to scrapy and html and I'm trying to create a simple spider to scrape the https://www.mobiel.nl website. I have managed to access the mobile phones pages, e.g. https://www.mobiel.nl/smartphone/apple/iphone-6-32gb I am trying to take information on the plans, such as operator names (taken from the image names), plan names and rates, which are stored in the following containers: &lt;div class="pc-result js-offer" data-offer-id="71-1928-3683-19.0"&gt; I have tried dozens of different ways of writhing the selectors, such as: scrapy shell https://www.mobiel.nl/smartphone# fetch('https://www.mobiel.nl/smartphone/apple/iphone-6-32gb') In [37]: response.xpath('//*[@id="js-compare-results"]/text()') Out[37]: [] In [38]: response.xpath('//*[@id="js-compare-results"]/*') Out[38]: [] In [39]: response.xpath('//*[@id="js-compare-results"]') Out[39]: [] In [40]: response.xpath('//*[@id="js-compare-results"]/div/div[2]/div[2]/div/div[1]/div/div[1]/div[1]/span[1]') Out[40]: [] In [41]: response.xpath('//*[@id="js-compare-results"]/div/div[2]/div[2]/div/div[1]/div/div[1]/div[1]/span[1]').extract() Out[41]: [] I couldnt find a way to get any information, except for the device name, which is : response.xpath('//*[@class="phone-info__phone"]/text()').extract_first() In the end I would like to have something like [device name, operator (e.g. t-mobile), plan (e.g. 1GB), period (e.g. 1 year) rate (e.g. 15€)] Does anyone know how to correctly extract (if possible) such information from this page? Thank you in advance. **Edit 1: spider sourcecode** # -*- coding: utf-8 -*- from scrapy import Spider from scrapy.http import Request from scrapy_splash import SplashRequest import re class TmnlPricecrawlerSpider(Spider): name = 'tmnl_pricecrawler' allowed_domains = ['www.mobiel.nl'] start_urls = ['https://www.mobiel.nl/smartphone#'] def parse(self, response): #Process spartphone pages - for this website, all phones are in the same page, no multi-pages processing needed mobielnl_items = r…
tagged with: scrapy
type: Question
tagged with: web-crawler
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52129873
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/comment/91361181
has text: @NilsWerner This solution will not help, have tried it already.... it looks simple, but it just does not work...(
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52205673
score: 0

http://stackoverflow.com/q/52150172
has body: I am using the Variable explorer in Spyder and clicked the "Remove all Variables" button, How do I undo this and restore all variables. Regards
has comment: http://stackoverflow.com/comment/91252396
has answer: http://stackoverflow.com/a/54955538
has title: "Spyder" Undo "Remove all Variables"
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52151887
has answer: http://stackoverflow.com/a/73820796
has comment: http://stackoverflow.com/comment/91251889
has comment: http://stackoverflow.com/comment/91309993
answer count: 3
has comment: http://stackoverflow.com/comment/91250813
tagged with: spyder
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52151887
has comment: http://stackoverflow.com/comment/91250338
tagged with: python
possible better answer: http://stackoverflow.com/a/54955538

header
type: Tag
tags question: http://stackoverflow.com/q/52215155
tag name: header
tags question: http://stackoverflow.com/q/52172760

http://stackoverflow.com/comment/91482322
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52267018
has text: Do you have any good reason to care if the elements are lists and not tuples..?
score: 0

http://stackoverflow.com/a/52126610
answers question: http://stackoverflow.com/q/52126524
downvote count: 0
score: 1
has body: from time import sleep # Usually you check `i` only once # which means `countdown` defaults to 1 def check(i, countdown = 1): print(i) # If `i` is 5 (or any other arbitrary problematic strange number) if i == 5: sleep(2) # Decide if the program should try it again # if `countdown` is 0, # we stop retrying and continue if countdown &gt; 0: print('Something Failed ...') return check(i, countdown - 1) # main for i in range(0, 20): check(i)
type: Answer
upvote count: 1

http://stackoverflow.com/q/52160432
has title: Issue with Kwargs Color argument
type: UnansweredQuestion
tagged with: python
has body: I've got an issue when triying to plot histogram of the features from a dataset I'm using. I searched a lot on the internet to find how to fix it but I couldn't. If anyone got an idea I'm interested ! dataset_base = pd.read_csv(path_dataset_real, names=names, skiprows=1, delimiter=';') dataset_base = pd.DataFrame(dataset_base) dataset_base['address'] = dataset_base['address'].apply(hexToint) dataset_refl = dataset_base.loc[dataset_base['Res4H'] == 1] dataset_true = dataset_base.loc[dataset_base['Res4H'] == 0] dataset_true = dataset_true.loc[0:571,:] fig, axes = plt.subplots(4,3, figsize=(10,20)) refl = dataset_refl true = dataset_true ax = axes.ravel() for i in range(0,12): _, bins = np.histogram(dataset_base.values[:,i], bins=50) ax[i].hist(refl.values[:,i], bins=bins, color='red', alpha=.5) ax[i].hist(true.values[:,i], bins=bins, color='green', alpha=.5) ax[i].set_title(names[i]) ax[i].set_yticks(()) ax[0].set_xlabel("Feature Magnitude") ax[0].set_ylabel('Frequency') ax[0].legend(["Refls", "Plots"], loc='best') fig.tight_layout() plt.show()
answer count: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91271253
upvote count: 1
has comment: http://stackoverflow.com/comment/91273267
has comment: http://stackoverflow.com/comment/91275034
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91273780
score: 0
has comment: http://stackoverflow.com/comment/91270483
tagged with: histogram
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/91471630
score: 0
has text: Possible duplicate of [Annotate bars with values on Pandas bar plots](https://stackoverflow.com/questions/25447700/annotate-bars-with-values-on-pandas-bar-plots)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52261697

http://stackoverflow.com/comment/91328613
type: AnswerComment
comment on: http://stackoverflow.com/a/52187188
type: Comment
has text: Hi @user2699, thanks! The solution obj.x = obj['x'] will solve for obj['x'] = obj['x'] / 2. print obj.x, obj['x'] but not for: obj.x = obj.x / 2. print obj.x, obj['x'] I am aware of the existence of the record array. In the example I simplified the class to simplify the question, but there is many other methods and attributes that I am trying to add. If I put obj = obj.view(np.recarray), my class type will be a recarray, and it gives me an error if I try to apply the extended methods. Now I am thinking if should I just subclass the recarray, instead of the ndarray?
score: 0

http://stackoverflow.com/q/52157994
upvote count: 1
downvote count: 0
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/91283099
has title: Can an empty MultiIndex be used to slice a DataFrame?
has body: I have a pandas MultiIndex that I'm trying to use to slice a DataFrame. When the MultiIndex is empty, it results in a ValueError: (Pdb) p _ix MultiIndex(levels=[[], [], [], []], labels=[[], [], [], []], names=['foo', 'bar', 'baz', 'raz']) (Pdb) p df.index MultiIndex(levels=[['adni'], ['123', '234'], ['M12_s1', 'M24_s1'], ['CRB', 'CRB_crop', 'PON']], labels=[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0]], names=['foo', 'bar', 'baz', 'raz']) (Pdb) p df.loc[_ix] *** ValueError: operands could not be broadcast together with shapes (0,) (4,) (0,) The names of the two indices match, so from what I understand this slicing should be fine. In some conditions when _ix isn't empty, this works as expected. I can't find anything in the documentation that describes not supporting an empty DataFrame like this though. Am I missing something obvious? Edit: adding concrete example: $ cat so_qc.csv foo,bar,baz,raz,qc pd,andrew,M24_s1,CRB,True pd,andrew,M24_s1,CRB_crop,True $ cat so_df.csv foo,bar,baz,raz,value pd,andrew,M24_s1,CRB,0.701794977111406 pd,andrew,M24_s1,CRB,0.309406238674409 $ python qc = pd.read_csv('so_qc.csv', index_col=[0,1,2,3], squeeze=True) df = pd.read_csv('so_df.csv', index_col=[0,1,2,3]) # This is OK df.loc[ qc.index.intersection(df.index) ] # When I select only False elements from `qc` (which is none of them), ValueError about broadcasting df.loc[ qc[~qc].index.intersection(df.index) ]
type: Question
has comment: http://stackoverflow.com/comment/91266982
tagged with: pandas

http://stackoverflow.com/q/52188589
answer count: 1
tagged with: spectrogram
score: 0
has body: I have computed the mel spectrogram with librosa like that: self.Spectrogram = librosa.feature.melspectrogram(y=self.RawSignal, sr=self.sampling_frequency, n_mels=128, fmax=8000) I need to obtain the corresponding value of a given frequency (say 4400 Hz) in the normalized scale [0,127], since n_mels=128. I have seen that 103 is the corresponding value to 4400 Hz, but I would like a generic formula. PS. it is not the conversion formula from Hz to mels what I am searching for. Thanks in advance
tagged with: python
tagged with: librosa
has title: How to compute "normalized" frequency from Mel Spectrogram?
has answer: http://stackoverflow.com/a/52682891
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52682891
type: Question

http://stackoverflow.com/q/52264349
tagged with: python
linked to: http://stackoverflow.com/q/8628123
has comment: http://stackoverflow.com/comment/91477175
linked to: http://stackoverflow.com/q/2675028
has body: class Country(object): """ Modeling a country immigration. """ def __init__(name, immigrants, population, disease_numbers): self.name = name self.immigrants = immigrants self.population = population self.disease_numbers = disease_numbers I have the follow class , that are more attributes .. Every year the population changes and at the end of x years im trying to built o ordered dictionary that will show me which country have the highest population and the least people with diseases... How do I built a dictionary that updates on every year/ turn and give me this info at the end. How can I get information of the stats on the last turn? Let me clarify the question. All i need is at the end of the simulation to have a ordered dictionary. d = {'self.name' : London ('self.immigrants' : 15000 'self.population' : 500000 'self.disease_numbers' :3000) , 'self.name' : Madrid ('self.immigrants' : 17000 'self.population' : 5000 'self.disease_numbers' :300)} Then be able to pick for example in this case London because of higher number of people with a disease. So thinking through it could almost be a new method that return the city with the higher number of people with the disease.
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91476858
has comment: http://stackoverflow.com/comment/91476863
has answer: http://stackoverflow.com/a/52265231
has comment: http://stackoverflow.com/comment/91476934
has title: Create a dictionary from all instances of a class OOP python
score: 0
has answer: http://stackoverflow.com/a/52264784
has comment: http://stackoverflow.com/comment/91476800
type: UnansweredQuestion

http://stackoverflow.com/comment/91218526
type: Comment
comment on: http://stackoverflow.com/a/52125367
has text: How exactly are you unable to relate this? This is more or less exactly the example that is given at the end of the tutorial: «As usual, a trained model can used be to transform new, unseen documents (plain bag-of-words count vectors) into LDA topic distributions: `doc_lda = lda[doc_bow]`»
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91288950
score: 0
type: Comment
type: QuestionComment
has text: what is your code ?
comment on: http://stackoverflow.com/q/52169137

http://stackoverflow.com/comment/91188022
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52118454
score: 0
has text: If the motivation is not to waste space, the bottom of the image's ticklabels should be aligned with the bottom of the plot's xlabel, right?

http://stackoverflow.com/comment/91426395
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52236547
has text: Yes I realized that was part of the problem after posting. See edit.

http://stackoverflow.com/comment/91190094
has text: I don't get that output at all when I merge on `Date`. Also, it seems that none of the column values in `df1` and `df2` are equal anywhere. It looks like you copied the wrong `df1`
score: 1
comment on: http://stackoverflow.com/q/52119585
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52134374
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/93396579
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52134570
has title: slice a list of strings from index[0] till random index
has answer: http://stackoverflow.com/a/52134536
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91218884
has comment: http://stackoverflow.com/comment/91219054
tagged with: list
has body: I am trying to slice a list of strings from index[0] till a random index. The index number where the slicing needs to end, is always at the index number that holds a "(". The code i'm trying is as follow new_name = [[:x:] if x == "(" else x for x in new_name] I always get invalid syntax error. How can i make this work? thx in advance
type: Question

http://stackoverflow.com/a/52261766
downvote count: 0
has comment: http://stackoverflow.com/comment/91482320
type: AcceptedAnswer
has body: Do you mean something like the following: Figure 1 import matplotlib.pyplot as plt partial_corr_array = np.array([[ 1., 0.52, 0.15, 0.91], [ 0.52, 1., 0.25, -0.25], [ 0.15, 0.25, 1. , -0.06], [ 0.91, -0.25, -0.06, 1. ]]) plt.matshow(partial_corr_array) plt.colorbar() Output Figure 2 Based on this link. Plotting only the lower half of the matrix because it is symmetric across the diagonal. import seaborn as sns f, ax = plt.subplots(figsize=(6, 5)) partial_corr_array = np.array([[ 1., 0.52, 0.15, 0.91], [ 0.52, 1., 0.25, -0.25], [ 0.15, 0.25, 1. , -0.06], [ 0.91, -0.25, -0.06, 1. ]]) mask = np.zeros_like(partial_corr_array, dtype=np.bool) mask[np.triu_indices_from(mask)] = True cmap = sns.diverging_palette(30, 10, as_cmap=True) sns.heatmap(partial_corr_array, mask=mask, cmap=cmap, vmax=1, center=0, square=True, linewidths=1, cbar_kws={"shrink": 0.9}, annot=True) Output
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52261575
score: 2
accepted answer of: http://stackoverflow.com/q/52261575
has comment: http://stackoverflow.com/comment/91507483

http://stackoverflow.com/comment/91235602
comment on: http://stackoverflow.com/q/52142162
has text: I can't reproduce your error. Your code displays the expected twin axis graph with Windows 10, Python 3.6, matplotlib 2.2.3, pandas 0.22. A full traceback would also be helpful. Please edit your question.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52155419
has comment: http://stackoverflow.com/comment/91271082
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91305276
upvote count: 1
tagged with: python
tagged with: multilabel-classification
has comment: http://stackoverflow.com/comment/91305221
has title: in which situation different methods in multi-label classifications in scikit learn should be applied
answer count: 0
score: 0
tagged with: text-classification
downvote count: 1
type: Question
has body: I have read this to learn about various method in multi-label classifiers. I learned that there are 3 techniques to do multi-label classifications: 1.Problem Transformation 2.Adapted Algorithm 3.Ensemble approaches In the category of Problem transformations there are more three sub categories: a.Binary Relevance b.Classifier Chains c.Label Powerset I know that when we want better result we should apply the ensemble model. I would like to know in which situations the other different algorithm we should use. I know how they differently work, but I do not know when I should use each of them. And Also there is only two method implemented for Adapted Algorithm. what if I want other methods but implemented in adapted algorithm approach? Please let me know if my statements are not clear. Thanks,
has comment: http://stackoverflow.com/comment/91305435
tagged with: scikit-learn
favorite count: 0

http://stackoverflow.com/comment/91811616
score: 0
type: AnswerComment
has text: Better post a new question, but try to find a solution on your own first and add your attempts to the question. You could put your images/pygame.Surfaces into a list and use `random.choice` to pick one. Then call [`image.get_rect()`](http://www.pygame.org/docs/ref/surface.html#pygame.Surface.get_rect) to create a rect with the size of the image and put the image and the rect into a list. I mean something similar to [this example](https://stackoverflow.com/questions/52188563/pygame-elements-with-different-speed/52235124#52235124).
type: Comment
comment on: http://stackoverflow.com/a/52156064

http://stackoverflow.com/q/52236954
type: Question
accepted answer: http://stackoverflow.com/a/52237031
duplicate of: http://stackoverflow.com/q/15112125
has body: I am trying to mak9e a love calculator, but it is throwing error that, score_total is not defined, I tried many things but it just doesn't works. I try to define it globally. When I defined it globally as score_total=0. It just doesn't return from function, it keeps its value 0 outside the function. I am a beginner. boy = input("Enter boy Name\n").casefold() girl = input("Enter girl name\n").casefold() #score_total= vowel_a =0 vowel_b=0 boyl=None girll=None boyl=len(boy) girll=len(girl) #print(boyl) cons_a =0 cons_b=0 for i in range(boyl): if boy[i] is 'a' or 'e' or 'i' or 'o' or 'u': vowel_a+=1 for i in range(girll): if girl[i] is 'a' or 'e' or 'i' or 'o' or 'u': vowel_b+=1 for i in range(len(boy)): if boy[i] is 'z' or 'b' or 't' or 'h': cons_a +=1 for i in range(len(girl)): if girl [i] is 'z' or 'b' or 't' or 'h': cons_b+=1 def calculation(a,b,score_total): score_total = 1 if len(a) == len(b): score_total += 20 elif len(a)!=len(b): score_total += 7.4 if a[0] and b[0] is 'a' or 'b' or 'c' or 'd' or 'e': score_total +=10 else: score_total+=3.7 if a[0] and [b] is 'z' or 'b' or 't' or 'h': score_total+=5 else: score_total +=1.16 if vowel_a == vowel_b: score_total +=12 else: score_total +=3.67 if cons_a == cons_b: score_total+=12 else: score_total+=4.56 if a[0] is 'i' or 'v' or 'o' or 'l': score_total+=7 else: score_total+=5.6 #return int(score_total) print(score_total) #print(scor-- calculation(boy,girl,1) if score_total &lt; 50: if score_total%2 ==0: score_total+=30 elif score_total&gt;100: temp = score_total-100 score_total -= temp else: score_total+=24 import time print("Calculating Result...........\n") time.sleep(3) print("Data processing...") time.sleep(7) print(f'The love between {boy} and {girl} is {score_total}%' )
tagged with: python-2.7
score: 0
answer count: 2
has title: i can't understand the actual problem of this code?
has answer: http://stackoverflow.com/a/52237049
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52237031
tagged with: python
possible better answer: http://stackoverflow.com/a/52237049
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20002503
duplicate of: http://stackoverflow.com/q/20002503
linked to: http://stackoverflow.com/q/15112125

http://stackoverflow.com/comment/91346768
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52194880
type: Comment
has text: @ProgramerBeginner I suggest you upgrade to Python 3 anyway. You'll have to sooner or later. The `2to3` tool (part of the Python installation) does a very good job at helping you port the code.

snappy
type: Tag
tags question: http://stackoverflow.com/q/52115655
tag name: snappy

http://stackoverflow.com/comment/91533046
comment on: http://stackoverflow.com/a/52267251
score: 0
type: Comment
has text: I have added a screen shot of my code in the edited post pleaseee check :) Thanks in advance
type: AnswerComment

sqlite
tags question: http://stackoverflow.com/q/52130392
tags question: http://stackoverflow.com/q/52207940
tags question: http://stackoverflow.com/q/52242296
tags question: http://stackoverflow.com/q/52121300
tags question: http://stackoverflow.com/q/52206011
tags question: http://stackoverflow.com/q/52162922
tags question: http://stackoverflow.com/q/52192233
tags question: http://stackoverflow.com/q/52141350
tags question: http://stackoverflow.com/q/52185043
type: Tag
tags question: http://stackoverflow.com/q/52230037
tags question: http://stackoverflow.com/q/52199075
tags question: http://stackoverflow.com/q/52154560
tags question: http://stackoverflow.com/q/52145497
tags question: http://stackoverflow.com/q/52129333
tags question: http://stackoverflow.com/q/52210750
tags question: http://stackoverflow.com/q/52264355
tags question: http://stackoverflow.com/q/52143572
tags question: http://stackoverflow.com/q/52127370
tags question: http://stackoverflow.com/q/52152848
tags question: http://stackoverflow.com/q/52124657
tags question: http://stackoverflow.com/q/52236112
tags question: http://stackoverflow.com/q/52248002
tags question: http://stackoverflow.com/q/52268592
tags question: http://stackoverflow.com/q/52113171
tags question: http://stackoverflow.com/q/52222401
tags question: http://stackoverflow.com/q/52154857
tags question: http://stackoverflow.com/q/52246833
tag name: sqlite

cd
tag name: cd
type: Tag
tags question: http://stackoverflow.com/q/52254868

http://stackoverflow.com/comment/109134575
type: QuestionComment
has text: Does this answer your question? [concatenate strings in 2 different lists in python](https://stackoverflow.com/questions/36885876/concatenate-strings-in-2-different-lists-in-python)
comment on: http://stackoverflow.com/q/52192855
score: 1
type: Comment

http://stackoverflow.com/a/52133355
type: Answer
has body: In case it helps anyone else, here's what I did. When users browse, they will be restricted to the folder with the finding images, since they are specific to that part of the report. Similarly, uploading an image will send it to the same folder. In a nutshell, you have to: Point the CKEditor Uploader URLs to your version of the views Update the CKEditor Uploader widget through the corresponding form views Override the CKEditor Uploader ImageUploadView and browse views to create the path you want Examples Updated CKEditor URL Paths path('myapp/&lt;int:org_id&gt;/report/&lt;int:report_id&gt;/finding/&lt;int:finding_id&gt;/image/upload', never_cache(ck_views.upload), path('myapp/&lt;int:org_id&gt;/report/&lt;int:report_id&gt;/finding/&lt;int:finding_id&gt;/images', never_cache(ck_views.browse), name='ckeditor_browse'), Widget Update def get(self, request, *args, **kwargs): context = {} obj = self.get_object() if obj is not None: context['org'] = obj.report.org.id form = FindingForm(instance=obj) # Set image browse/upload path image_kwargs = { 'finding_id': obj.id, 'org_id': obj.report.org.id, 'report_id': obj.report.id, } image_browse_path = reverse('ckeditor_browse', kwargs=image_kwargs) image_upload_path = reverse('ckeditor_upload', kwargs=image_kwargs) form.fields['description'].widget.config['filebrowserBrowseUrl'] = image_browse_path form.fields['description'].widget.config['filebrowserUploadUrl'] = image_upload_path context['form'] = form return render(request, self.template_name, context)
accepted answer of: http://stackoverflow.com/q/52123097
answers question: http://stackoverflow.com/q/52123097
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/52116918
has comment: http://stackoverflow.com/comment/91186833
has comment: http://stackoverflow.com/comment/91357304
tagged with: arrays
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91186287
has body: I am in the process of porting a Fortran 77 code (c. 1990), which was originally written in BASIC (c. 1986) into Python 3 utilizing several modules, namely Numpy and Pandas. It uses several loops to assign elements of arrays. For instance: 6050 do 6100 J = 1,3 Y(J,1) = Z(J) 6100 continue where Z is a initialized as 5000 do 5500 J = 1,3 Z(J) = 0 5500 continue and Z and Y were allocated memory as dimension C(4), Z(4), ... K(4,4), Y(4,4) Further down the code the Z vector is reassigned after the C vector is constructed using array K 6500 do 6600 M = 1,3 C(M) = (K(M,1)+2*K(M,2)+2*K(M,3)+K(M,4))/6 Z(M) = Z(M) + C(M) 6600 continue There are several places that this occurs with various other arrays. Z and Y are the most critical arrays, though, as they are how most variables are assigned. I was wondering how one handles this in numpy? or if there is a better way to attempt this. currently I have import numpy as np ... Z = np.zeroes((1,4)) Y = np.zeroes((4,4)) (...etc...) ... for n in range(1,i) # main loop of calculation ... Y[0,:] = Z ... C = (K[:,0]+2*K[:,1]+2*K[:,2]+K[:,3])/6 Z = Z + C but I dont think this is correct. I only have a print-out of the source code to go off of. I don't have copies of the input/output files. If I had at least a properly formatted input file, I would retype the fortran into a compiler, run it and see what is happening in the actual code.
tagged with: python
has comment: http://stackoverflow.com/comment/91185557
answer count: 0
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91185396
type: Question
tagged with: numpy
has title: Fortran 77 arrays to Numpy Arrays
score: 3
has comment: http://stackoverflow.com/comment/91184923
has comment: http://stackoverflow.com/comment/91186106

http://stackoverflow.com/comment/91335719
comment on: http://stackoverflow.com/q/52192983
type: QuestionComment
has text: Your `agg_sheet['APPL_4']` are strings so that's why you are getting this error. What kind of chart do you want to plot? A bar chart?
type: Comment
score: 1

http://stackoverflow.com/comment/91192943
comment on: http://stackoverflow.com/q/52120850
score: 0
type: Comment
type: QuestionComment
has text: `if searchPhrase1 in line` will work, assuming the line contains the words in exactly that order. Are you saying you want to look for lines containing the words in any order?

http://stackoverflow.com/comment/91335452
comment on: http://stackoverflow.com/q/52192722
score: 2
has text: @mypetlion: Aside from the NumPy motivation, it was impossible to implement equality comparisons without ordering comparisons in the old API. Also, requiring every equality test to compute ordering was hurting performance. Rich comparisons may be more code, but the benefits are real.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52216920
has body: You see the error because the Python expression that you have will result in a dictionary object if 'result' doesn't contain 'stdout'. This can be print-ed - print happily accepts any data type, but write does not. The problem is with the priority of operations in your expression: if ... else binds less tightly than %. I suspect that what you wanted is this: f.write('result: %s\n' % (result['stderr'] if 'stderr' in result else result) ) NOTE the parentheses.
type: Answer
answers question: http://stackoverflow.com/q/52216645
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/q/52179685
type: Question
has comment: http://stackoverflow.com/comment/91309715
tagged with: python
has answer: http://stackoverflow.com/a/52180287
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/91309543
has title: When I set the value of local to be greater than 1, why did pyspark resort the error
tagged with: pyspark
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52179965
downvote count: 0
score: 1
favorite count: 0
has body: When I set the value of local to 1, the operation is normal, but when set to 2, the error message is reported as follows from pyspark import SparkContext # Changing 1 to 2 will give you an error sc = SparkContext("local[2]", "sort") class MySort: def __init__(self, tup): self.tup = tup def __gt__(self, other): if self.tup[0] &gt; other.tup[0]: return True elif self.tup[0] == other.tup[0]: if self.tup[1] &gt;= other.tup[1]: return True else: return False else: return False r1 = sc.parallelize([(1, 2), (2, 2), (2, 3), (2, 1), (1, 3)]) r2 = r1.sortBy(MySort) print(r2.collect()) Caused by: org.apache.spark.api.python.PythonException: Traceback (most recent call last): File "E:\spark2.3.1\spark-2.3.1-bin-hadoop2.7\python\lib\pyspark.zip\pyspark\worker.py", line 230, in main File "E:\spark2.3.1\spark-2.3.1-bin-hadoop2.7\python\lib\pyspark.zip\pyspark\worker.py", line 225, in process File "E:\spark2.3.1\spark-2.3.1-bin-hadoop2.7\python\lib\pyspark.zip\pyspark\serializers.py", line 376, in dump_stream bytes = self.serializer.dumps(vs) File "E:\spark2.3.1\spark-2.3.1-bin-hadoop2.7\python\lib\pyspark.zip\pyspark\serializers.py", line 555, in dumps return pickle.dumps(obj, protocol) _pickle.PicklingError: Can't pickle : attribute lookup MySort on __main__ failed

http://stackoverflow.com/q/52154334
has comment: http://stackoverflow.com/comment/91258860
downvote count: 4
upvote count: 0
answer count: 1
has title: Is it an array inside another array or are we looking for a certain value in the array?
favorite count: 0
tagged with: python
has body: i know this might be a bit beginner level type of code but i am getting a bit confused by this code below. i don't know what is happening. may someone be kind enough to explain it to me? And what is the output of the code? lest = [3, 1, -2] print(lest[lest[-1]]) 3 1 -1 -2 What really is happening here, especially with lst[lst[-1]]? i do not understand the concept being shown here. are we looking for a value in a multi-dimensional array or what?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91258883
has answer: http://stackoverflow.com/a/52156953
score: -4
type: Question
accepted answer: http://stackoverflow.com/a/52156953

http://stackoverflow.com/a/57011065
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52124258
has body: such a MaybeEncodingError mostly due to this fact that you forgot to use if __name__ == '__main__': when trying to create a working version on Windows, I had a strange repeating error message. Attempt to start a new process before the current process has finished its bootstrapping phase. This probably means that you are on Windows and you have forgotten to use the proper idiom in the main module: if __name__ == '__main__': literally quoting the comment I got, since it's self-explanatory: the error on windows is because each process spawns a new python process which interprets the python file etc. so everything outside the "if main block" is executed again" so to be portable, you have to use if __name__=='__main__' when running this module: import multiprocessing as mp from multiprocessing import Pool, freeze_support if __name__ == '__main__': #you need this in windows freeze_support() main()

http://stackoverflow.com/q/52268343
has body: How much can I rely on the object's id() and its uniqueness in practice? E.g.: Does id(a) == id(b) mean a is b or vice versa? What about the opposite? How safe is it to save an id somewhere to be used later (e.g. into some registry instead of the object itself)? (Written as a proposed canonical in response to Canonicals for Python: are objects with the same id() the same object, `is` operator, unbound method objects)
has answer: http://stackoverflow.com/a/52268344
accepted answer: http://stackoverflow.com/a/52268344
linked to: http://stackoverflow.com/q/20753364
linked to: http://stackoverflow.com/q/306313
type: AnsweredQuestion
score: 10
tagged with: identity
type: Question
tagged with: identity-operator
linked to: http://stackoverflow.com/q/13348031
answer count: 1
duplicate of: http://stackoverflow.com/q/20753364
linked to: http://stackoverflow.com/q/29785084
linked to: http://stackoverflow.com/q/17679861
upvote count: 10
tagged with: python
favorite count: 0
has title: id() vs `is` operator. Is it safe to compare `id`s? Does the same `id` mean the same object?
downvote count: 0

http://stackoverflow.com/q/52188435
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/91327127
linked to: http://stackoverflow.com/q/51717751
has comment: http://stackoverflow.com/comment/91327170
has body: I created the Keras model. Then I used a function that draws you a graph of the architecture of the model. It created png file that is shown below. Code that creates a model: model = Sequential() model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2]))) model.add(Dense(1, activation='linear')) model.compile(loss='mae', optimizer='adam', metrics=[self.coeff_determination]) Line that creates png image of the architecture: plot_model(model, to_file='C:\CSV\model.png', show_layer_names=True, show_shapes=True) This is the image I get: The question is what the big number at the top of the graph means.
duplicate of: http://stackoverflow.com/q/51717751
tagged with: python
upvote count: 2
has title: Keras Model Architecture
tagged with: machine-learning
downvote count: 1
has answer: http://stackoverflow.com/a/52189992
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91328337
has comment: http://stackoverflow.com/comment/91327475
accepted answer: http://stackoverflow.com/a/52189992
type: Question
tagged with: deep-learning
answer count: 1

http://stackoverflow.com/comment/91446137
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/52236982
type: Comment
has text: Have you tried running an `airflow upgradedb`?

http://stackoverflow.com/comment/91490445
type: Comment
has text: How can I write this file in the UTF-8 format so that it can be read as well write?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52256072

http://stackoverflow.com/comment/91419973
type: Comment
has text: I have edited the question to show more information. I need the output to show in a single line like this : [average for Mon average for Tue average for Wed etc.]
comment on: http://stackoverflow.com/a/52235668
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91465584
comment on: http://stackoverflow.com/q/52258825
type: QuestionComment
has text: Haven't you found this in your research? https://docs.python.org/3.4/library/string.html#format-string-syntax It's hard to believe ... or this: https://www.python.org/dev/peps/pep-3101/
score: 0
type: Comment

seq2seq
tag name: seq2seq
type: Tag
tags question: http://stackoverflow.com/q/52197023

http://stackoverflow.com/q/52220670
has body: I use PyCharm, normally I install 3rd party libraries with the Project Interpreter in PyCharm. Today I installed plotly by running pip install plotly==2.7 in the terminal. But when I tried to import it, I got an unresolved reference 'plotly' warning in the editor. How can I solve it? I got this error when I run the code ModuleNotFoundError: No module named 'plotly'
answer count: 1
favorite count: 0
has title: Can't find the modules that have been installed by pip
tagged with: python-3.x
tagged with: pycharm
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52223275
tagged with: pip
tagged with: python
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91390519
has comment: http://stackoverflow.com/comment/91390423
has comment: http://stackoverflow.com/comment/91390167
has comment: http://stackoverflow.com/comment/91390629
type: Question
has comment: http://stackoverflow.com/comment/91390614
has comment: http://stackoverflow.com/comment/91390215
has comment: http://stackoverflow.com/comment/91390099
upvote count: 2

http://stackoverflow.com/a/52245472
answers question: http://stackoverflow.com/q/52245357
has body: it looks like your data has quotes, why have you got QUOTE_NONE specified there?
has comment: http://stackoverflow.com/comment/91439199
type: Answer
has comment: http://stackoverflow.com/comment/91444053
score: 0

http://stackoverflow.com/q/52258924
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: pyqt5
accepted answer: http://stackoverflow.com/a/52300225
type: Question
has comment: http://stackoverflow.com/comment/91465635
tagged with: debugging
has body: I am desperately trying to use the Spyder3 built-in debugger to debug a pyqt5 application. It seems that as soon as the qt app is running the breakpoints are not hit anymore. I had a similar problem with exceptions occurring inside slots which somehow by default are lost along their way to the console. For that there is a workaround which works most of the time. However, debugging seems quite impossible. The code which should demonstrate the problem: from PyQt5 import QtCore, QtWidgets from PyQt5.QtWidgets import QApplication, QMainWindow import sys class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(240, 190, 75, 23)) self.pushButton.setObjectName("pushButton") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) self.pushButton.clicked.connect(MainWindow.clicked_slot) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.pushButton.setText(_translate("MainWindow", "PushButton")) class main_app_class(QMainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.show() def clicked_slot(self): """Breakpoints in here are never hit""" print("Hit me!") if __name__ == "__main__": if not QApplication.instance(): app = QApplication(sys.argv) else: app = QApplication.instance() main_ap…
has comment: http://stackoverflow.com/comment/91547502
has comment: http://stackoverflow.com/comment/91499989
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52300225
tagged with: spyder
has title: Debug QT5 application in Spyder3
tagged with: python

http://stackoverflow.com/comment/91436292
type: QuestionComment
score: 1
has text: MaxPooling is working as intended, the problem is your understanding of what the parameters do. I wouldn't use padding=same with pooling as the whole purpose of using pooling is to reduce dimensions (the shapes).
comment on: http://stackoverflow.com/q/52241539
type: Comment

replace
tags question: http://stackoverflow.com/q/52239692
tags question: http://stackoverflow.com/q/52247052
tags question: http://stackoverflow.com/q/52205673
tags question: http://stackoverflow.com/q/52180942
tags question: http://stackoverflow.com/q/52190143
tags question: http://stackoverflow.com/q/52123501
tags question: http://stackoverflow.com/q/52126313
type: Tag
tags question: http://stackoverflow.com/q/52149305
tag name: replace
tags question: http://stackoverflow.com/q/52266756
tags question: http://stackoverflow.com/q/52217300
tags question: http://stackoverflow.com/q/52171458

http://stackoverflow.com/comment/91449490
score: 2
comment on: http://stackoverflow.com/q/52250895
type: Comment
has text: try `drama__name` note the two `_`'s
type: QuestionComment

http://stackoverflow.com/comment/91255105
type: AnswerComment
comment on: http://stackoverflow.com/a/52152174
type: Comment
has text: CalculatorRoot is not a ScreenManager. But I do have a ScreenManager named calc_screen_manager in my CalculatorRoot. look at the new version of the question.
score: 0

http://stackoverflow.com/q/52199666
has title: How to install wxPython 2.8 on Ubuntu 18.04?
tagged with: python
has answer: http://stackoverflow.com/a/60576789
has answer: http://stackoverflow.com/a/53773777
has comment: http://stackoverflow.com/comment/91348760
has comment: http://stackoverflow.com/comment/91361537
type: Question
has comment: http://stackoverflow.com/comment/93064313
tagged with: robotframework
tagged with: ubuntu
score: 0
has answer: http://stackoverflow.com/a/60938641
has answer: http://stackoverflow.com/a/55663071
tagged with: wxpython
has comment: http://stackoverflow.com/comment/91348475
has body: I am trying to install wxPython 2.8 on Ubuntu 18.04 system. But it is failing with below error : $ sudo apt install python-wxgtk2.8 Reading package lists... Done Building dependency tree Reading state information... Done Package python-wxgtk2.8 is not available, but is referred to by another package. This may mean that the package is missing, has been obsoleted, or is only available from another source E: Package 'python-wxgtk2.8' has no installation candidate Let me know how to resolve above error so that I can install wxPython 2.8
has answer: http://stackoverflow.com/a/52214192
answer count: 5
type: UnansweredQuestion

http://stackoverflow.com/comment/91217337
score: 2
type: Comment
comment on: http://stackoverflow.com/a/52133334
has text: While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
type: AnswerComment

http://stackoverflow.com/q/52183109
type: Question
has comment: http://stackoverflow.com/comment/91324049
tagged with: python
has body: I am trying to do some work with the networkx package in python and am stuck at the most basic level. I cannot even get the simplest code snippets to work in my environment. For example: import networkx as nx G = nx.Graph() G.add_node(1) G.add_nodes_from([2, 3]) G.add_nodes_from(range(4, 7)) G.add_edge(1, 2) G.add_edge(1, 1) G.add_edges_from([(2,3), (3,6), (4,6), (5,6)]) list(G.nodes) This throws the following error: &gt; --------------------------------------------------------------------------- TypeError Traceback (most recent call &gt; last) &lt;ipython-input-280-90765acb4d1b&gt; in &lt;module&gt;() &gt; 9 G.add_edges_from([(2,3), (3,6), (4,6), (5,6)]) &gt; 10 &gt; ---&gt; 11 list(G.nodes) &gt; &gt; ~\Anaconda3\envs\tracx\lib\site-packages\networkx\classes\graph.py in &gt; nodes(self) &gt; 717 &gt; 718 """ &gt; --&gt; 719 nodes = NodeView(self) &gt; 720 # Lazy View creation: overload the (class) property on the instance &gt; 721 # Then future G.nodes use the existing View &gt; &gt; ~\Anaconda3\envs\tracx\lib\site-packages\networkx\classes\reportviews.py &gt; in __init__(self, graph) &gt; 166 &gt; 167 def __init__(self, graph): &gt; --&gt; 168 self._nodes = graph._node &gt; 169 &gt; 170 # Mapping methods &gt; &gt; TypeError: descriptor '_nodes' for 'NodeView' objects doesn't apply to &gt; 'NodeView' object I've got 2.1 installed and run it from Jupyter notebook with python 3.5. What am I missing here?
has answer: http://stackoverflow.com/a/52209214
score: 0
upvote count: 1
answer count: 1
downvote count: 1
tagged with: networkx
type: UnansweredQuestion
tagged with: graph
has title: Networkx not working at all - weird errors for the most basic operations
favorite count: 0

http://stackoverflow.com/q/52220462
has comment: http://stackoverflow.com/comment/91452886
tagged with: list
has comment: http://stackoverflow.com/comment/91465723
linked to: http://stackoverflow.com/q/32706135
has answer: http://stackoverflow.com/a/52276227
accepted answer: http://stackoverflow.com/a/52277985
has comment: http://stackoverflow.com/comment/91454248
has comment: http://stackoverflow.com/comment/91500509
linked to: http://stackoverflow.com/q/43385877
has answer: http://stackoverflow.com/a/52272814
has comment: http://stackoverflow.com/comment/91443554
has comment: http://stackoverflow.com/comment/91443312
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52279509
has comment: http://stackoverflow.com/comment/91458435
has comment: http://stackoverflow.com/comment/91389690
has comment: http://stackoverflow.com/comment/91443267
has answer: http://stackoverflow.com/a/52274429
has answer: http://stackoverflow.com/a/52275082
has comment: http://stackoverflow.com/comment/91446567
score: 6
favorite count: 0
has comment: http://stackoverflow.com/comment/91389482
has comment: http://stackoverflow.com/comment/91446616
type: Question
answer count: 8
has title: Select sublists from python list, beginning and ending on the same element
has comment: http://stackoverflow.com/comment/91465352
tagged with: python
has answer: http://stackoverflow.com/a/52277985
possible better answer: http://stackoverflow.com/a/52274070
has answer: http://stackoverflow.com/a/52301646
has answer: http://stackoverflow.com/a/52274070
tagged with: python-3.x
has body: I have a (very large) list similar to: a = ['A', 'B', 'A', 'B', 'A', 'C', 'D', 'E', 'D', 'E', 'D', 'F', 'G', 'A', 'B'] and I want to extract from it a list of lists like: result = [['A', 'B', 'A', 'B', 'A'], ['D', 'E', 'D', 'E', 'D']] The repeating patterns can be different, for example there can also be intervals such as: ['A', 'B', 'C', 'A', 'D', 'E', 'A'] (with a 'jump' over two elements) I have written a very simple code that seems to work: tolerance = 2 counter = 0 start, stop = 0, 0 for idx in range(len(a) - 1): if a[idx] == a[idx+1] and counter == 0: start = idx counter += 1 elif a[idx] == a[idx+1] and counter != 0: if tolerance &lt;= 0: stop = idx tolerance = 2 elif a[idx] != a[idx+1]: tolerance -= 1 if start != 0 and stop != 0: result = [a[start::stop]] But 1) it is very cumbersome, 2) I need to apply this to very large lists, so is there a more concise and faster way of implementing it? EDIT: As @Kasramvd correctly pointed out, I need the largest set that satisfies the requirement of (at most a tolerance number of jumps between the start and end elements), so I take: ['A', 'B', 'A', 'B', 'A'] instead of [ 'B', 'A', 'B' ] because the former includes the latter. Also it would be good if the code can select elements UP TO the certain tolerance, for example if the tolerance (maximum number of elements not equal to the start or end element) is 2, it should also return sets as: ['A', 'A', 'A', 'B', 'A', 'B', 'A', 'C', 'D', 'A'] with tolerances 0, 1 and 2.
has comment: http://stackoverflow.com/comment/91455845
has comment: http://stackoverflow.com/comment/91457101
upvote count: 7
downvote count: 1
has comment: http://stackoverflow.com/comment/91443510
has comment: http://stackoverflow.com/comment/91495962
has comment: http://stackoverflow.com/comment/91478752

http://stackoverflow.com/comment/91444333
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52246451
has text: in scala, you could to `.withColumn("val1", col("val._1")).withColumn("val2", col("val._2"))`, not sure whether this works in pyspark
type: Comment

http://stackoverflow.com/comment/91246926
comment on: http://stackoverflow.com/a/52148606
type: Comment
score: 0
type: AnswerComment
has text: I am pretty sure `'bar barfoo'` should also return `True`.

http://stackoverflow.com/q/52169501
has body: I'm looking for a way to extract a specific file (knowing his name) from an archive containing multiple ones, without writing any file on the hard drive. I tried to use both StringIO and zipfile, but I only get the entire archive, or the same error from Zipfile (open require another argument than a StringIo object) Needed behaviour: archive.zip #containing ex_file1.ext, ex_file2.ext, target.ext extracted_file #the targeted unzipped file archive.zip = getFileFromUrl("file_url") extracted_file = extractFromArchive(archive.zip, target.ext) What I've tried so far: import zipfile, requests data = requests.get("file_url") zfile = StringIO.StringIO(zipfile.ZipFile(data.content)) needed_file = zfile.open("Needed file name", "r").read()
has title: How to extract a specific file from an archive donwloaded from internet using only memory
tagged with: python-2.7
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52202638
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/2463770
tagged with: python
possible better answer: http://stackoverflow.com/a/52169725
has answer: http://stackoverflow.com/a/52169725
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/52202638
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/52229781
upvote count: 3
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52227509
has body: In order to get the value of title for the instance of Post to which you are uploading the image, upload_to needs to be a callable. That callable will receive the instance as an argument and you can then get the title. Something like this: def post_image_path(instance, filename): title = instance.title return f"image/posts/{title}/{filename}" class Post(models.Model): # ... title = models.CharField(max_length=250) image = models.ImageField(upload_to=post_image_path)
score: 3
accepted answer of: http://stackoverflow.com/q/52227509
downvote count: 0

http://stackoverflow.com/comment/91393563
comment on: http://stackoverflow.com/q/52216489
score: 0
type: Comment
type: QuestionComment
has text: Not yet, Still am looking for answer

http://stackoverflow.com/a/52231650
type: Answer
has body: This regex should do the trick: _([^0-9]?&lt;=)|(?=[^0-9])_ In English: "either before or after the underscore is not a number" ?&lt;= means that whatever precedes is the group to capture ?= means that whatever follows is the group to capture
answers question: http://stackoverflow.com/q/52231496
score: 0

http://stackoverflow.com/comment/91332994
type: Comment
score: 1
has text: I'm aware of the solution and I'm sure you are too. I liked your original answer for it's simplicity. My comment was just a general dissatisfaction with `setdefault`. It would be nice to have another method that accepts a callable instead of a preconstructed instance.
type: AnswerComment
comment on: http://stackoverflow.com/a/52187030

http://stackoverflow.com/q/52136980
has comment: http://stackoverflow.com/comment/91223854
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/91224300
score: 2
has comment: http://stackoverflow.com/comment/91224299
downvote count: 0
tagged with: pytz
has comment: http://stackoverflow.com/comment/91223893
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91224422
has body: I was expecting that the following two would give the same result, but they didn't. Why is that the case? Versions: pytz==2018.5 python-dateutil==2.7.3 Example 1: pytz import datetime import pytz tz = pytz.timezone('Pacific/Apia') today_utc = datetime.datetime(2011, 12, 30, 9, 59, tzinfo=datetime.timezone.utc) today_tz = today_utc.astimezone(tz) print(today_tz.isoformat()) prints 2011-12-29T23:59:00-10:00 (which is correct) Example 2: dateutil import datetime import dateutil.tz tz = dateutil.tz.gettz('Pacific/Apia') today_utc = datetime.datetime(2011, 12, 30, 9, 59, tzinfo=datetime.timezone.utc) today_tz = today_utc.astimezone(tz) print(today_tz.isoformat()) prints 2011-12-29T23:59:00+14:00 (which is wrong)
tagged with: python-dateutil
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/52137582
has comment: http://stackoverflow.com/comment/91223881
answer count: 1
has title: Why do I get different results for pytz and dateutil for Samoa?
favorite count: 0
has answer: http://stackoverflow.com/a/52137582

http://stackoverflow.com/q/52132599
has answer: http://stackoverflow.com/a/52132692
type: Question
downvote count: 0
tagged with: dataframe
tagged with: pandas
answer count: 1
tagged with: scikit-learn
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has body: Lets take boston data set available in the from sklearn.datasets import load_boston boston = load_boston() X = pd.DataFrame(boston["data"]) 0 1 2 3 4 5 6 7 8 9 10 11 12 0 0.00632 18.0 2.31 0.0 0.538 6.575 65.2 4.0900 1.0 296.0 15.3 396.90 4.98 1 0.02731 0.0 7.07 0.0 0.469 6.421 78.9 4.9671 2.0 242.0 17.8 396.90 9.14 2 0.02729 0.0 7.07 0.0 0.469 7.185 61.1 4.9671 2.0 242.0 17.8 392.83 4.03 3 0.03237 0.0 2.18 0.0 0.458 6.998 45.8 6.0622 3.0 222.0 18.7 394.63 2.94 4 0.06905 0.0 2.18 0.0 0.458 7.147 54.2 6.0622 3.0 222.0 18.7 396.90 5.33 5 0.02985 0.0 2.18 0.0 0.458 6.430 58.7 6.0622 3.0 222.0 18.7 394.12 5.21 6 0.08829 12.5 7.87 0.0 0.524 6.012 66.6 5.5605 5.0 311.0 15.2 395.60 12.43 I have built a machine learning model (RF) and have obtained all estimators in the model. estimators = model.estimators_ You can think this has list of functions that takes row level data and return a value. &gt;&gt; estimators = model.estimators_ &gt;&gt; estimators [DecisionTreeRegressor(criterion='mse', max_depth=60, max_features=8, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=5, min_samples_split=12, min_weight_fraction_leaf=0.0, presort=False, random_state=1838148368, splitter='best'), DecisionTreeRegressor(criterion='mse', max_depth=60, max_features=8, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=5, min_samples_split=12, min_weight_fraction_leaf=0.0, presort=False, random_state=1754873550, splitter='best'), DecisionTreeRegressor(criterion='mse', max_depth=60, max_features=8, max_leaf_nodes=None, min_impurity_decrease=0.0,....] I want each estimator/function in list to be apply to every row in the data frame. If I don't convert the data to data frame boston['data'] returns a 2D Array. I can use two for loops to accomplish above. Assume X is a 2D array then I can do following for x in range(len(X)): vals = [] for estimator in model.estimators_: vals.append(estimator.predict(X[x])[0]) I don't want …
tagged with: python
has title: pandas apply list of function to data frame
score: 2

http://stackoverflow.com/comment/91267919
comment on: http://stackoverflow.com/q/52154162
type: Comment
type: QuestionComment
has text: Add this in first layer `return_sequences = True`
score: 0

http://stackoverflow.com/a/52225190
has body: It's not that complex. Start with a regular expression that can match "pristine" output, something like \$[0-9]+(\.[0-9]{2})? Now, just replace the questionable characters with their alternatives. [$S][0-9SIl]+([.,][0-9SIl]{2})? This can give you false positives, as you will "find" $1 in a sentence like "I read SI for baseball and basketball news" (SI being an abbreviation for the magazine Sports Illustrated, but that's unavoidable with regular expressions alone. Once you've made the match, converting the result to its assumed correct form is simple: replace any initial S with $, any , with ., and any other S with 5.
answers question: http://stackoverflow.com/q/52225009
accepted answer of: http://stackoverflow.com/q/52225009
has comment: http://stackoverflow.com/comment/91399775
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/91400131
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/52124719
accepted answer: http://stackoverflow.com/a/52126359
tagged with: mysql
tagged with: django
upvote count: 1
has title: Django - Unable to retrieve data in database in dropdownlist
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91200873
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52126359
has comment: http://stackoverflow.com/comment/91200617
favorite count: 0
has comment: http://stackoverflow.com/comment/91201001
has comment: http://stackoverflow.com/comment/91201021
possible better answer: http://stackoverflow.com/a/52125144
tagged with: python
has answer: http://stackoverflow.com/a/52125144
has answer: http://stackoverflow.com/a/52127273
type: AnsweredQuestion
has body: Hi, I really need help in this, tried for many days and still cannot do it. I am very new to Django. Problem: I am unable to retrieve the data in MySQL database to display it in a drop-down list. Can someone help me, please? Much appreciated! models.py class paper(models.Model): id = models.CharField(max_length=70, primary_key=True, null=False) year = models.TextField(null=True) month = models.TextField(null=True) number = models.IntegerField(null=True) def __str__(self): return str(self.id) Views.py def dropdown_list(request): paper = paper.objects.all() pname = request.GET.get('paper_id') context = { "paper": paper, "name": pname } return render(request, 'exampapersNew/exampaper.html', context) exampaper.html {% csrf_token %} SELECT YEAR {% if paper %} {% for p in paper %} {{ p.year }} {{ p.month }} Paper {{ p.number }} {% endfor %} {% endif %} urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^feedback/', include('feedback.urls')), url(r'^exampapersNew/', include('exampapersNew.urls')), url(r'^$', views.HomeView, name = 'home'), url(r'^feedback', views.FeedbackM, name = 'feedback'), url(r'^exampapersNew', views.ExampapersNewView, name = 'exampapersNew'), url(r'^frequentlyasked', views.FrequentlyaskedView, name = 'frequentlyasked'), url(r'^api/', include(v1_api.urls)), url(r'^exampapersNew/<int:paper_id>/', views.EMaths_Menu, name = 'paper_archive'), url(r'^formula', views.e_math_concept, name = 'formula'), ] forms.py class DropdownForm(forms.Form): class Meta: model = paper fields = ['id', 'year', 'month', 'number'] mySQL Table mysql> SELECT * from exampapersnew_paper; +-----------+------+----------+--------+ | id | year | month | number | +-----------+------+----------+--------+ | 200801001 | 2008 | November | 1 | | 200801002 | 2008 | November | 2 | | 200901001 | 2009 | November | 1 | +-----------+------+----------+--------+ 3 rows in set (0.00 sec)

http://stackoverflow.com/a/52116863
has comment: http://stackoverflow.com/comment/91184934
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91185512
has comment: http://stackoverflow.com/comment/91184801
has comment: http://stackoverflow.com/comment/91184614
answers question: http://stackoverflow.com/q/52116721
has comment: http://stackoverflow.com/comment/91184666
has body: Just use plt.xlim and plt.ylim if you want to restrict the limits to within some range. Here is an example: import matplotlib.pyplot as plt import numpy as np X = [1,2,3,4,5] # y = [0.1,0.3,2.4,3.9,3.2] y = [0.1,0.2,0.3,0.5,1.1] plt.plot(X, y) plt.xlim(min(X), max(X)) ticks = [tick for tick in ax.get_yticks()] plt.ylim(ticks[0], ticks[-1]) # plt.ylim(np.floor(min(y)), np.ceil(max(y))) # If you want only integer upper and lower limits EDIT: This addresses your concern for the following set of values X = [1,2,3,4,5] and y = [0.1,0.2,0.3,0.5,1.1]
has comment: http://stackoverflow.com/comment/91184565
accepted answer of: http://stackoverflow.com/q/52116721
has comment: http://stackoverflow.com/comment/91184856
upvote count: 1
has comment: http://stackoverflow.com/comment/91184699
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91184744
type: Answer

http://stackoverflow.com/a/52240494
downvote count: 0
type: Answer
has body: Use a list comprehension with np.array_equal: &gt;&gt;&gt; [i for i in arr if not np.array_equal(i, [0,0])] [array([71, 35, 44, 0]), array([56, 55, 0]), array([32, 90, 11]), array([ 0, 3, 81, 9, 20]), array([ 5, 89])] However, it is best to not work with jagged numpy arrays, as numpy does not behave well with such arrays.
has comment: http://stackoverflow.com/comment/91429730
has comment: http://stackoverflow.com/comment/91429728
upvote count: 3
answers question: http://stackoverflow.com/q/52240476
score: 3

http://stackoverflow.com/comment/91301518
score: 0
type: Comment
has text: Still not working :/..and by source, I just meant the news source. I am using selenium to click through and search for specific terms and then from the results page pull the headline, news source, and date of publication.
type: AnswerComment
comment on: http://stackoverflow.com/a/52175228

http://stackoverflow.com/q/52174366
has answer: http://stackoverflow.com/a/52174465
has comment: http://stackoverflow.com/comment/91299822
accepted answer: http://stackoverflow.com/a/52174456
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52174456
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52174416
has comment: http://stackoverflow.com/comment/91300089
has body: def istrue(a): if a: return True return False Can such a function have its niche somehow? I mean if I want to check the trueness of a variable I can always just use if variable: do that Thanks in advance
has comment: http://stackoverflow.com/comment/91300374
has comment: http://stackoverflow.com/comment/91299710
type: Question
tagged with: function
upvote count: 3
possible better answer: http://stackoverflow.com/a/52174416
has title: Is there any use for a isTrue-function?
answer count: 3
downvote count: 1

http://stackoverflow.com/a/52133533
has comment: http://stackoverflow.com/comment/91217480
upvote count: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52133506
score: 1
has body: The following will do: intended_dict = dict1.copy() for k, v in dict1.items(): for i in v: intended_dict.setdefault(i, []).append(k)
has comment: http://stackoverflow.com/comment/91217450

http://stackoverflow.com/comment/91401317
type: Comment
type: QuestionComment
has text: are you adding enough wait time for item to be available before clicking on it?
comment on: http://stackoverflow.com/q/52225661
score: 0

http://stackoverflow.com/comment/91264798
has text: Ok. I was imagining a whole bunch of possibilities that don't exist. I see your point now.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52155783

http://stackoverflow.com/q/52159269
upvote count: 1
linked to: http://stackoverflow.com/q/49748063
tagged with: python
linked to: http://stackoverflow.com/q/49768770
has body: I'm trying to use pipenv in a new Django project. However, if I try to pipenv install django, I get an error confirming the SSL certificate: Kurts-MacBook-Pro:wemap kurtpeek$ pipenv install django Installing django... Collecting django Could not fetch URL https://pypi.python.org/simple/django/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) - skipping Error: An error occurred while installing django! Could not find a version that satisfies the requirement django (from versions: ) No matching distribution found for django I've recently run a brew upgrade; here are my Pipenv and Python versions: Kurts-MacBook-Pro:wemap kurtpeek$ pipenv --version pipenv, version 2018.7.1 Kurts-MacBook-Pro:wemap kurtpeek$ python --version Python 3.7.0 I've tried the answer of Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION] but this essentially didn't do anything as my pip version was already up-to-date: Kurts-MacBook-Pro:wemap kurtpeek$ curl https://bootstrap.pypa.io/get-pip.py | python % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 1604k 100 1604k 0 0 583k 0 0:00:02 0:00:02 --:--:-- 583k Collecting pip Using cached https://files.pythonhosted.org/packages/5f/25/e52d3f31441505a5f3af41213346e5b6c221c9e086a166f3703d2ddaf940/pip-18.0-py2.py3-none-any.whl Installing collected packages: pip Found existing installation: pip 18.0 Uninstalling pip-18.0: Successfully uninstalled pip-18.0 Successfully installed pip-18.0 I am running MacOS Sierra version 10.12.6, so this does indeed seem to be caused by the TLS 1.0 deprecation issue described in 'pip install' fails for every package ("Could not find a version that satisfies the requirement"). But how to remedy this?
downvote count: 0
tagged with: pip
has title: "There was a problem confirming the ssl certificate" using pipenv install
type: AnsweredQuestion
score: 1
tagged with: ssl
favorite count: 0
has answer: http://stackoverflow.com/a/52160138
accepted answer: http://stackoverflow.com/a/52160138
type: Question
answer count: 1

http://stackoverflow.com/comment/91277127
type: Comment
type: QuestionComment
score: 0
has text: No,if i filled that list also it throws me the same error.can you check one more time.
comment on: http://stackoverflow.com/q/52163474

http://stackoverflow.com/q/52254234
score: -1
has body: I'm sure there are probably several ways to do what I am achieving, but have run into some problems. I have a "Member" model and I'm also trying to add a "Dependent" model that inherits some fields and data from the parent (Member) but also has some of the same fields, but their own data. What would be the best way to achieve this? ForeignKey, OneToOne, or ManyToMany, or is it even possible? Example: class Member(models.Model): name = models.CharField(max_length=128) address = models.CharField(max_length=128) age = models.DateField() class Dependent(models.Model): name = models.CharField(max_length=128) (different name) address = models.CharField(max_length=128) (same address as Member) age = models.DateField() (different age) Thank you for your help.
has answer: http://stackoverflow.com/a/52254360
has comment: http://stackoverflow.com/comment/91456016
answer count: 1
has comment: http://stackoverflow.com/comment/91456084
has comment: http://stackoverflow.com/comment/91456168
favorite count: 0
tagged with: model
has comment: http://stackoverflow.com/comment/91470833
has comment: http://stackoverflow.com/comment/91457457
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91456124
has title: Model Inheritance or Foreign Key?
downvote count: 1
type: Question
upvote count: 0

http://stackoverflow.com/a/52262254
answers question: http://stackoverflow.com/q/52261435
type: Answer
has body: boxplot expects a single argument x (axs[0, 0].boxplot(x)). However you provide two arguments. This will of course fail, because the second argument is interpreted to qualify if notches are to be shown and should hence take either True or False. It looks like you want to plot two boxplots instead, axs[0, 0].boxplot(dfFl['ppt']) axs[0, 0].boxplot(dfnFl['ppt']) Or axs[0, 0].boxplot([dfFl['ppt'],dfnFl['ppt']])
score: 0

http://stackoverflow.com/a/52121229
upvote count: 1
answers question: http://stackoverflow.com/q/52120850
has body: Here is one of my older python scripts for parsing text. It uses a little regx but should get you where you want to go. #!/usr/bin/python import sys import os import re def readFile( fileName ): try: file myFile = open( fileName, "r") except IOError: print "There was an error reading file" sys.exit() file_text = myFile.read() myFile.close() return file_text def writeFile( fileName, fileContent ): ret = 1 try: file myFile = open(fileName, "w") except IOError: print "There was an error writing to", fileName sys.exit() myFile.write(fileContent) myFile.close() return ret str textContents = readFile("./myfile.txt") list textLineList = textContents.splitlines() for textLine in textLineList: if re.match("(?:word1|word2|word3)*", textLine, re.I ): print textLine To further optimize this you could precompile the regex. But it should be a pretty fast little script already.
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/91485328
type: QuestionComment
has text: I don't have a toy example because I don't know how to do it. And the result I am expecting is the addition of one object to another. Example:- "00:07:00 + 2016-09-02 14:41:00" = "2016-09-02 14:48:00"
comment on: http://stackoverflow.com/q/52268817
score: 0
type: Comment

http://stackoverflow.com/comment/91444697
has text: `input().replace(r'\n', '\n')`
comment on: http://stackoverflow.com/q/52248391
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52206011
tagged with: python
accepted answer: http://stackoverflow.com/a/52206274
answer count: 1
linked to: http://stackoverflow.com/q/25387537
has body: This syntax: consulta.execute("SELECT * FROM {0} WHERE rut LIKE '%"+str(cadena)+"%'".format(tablepx)) produces an error: sqlite3.OperationalError: unrecognized token: "{" I tried with this too: consulta.execute("SELECT * FROM {0} WHERE rut LIKE ?".format(tablepx),(cadena,)) It doesn't send error but nothing happens, it doesn't work as I get zero results from the database. I don't know how to work with '%" + str(cadena) +"%', I always work with .format().
downvote count: 1
upvote count: 0
has answer: http://stackoverflow.com/a/52206274
has comment: http://stackoverflow.com/comment/91361274
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91361299
tagged with: sqlite
score: -1
favorite count: 0
tagged with: python-3.x
has title: python sqlite3 unrecognized token: "{"

http://stackoverflow.com/comment/91370028
score: 0
type: QuestionComment
type: Comment
has text: Yeah that's correct will edit
comment on: http://stackoverflow.com/q/52210121

http://stackoverflow.com/comment/91329078
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52189631
type: Comment
has text: responsedata.raise_for_status() updates responsedata.status_code, responsedata.reason. They can't be empty... This is the whole idea behind the request package isn't it?

http://stackoverflow.com/q/52235433
tagged with: python
type: AnsweredQuestion
tagged with: list
has body: global globalEnd globalEnd = 0 aList = [0,globalEnd,[0,1,globalEnd]],[[],['l'],globalEnd] for i in range(10): globalEnd += 1 print(aList) Like the code above I want all the values called globalEnd in the list to be 10. But it still prints out 0
has title: How do I get global variables in python to work within a list?
tagged with: global-variables
type: Question
accepted answer: http://stackoverflow.com/a/52235573
score: 0
answer count: 2
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52235485
has answer: http://stackoverflow.com/a/52235573
favorite count: 0
possible better answer: http://stackoverflow.com/a/52235485

http://stackoverflow.com/comment/91445773
type: AnswerComment
score: 0
type: Comment
has text: @AkshayGaur happy to help, remember that both of these one liners *do not* modify the dataframe in place, but instead return an updated copy. If you need to modify the original dataframe you can just replace `df.assign` with `df['Tair'] = ` etc..
comment on: http://stackoverflow.com/a/52248714

http://stackoverflow.com/q/52201081
has comment: http://stackoverflow.com/comment/91351909
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91351441
favorite count: 0
tagged with: combinatorics
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52202070
duplicate of: http://stackoverflow.com/q/464864
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91352006
type: Question
linked to: http://stackoverflow.com/q/104420
has body: I have a list of 11 numbers, and I want to test the product of all combinations against some rule (2^11 possibilities). I came across this SO question, but it seems to return a list of all combinations, which I think would take up to much memory. My C++ thinking would be to go through each binary number 0x001 to 0x7FF and multiply each number where its corresponding bit is 1. Example with 4 numbers: My list is [2, 3, 5, 7] The first binary number would be 0001 giving - 2 = 2 Later we would get to 1110 and the product would be 3 * 5 * 7 = 105 Is there a better way of doing this in python? A bit manipulation doesn't seem like the right way to go.
has title: Compute product of all combinations of a list
has answer: http://stackoverflow.com/a/52202070

http://stackoverflow.com/comment/91451480
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52251912
has text: I'm guessing that you want to write `href="{% url 'cart:cart-add' object.id %}"` instead of `href="{% url 'cart:cart-add' product.id %}"` . I'm not sure that `product` is passed to the view or is it?
score: 0

http://stackoverflow.com/comment/91446763
type: AnswerComment
type: Comment
has text: Basically the task is to compare the hyperparameters for LinearSVC. Meaning the model is confirmed and I am just looking to fine-tune the hyperparameters. This is why I was confused. So given that I assume I can use the entire dataset, right?
comment on: http://stackoverflow.com/a/52249233
score: 0

http://stackoverflow.com/q/52173535
has title: Running python script from VBA
score: 1
has comment: http://stackoverflow.com/comment/91313495
has comment: http://stackoverflow.com/comment/91299225
type: Question
has comment: http://stackoverflow.com/comment/91335362
has comment: http://stackoverflow.com/comment/91298280
has body: the below code is executing simple python script from Windows excel VBA Shell on 1 machine, but not on the other. Sub RunIt() CreateObject("wscript.shell").Run "python.exe " &amp; """\\acntnyc039\dept\HGS\Bob\test_syst_arg2.py""", 1, True 'same as Shell "python.exe ""\\acntnyc039\dept\HGS\Bob\test_syst_arg2.py""", 1 End Sub corresponding python: import pandas as pd import sys path = r'\\acntnyc039\dept\HGS\Bob\test\test.csv' raw_data = {'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 'last_name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze'], 'age': [42, 52, 36, 24, 73], 'preTestScore': [4, 24, 31, 2, 3], 'postTestScore': [25, 94, 57, 62, 70]} df = pd.DataFrame(raw_data, columns = ['first_name', 'last_name', 'age', 'preTestScore', 'postTestScore']) df.to_csv(path) i've read all similar threads and checked the following: both users have identical non-admin access, yet it does not execute for one of them producing no error message (but cmd opens) network path does not have spaces the same line runs just fine from cmd directly python is found when typing python from cmd, but still tried replacing python with python.exe along with full path to python.exe in VBA string above to no avail full anaconda3 reinstall did not fix the problem shell seems to be working fine on non-python code as in: Shell "notepad.exe ""\\acntnyc039\dept\HGS\Bob\test\test.csv""", 1 i'm really running out of ideas here ...
upvote count: 1
accepted answer: http://stackoverflow.com/a/70705942
answer count: 1
downvote count: 0
tagged with: vba
tagged with: shell
has comment: http://stackoverflow.com/comment/91299824
favorite count: 0
linked to: http://stackoverflow.com/q/51947269
has answer: http://stackoverflow.com/a/70705942
tagged with: python
tagged with: excel
type: AnsweredQuestion

http://stackoverflow.com/comment/91321234
comment on: http://stackoverflow.com/a/52183995
has text: It seems that I have to reinstall Tensorflow. Thanks for your answer and your Code addition. I'll try it out in a moment.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52208100
has body: I thought this would be funny and interesting to share. I ran into a weird situation which I have never encountered before. I was fooling around with pythons beautifulsoup. After scraping https://www.amazon.ca i got the strangest output at the end of the HTML. Can anyone tell me if this is intentional from the developers of amazon? Or is this something else ? FYI here is the code I used to show it has nothing to do with me import lxml from bs4 import BeautifulSoup import urllib.request as re # ********Below is the soup used to gather the HTML************ url = "https://www.amazon.ca" page = re.urlopen(url) soup = BeautifulSoup(page, 'lxml') print(soup)
type: Question
has title: Weird / Funny ouput after beautifulsoup web scrape
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/91367084
has comment: http://stackoverflow.com/comment/91365669
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91365597
has answer: http://stackoverflow.com/a/63807355
tagged with: beautifulsoup

http://stackoverflow.com/comment/91294635
has text: There is no requirements.txt in the working directory now. I am ABLE to create one by running your code, if that's what you are asking.
comment on: http://stackoverflow.com/a/52171756
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52148236
has comment: http://stackoverflow.com/comment/91273586
type: Question
tagged with: pydoc
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91273558
has body: I have a function foobar which expects its parameter baz to be any object that implements __gt__ and __eq__. def foobar(baz, qux): """ :type baz: Any object that implements __gt__ and __eq__ """ if baz &gt;= qux: return 'nice!' return 'ouch!' Are there any conventions on how you should document these types of parameters? I'm using Python 3.5 if it matters.
tagged with: documentation
favorite count: 0
has comment: http://stackoverflow.com/comment/91246949
has comment: http://stackoverflow.com/comment/91273855
tagged with: python
has comment: http://stackoverflow.com/comment/91246310
linked to: http://stackoverflow.com/q/47965083
upvote count: 1
has comment: http://stackoverflow.com/comment/91273388
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91246344
has title: Documenting Python params that are duck-typed
has comment: http://stackoverflow.com/comment/91247886
has answer: http://stackoverflow.com/a/52149213
accepted answer: http://stackoverflow.com/a/52149213
score: 1

http://stackoverflow.com/comment/91765264
type: QuestionComment
comment on: http://stackoverflow.com/q/52266658
type: Comment
has text: Well all I really would like to do is have an accurate way to find the FWHMs of this image in Python along different directions -- perhaps I should abandon the Gaussian fit method. I did try a different method involving simply measuring the FWHMs using the roots of `UnivariateSpline`, but oddly it returns smaller widths for the semi-major and minor axes than what is documented on the webpage.
score: 0

http://stackoverflow.com/q/52131173
has title: Problems using scipy.odr with math.erf()
tagged with: python
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
upvote count: 1
type: Question
score: 1
has body: I have a problem using the orthogonal distance regression with a function using the error function math.erf(). To be more clear it seems I have a problem with the variables which should be fit. import numpy as np from scipy import odr import math def CDF(x,a,b,c): #definition of errorfunction to fit data return c/2*(1+math.erf((x-a)/(b*math.sqrt(2)))) #to make things a little shorter I excluded the parts in which the data is read and prepared guess=Ergebnis_popt[1] #using found values for a,b,c from curve_fit without errors guess_a=guess[0] guess_b=guess[1] guess_c=guess[2] xerr=Verschiebung_fit[2] #determination of x_erros, the values for the y errors are included in the prepared data xerr=xerr/xerr xerr=xerr/200 #building the model for the odr fit, as the erf function seems to only handle single values I use np.vectorize cfd = odr.Model(np.vectorize(CDF,excluded=['a','b','c']),extra_args= ['a','b','c']) #Definition of the Data with ererrors for the fit mydata =odr.RealData(Verschiebung_fit[2],y=y_values_fit[2],sx=xerr,sy=y_values_fit[4]) #basis for the odr fit odr=odr.ODR(mydata,cfd, beta0 = [guess_a,guess_b,guess_c] ) myoutput = odr.run() myoutput.pprint() All this results in a Error: File "C:\Users\Public\Anaconda\lib\site-packages\numpy\lib\function_base.py", line 2785, in _get_ufunc_and_otypes outputs = func(*inputs) File "C:\Users\Public\Anaconda\lib\site-packages\numpy\lib\function_base.py", line 2750, in func return self.pyfunc(*the_args, **kwargs) TypeError: CDF() takes 4 positional arguments but 5 were given I am a novice using python. I guess there is a problem with communicating the variables which should be fitted, but I can not figure out where this problem occurs.
linked to: http://stackoverflow.com/q/48226089
has comment: http://stackoverflow.com/comment/91215128
downvote count: 0
tagged with: one-definition-rule
favorite count: 0

http://stackoverflow.com/comment/91395323
has text: Can you try opening the image with GDAL in Python (as in the code you shared) and looking at the output when you print one of the raster bands? And also the output of the metadata when opened with GDAL. GDAL Python's documentation explains how you can do this
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52222834

http://stackoverflow.com/comment/91325122
comment on: http://stackoverflow.com/q/52187001
has text: @timgeb because for index 3 the value contains 'hi' & 'bye'. For it to be true the value must contain an element which exists in `check_against_myList`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/62720456
type: Answer
score: 13
upvote count: 13
has comment: http://stackoverflow.com/comment/119296381
answers question: http://stackoverflow.com/q/52132913
downvote count: 0
has body: Don't know if your problem is solved or not, but for all future developers looking on this thread. A super simple way to get a bot to mention a channel is like this... <#channelID> were the channel ID is the discord ID of the specific channel you wish to mention. and in an example await message.channel.send("Please go to <#channelID>") I'm honestly a bit confused that no one on this thread has already mentioned this, so I feel like I'm missing something that y'all already know lol.

http://stackoverflow.com/comment/91430222
type: Comment
type: QuestionComment
has text: You can do `df=df.astype("float64", errors="ignore")`. All columns that could be converted, will be converted.
comment on: http://stackoverflow.com/q/52240694
score: 4

http://stackoverflow.com/q/52239615
upvote count: 6
tagged with: google-cloud-dataflow
has answer: http://stackoverflow.com/a/52279394
accepted answer: http://stackoverflow.com/a/52279394
favorite count: 0
score: 6
tagged with: python
has body: My folder structure is as follows: Project/ --Pipeline.py --setup.py --dist/ --ResumeParserDependencies-0.1.tar.gz --Dependencies/ --Module1.py --Module2.py --Module3.py My setup.py file looks like this: from setuptools import setup, find_packages setup(name='ResumeParserDependencies', version='0.1', description='Dependencies', install_requires=[ 'google-cloud-storage==1.11.0', 'requests==2.19.1', 'urllib3==1.23' ], packages = ['Dependencies'] ) I used the setup.py file to create a tar.gz file using 'python setup.py sdist'. The tar file is in the dist folder as ResumeParserDependencies-0.1.tar.gz. I then specified setup_options.extra_packages = ['./dist/ResumeParserDependencies-0.1.tar.gz'] in my pipeline options. However, once I run my pipeline on Dataflow, I get the error 'No module named ResumeParserDependencies'. If I use 'pip install ResumeParserDependencies-0.1.tar.gz' locally, the package installs, and I can see it using 'pip freeze'. What am I missing to load the package into Dataflow?
type: AnsweredQuestion
downvote count: 0
has title: How can I install a python package onto Google Dataflow and import it into my pipeline?
possible better answer: http://stackoverflow.com/a/52266402
has answer: http://stackoverflow.com/a/52266402
linked to: http://stackoverflow.com/q/42984118
type: Question
answer count: 2

http://stackoverflow.com/q/52171726
score: -1
has title: What is the alternative to dict as way to parameterize python class?
tagged with: class
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91294365
has comment: http://stackoverflow.com/comment/91294157
has comment: http://stackoverflow.com/comment/91294131
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52171858
has body: I usually see the following python code around the codebase I work with: class A: def do_something(self): pass class B: def do_something(self): pass class C: _magic_dict = {'option1' : A, 'option2' : B} def do_something_else(self, option): # call some other methods, functiosn my_option = _magic_dict['option']() my_option.do_something() self.do_more_things(my_option) So the basic idea is to make class C generic to A or B. Is this a common practice? I feel like it is an overuse of dicts and the fact that everything (in this case the class) is an object that can be passed around. For a more specific problem, the following example might help. There is a class responsible to take a given metric object, which in the end is a dict of objects holding the info for that type of metric. And there is a statistics reporter which will take a given metric object, choose a type of data it is interested to report (one of the entries in the dict, let's say) and output that in a pretty format. So: class FoodMetric: def __init__(self, path_to_my_stock_files): self._path = path_to_my_stock_files self._data = {} def parse(self): # let's assume that after parsing the files, the following data would have been obtained: # self.data = {'cheese' : {'cheddar' : 10, 'goat' : 20}} class WoodFastenerMetric: def __init__(self, path_to_my_stock_files): self._path = path_to_my_stock_files self._data = {} def parse(self): # let's assume that after parsing the files, the following data would have been obtained: # self.data = {'nails' : {'round' : 10, 'oval' : 20}} class StatsReporter: _magic_dict = {'food' : (FoodMetric, ['column1', 'column2'], 'cheese') 'wood_fastener' : (WoodFastener, ['columnA', 'columnB'], 'nail') } def present_data(metric_type): the_class, columns, data_set_name = _magic_dict(metric_type) metric = the_class(self._path) # assume I have the path for the files here metric.parse() print(self._convert_to_table(metric, columns, data_set_name)) I do have an alternative implementation in…

http://stackoverflow.com/q/52134654
has comment: http://stackoverflow.com/comment/91220206
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52135223
score: 1
upvote count: 1
has title: Use service for queries in Flask application
tagged with: sqlalchemy
type: Question
has body: I am working with flask and SQLAlchemy, so let's say for example i have a class User : class User(UserMixin, Base): __tablename__ = 'user' id = Column(Integer, nullable=False, autoincrement=True, primary_key=True) email = Column(String(100), nullable=False, unique=True) password = Column(String(100)) name = Column(String(100)) Now in my views every time i make a query to get a user by id or by name i make a query.So i thought to make a class called userService and put all queries in it.So i could have : class UserService(): def getUserByName(self, name): return User.query.filter(User.name == name).first() def getUserById(self, id): return User.query.get(id) def getUserByEmail(self, email): return User.query.filter(User.email == email).first() Now in my views i can call the UserService class every time i need a user.I use application factory, so my question is: Is it more efficient to instantiate the UserService object in my create_app function and then import it in my views.py file, or instantiate a new UserService object in every route in my views.py file?
downvote count: 0
tagged with: flask
answer count: 1
has answer: http://stackoverflow.com/a/52135223
favorite count: 0

http://stackoverflow.com/a/52264165
type: Answer
upvote count: 3
score: 3
has body: To work with a relational database is to understand that there is no next row, no preset order. You need to request a particular order by sorting, then fetch as many records in that order as you need. In this case, you use e.g. .filter(the_table.c.name == "John"), then .order_by("id", "name"), then .limit(2). If you fetched two rows there were two records that match your constraint. There can be no records, or just one record. Things become trickier if you have multiple sets of records for John, and want a particular subsequence. For that you might add a condition like the_table.c.id &gt;= certain_id, or something similar for the date. In general, your data model is lacking an explicit way to link several records into one sequence. You don't have a "sequence id", or "previous record id", or something like that which would help see several records as related. Maybe you can use the timestamp column for that, if it fits your problem; it quite likely does not.
downvote count: 0
answers question: http://stackoverflow.com/q/52263573

http://stackoverflow.com/q/52209043
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91367909
accepted answer: http://stackoverflow.com/a/52209361
tagged with: selenium
tagged with: webdriver
type: Question
has title: How to locate the button with text as Comment as per the html using Selenium and Python?
has body: I am using Xpath helper in chrome extension to find xpath for python programming. I have read the documentation but is there a better guide out there. HTML is as follows: Comment Can someone show me an example to click the button of this path? I have tried to use it but didnt work submit_comment = driver.find_element_by_xpath("/html[@class='gr__society6_com']/body[@class='platform- desktop']/div[@id='wrap']/div[@id='content']/div[@id='MySociety']/div[@class='one-col clearfix']/ul[@id='Mason']/li[@id='9649102']/div[@class='item-wrap']/div[@class='comments']/form[@class='addComment expand']/button[@id='b9649102']").click()
has comment: http://stackoverflow.com/comment/91368004
answer count: 1
has comment: http://stackoverflow.com/comment/91369556
has comment: http://stackoverflow.com/comment/91367939
tagged with: css-selectors
has answer: http://stackoverflow.com/a/52209361
score: -1
favorite count: 0
tagged with: xpath
downvote count: 2
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/119999858
has comment: http://stackoverflow.com/comment/91367629
linked to: http://stackoverflow.com/q/32259865

http://stackoverflow.com/comment/91482610
type: Comment
has text: @AndrewK It's reliable on CPython 3.6+ or Python 3.7+. What version of Python do you use?
comment on: http://stackoverflow.com/a/52267018
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91283813
type: QuestionComment
has text: @p.strain to create the array as you need, use this: `Region_array = np.array(tuple(range(region_width)), tuple(range(region_height)))`. Explained: `range` creates iterable in size of given number with increments by 1, `tuple` makes tuple (faster version of list) from the iterable, so it can be passed to the numpy array.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52166465

http://stackoverflow.com/a/52145619
has body: It's possible that you've installed modules for a different python executable, not the one that your mod_wsgi uses by default. To check that, add to the beggining of your WSGI file: import sys print(sys.executable) Then, open shell, run a python and type the same code there. If path is different, you should specify WSGIPythonHome to point at the desired python executable.
upvote count: 1
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52140184

http://stackoverflow.com/comment/91302060
has text: @jpmc26 FWIW, the future ODPI-C 3 (and hence cx_Oracle 7) on Windows (only) will [look first for Oracle Client libraries in the same directory as the ODPI-C or cx_Oracle binary is located it](https://github.com/oracle/odpi/commit/d02192a77783523f2e74aa6518241a8fc58b9616). This may help some install scenarios, particularly for people creating software bundles.
comment on: http://stackoverflow.com/q/52152943
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91422836
score: 0
has text: Is this a rolling operation? Like do you use intermediate results in the calculations?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52236604

http://stackoverflow.com/q/52268108
has comment: http://stackoverflow.com/comment/91559058
has comment: http://stackoverflow.com/comment/91500942
tagged with: ubuntu-18.04
tagged with: python-import
has title: Python Can't find the mvnc module
has comment: http://stackoverflow.com/comment/91510366
type: UnansweredQuestion
score: 2
has answer: http://stackoverflow.com/a/53202029
has body: I've been trying to setup the movidius library created by intel, but I keep getting stuck when I try to import the mvnc package. To set up mvnc I followed the directions here: Real-time object detection with movidius and when it comes time to test if the install works, I run make examples which gives this error whenever I run it. Traceback (most recent call last): File "/usr/local/bin/mvNCCompile", line 25, in &lt;module&gt; from Models.Blob import * File "/usr/local/bin/ncsdk/Models/Blob.py", line 19, in &lt;module&gt; from Controllers.MiscIO import * File "/usr/local/bin/ncsdk/Controllers/MiscIO.py", line 35, in &lt;module&gt; from mvnc import mvncapi So I'm wondering how it would be possible to get python to recognize the mvnc module so I can import it into any of my code. Thank you for your help! I'm running Ubuntu 18.04.1 LTS in a virtual machine on a windows 10 computer Here's the full command line output: ./install-opencv.sh Installing opencv python for non-Raspbian [sudo] password for odyssey: Requirement already satisfied: opencv-python in /usr/local/lib/python3.6/dist-packages Requirement already satisfied: numpy&gt;=1.11.3 in /usr/lib/python3/dist-packages (from opencv-python) Requirement already satisfied: opencv-contrib-python in /usr/local/lib/python3.6/dist-packages Requirement already satisfied: numpy&gt;=1.11.3 in /usr/lib/python3/dist-packages (from opencv-contrib-python) make examples starting. (cd examples; make) make[1]: Entering directory '/home/odyssey/workspace/ncsdk/examples' make -C apps/. make[2]: Entering directory '/home/odyssey/workspace/ncsdk/examples/apps' make -C hello_ncs_py/. make[3]: Entering directory '/home/odyssey/workspace/ncsdk/examples/apps/hello_ncs_py' nothing to make, use 'make run' to run. make[3]: Leaving directory '/home/odyssey/workspace/ncsdk/examples/apps/hello_ncs_py' make -C multistick_cpp/. make[3]: Entering directory '/home/odyssey/workspace/ncsdk/examples/apps/multistick_cpp' making googlenet (cd ../../caffe/Go…
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91544435
type: Question
upvote count: 2
tagged with: python
answer count: 1

http://stackoverflow.com/a/52199963
accepted answer of: http://stackoverflow.com/q/52181106
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52181106
has body: Here's a hack: import sys def function(str_source): # get existing value gvars = sys._getframe(1).f_globals lvars = sys._getframe(1).f_locals if str_source in lvars: dir = lvars elif sttr_source in gvars: dir = gvars else: # might want to raise an exception here print(str_source, "not found") return False ext_str = str(dir[str_source]) ext_str = ext_str[:-1] # removing last character of the string # Store dir[str_source] = ext_str return True s1 = "hello" function("s1") s2 = "world" function("s2") print(s1) print(s2) Gives: hell worl
type: Answer

http://stackoverflow.com/q/52115775
upvote count: 1
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/91182786
has comment: http://stackoverflow.com/comment/91182157
has answer: http://stackoverflow.com/a/52115861
accepted answer: http://stackoverflow.com/a/52116789
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52116789
favorite count: 0
possible better answer: http://stackoverflow.com/a/52115861
tagged with: python
type: AnsweredQuestion
has title: python multiprocessing will only start first process
has body: So I worked on this python thing, where I would download pics from reddit and upload them again to ig and I`m trying to make the download and upload process simoultanious. I'm using multiprocessing for the matter. However, only my first process will start... Here's the "complete" code: def main(argv): timer = 15 username = '' password = '' caption = '' filecontainer = '' isset = 0 redisset = 0 redname = '' redsort = 'new' redtimer = 1 redscore = 50 redmax = 40 redre = False try: opts, args = getopt.getopt(argv, "hr:t:u:p:c:f:", ["reddit=", "red=", "redditname=", "freshtimer=","top","new","hot", "score=", "max=","overwrite"]) except getopt.GetoptError: print('this.py -t &lt;time in minutes&gt; -u &lt;ig-username&gt; -p &lt;ig-password&gt; -c &lt;captionContainer&gt; -f &lt;path to filecontainer&gt;') sys.exit(2) for opt, arg in opts: ## Just some getopt stuff here... if isset == 4: #isset is just a way of testing if every arg was set. mainprozess = Process(target = runUpload(timer,username,password,caption,filecontainer)) mainprozess.start() mainprozess.join() rdprozess = Process(target = getReddit(filecontainer,redname,redtimer,redmax,redscore,redsort,redre)) rdprozess.start() rdprozess.join() else: print('you need to set all args') print('this.py -t &lt;time in minutes(only INTEGER!!!)&gt; -u &lt;ig-username&gt; -p &lt;ig-password&gt; -c &lt;caption&gt; -f &lt;path to filecontainer&gt;') sys.exit(1) def runUpload(timer,username,password,caption,filecontainer): #search for images in filecontainer allFiles = [] while len(allFiles) &lt;= 1: allFiles = [f for f in os.listdir(filecontainer) if os.path.isfile(os.path.join(filecontainer, f))] time.sleep(15) print("no files found...\nwaiting for files") r = random.randint(0,100) if r &lt;= 100: #80% chance to post just an image postOK = postImage(allFiles,filecontainer,caption,username,password) #elif r &gt;= 80: #20% chance to post an album # postOK = postAlbum(allFiles,filecontainer,caption,username,password) if postOK =…
score: 1

http://stackoverflow.com/comment/91462398
comment on: http://stackoverflow.com/a/52257181
score: 0
type: Comment
has text: For all other moments - please take time to test portions of code you have errors in with both python versions and go from there
type: AnswerComment

http://stackoverflow.com/comment/91187620
type: Comment
score: 1
has text: Do you need this to be cross-platform? If not, which platform do you care about?
comment on: http://stackoverflow.com/q/52118317
type: QuestionComment

http://stackoverflow.com/comment/91375290
type: QuestionComment
type: Comment
has text: Right, but it seems the builtin `numpy.isclose(, atol)` would be simpler (and probably faster) than all that. Also less error-prone. We have this neat (not-very-well-known) builtin, why hack around it and risk errors if user forgets to round before coercing to int before comparing....
comment on: http://stackoverflow.com/q/52185208
score: 0

http://stackoverflow.com/a/52178857
has comment: http://stackoverflow.com/comment/91379364
has comment: http://stackoverflow.com/comment/91308879
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91379462
has comment: http://stackoverflow.com/comment/91309149
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91309371
has comment: http://stackoverflow.com/comment/91308798
accepted answer of: http://stackoverflow.com/q/52178004
has comment: http://stackoverflow.com/comment/91380570
answers question: http://stackoverflow.com/q/52178004
has comment: http://stackoverflow.com/comment/91308301
has body: You must understand the following expression: Example().setWindowTitle("Window") it is equivalent to: obj = Example() obj.setWindowTitle("Window") That is, you are creating another Example object other than ex = Example(), and that object is creating another myclass2 object, and that other myclass2 object is creating another Example, and an infinite loop is clearly being created. Another thing that in the future could cause you problems is to establish the same name for different things, although in this case it is not a problem but in future occasions it could bring you problems, the code to which I refer is: self.myclass2 = myclass2() For example, it is recommended that classes should start with capital letters. Another error that is valid only in Qt is that the GUI can not be created or manipulated in a thread other than the main thread. So you can not change the title directly in the other thread but there are 2 methods: 1. QMetaObject::invokeMethod(...) But for this we must pass the GUI through a property: class Example(QWidget): def __init__(self): super().__init__() self.myclass2 = MyClass() self.myclass2.gui = self self.myclass2.start() self.initUI() def initUI(self): self.setGeometry(300, 300, 300, 220) self.setWindowTitle('Icon') self.setWindowIcon(QIcon('web.png')) self.show() class MyClass(QThread): def run(self): while True: time.sleep(.1) print(" in thread \n") QMetaObject.invokeMethod(self.gui, "setWindowTitle", Qt.QueuedConnection, Q_ARG(str, "Window")) 2. signals &amp; slots class Example(QWidget): def __init__(self): super().__init__() self.myclass2 = MyClass() self.myclass2.titleChanged.connect(self.setWindowTitle) self.myclass2.start() self.initUI() def initUI(self): self.setGeometry(300, 300, 300, 220) self.setWindowTitle('Icon') self.setWindowIcon(QIcon('web.png')) self.show() class MyClass(QThread): titleChanged = pyqtSignal(str) def run(self): while True: time.sleep(.1) print(" in thread \n") self.titleChanged.emit("Window") PLUS: You should …

http://stackoverflow.com/comment/91477948
type: QuestionComment
comment on: http://stackoverflow.com/q/52264616
score: 0
has text: can you navigate to the smb folder in the UI?
type: Comment

http://stackoverflow.com/a/52175978
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52175833
has comment: http://stackoverflow.com/comment/91323593
accepted answer of: http://stackoverflow.com/q/52175833
type: Answer
has body: In the tp_name slot of your C-level type definition, write the fully-qualified name: "your_module.YourClass" The __module__ of the type object will be set based on tp_name. The __file__ attribute of the module should already be handled automatically.
has comment: http://stackoverflow.com/comment/139844448
score: 2
has comment: http://stackoverflow.com/comment/91329849
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/91430176
type: Comment
comment on: http://stackoverflow.com/a/52240591
has text: lol, what is that image representing? did you wrote it with a stick ? :)
score: 0
type: AnswerComment

http://stackoverflow.com/q/52230139
type: Question
tagged with: python
has body: I have a number of pandas DataFrames like this: pd.DataFrame( {'Change': {0: 'C&gt;T', 1: 'C&gt;T', 2: 'C&gt;T'}, 'Gene': {0: 'TIIId', 1: 'HRAS', 2: 'p53-3'}, 'Loc': {0: 110541232, 1: 534280, 2: 7577120}} ) That looks like this: Loc Change Gene 0 110541232 C&gt;T TIIId 1 534280 C&gt;T HRAS 2 7577120 C&gt;T p53-3 And I would like to pull information from other DataFrames like this: pd.DataFrame( {'Change': {1: 'T&gt;C', 342: 'A&gt;T', 499: 'C&gt;T', 556: 'C&gt;T', 1082: 'C&gt;T'}, 'Gene': {1: 'TIIIa', 342: 'SF3B1', 499: 'IDH1', 556: 'TIIIb', 1082: 'TIIId'}, 'Loc': {1: 115227854, 342: 198266844, 499: 209113142, 556: 223190698, 1082: 110541232}, 'VAF': {1: 0.0008172746042670338, 342: 0.0005706242629436604, 499: 0.0012779008348952122, 556: 0.0011640569261387105, 1082: 0.9980550801306987}} ) That looks like this: Loc Change VAF Change Gene 1 115227854 T&gt;C 0.000817275 T&gt;C TIIIa 342 198266844 A&gt;T 0.000570624 A&gt;T SF3B1 499 209113142 C&gt;T 0.0012779 C&gt;T IDH1 556 223190698 C&gt;T 0.00116406 C&gt;T TIIIb 1082 110541232 C&gt;T 0.998055 C&gt;T TIIId I would like to get all the values that fall under the VAF column for entries that have the same Loc and Change combination between the two DataFrames. So in the provided example, I would like to get the value of 0.998055 because location 110541232 and Change C&gt;T are found in both DataFrames.
score: 0
has title: Looking up information in matching rows of pandas DataFrames
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91409944
has comment: http://stackoverflow.com/comment/91409993
tagged with: pandas
answer count: 0

http://stackoverflow.com/comment/91476437
comment on: http://stackoverflow.com/a/52197844
type: AnswerComment
score: 0
type: Comment
has text: - Thank you for your suggestion. i am learning that Python 2.3 xx and Python 3 are quite different! so problem is fixed. My next is, Although i entered the IP that i want to scan i have this error message. "Read data files from: /usr/bin/../share/nmap WARNING: No targets were specified, so 0 hosts scanned. Nmap done: 0 IP addresses (0 hosts up) scanned in 0.03 seconds" I dont see what i am doing wrong - Thanks for your help.

http://stackoverflow.com/a/52185980
answers question: http://stackoverflow.com/q/52185838
downvote count: 0
has body: You could use a dict-comprehension like so: from numpy import array D1 = {0: array([1, 2, 3]), 1: array([0,4])} D2 = {'Jack': 1, 'Mike': 2, 'Tim': 3, 'Paul': 4, 'Tommy': 5} temp = dict(zip(D2.values(), D2.keys())) # inverting key-value pairs D3 = {k: [temp.get(i+1, 'N\A') for i in v] for k, v in D1.items()} which results in: {0: ['Mike', 'Tim', 'Paul'], 1: ['Jack', 'Tommy']}
has comment: http://stackoverflow.com/comment/91321843
score: 4
has comment: http://stackoverflow.com/comment/91321779
type: Answer
upvote count: 4

http://stackoverflow.com/a/52116785
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91184780
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52116398
answers question: http://stackoverflow.com/q/52116398
type: Answer
has body: It looks like you are trying to calculate cumulative returns. If so, those numbers are not in returns space and need to be divided by 100 first import pandas as pd df = pd.read_csv("Randomdata.csv") df2 = df.div(100).add(1).cumprod().sub(1).mul(100) Comment from OP I made the following change, removed subtraction. df2 = df.div(100).add(1).cumprod().mul(100) df2['returns_from_price_recovered'] = 100 * df2.pct_change()

http://stackoverflow.com/q/52134302
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91279778
has body: I've written a script in Python in association with selenium to click on each of the signs available in a map. However, when I execute my script, it throws timeout exception error upon reaching this line wait.until(EC.staleness_of(item)). Before hitting that line, the script should have clicked once but It could not? How can I click on all the signs in that map cyclically? This is the site link. This is my code so far (perhaps, I'm trying with the wrong selectors): from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC link = "https://www.findapetwash.com/" driver = webdriver.Chrome() driver.get(link) wait = WebDriverWait(driver, 15) for item in wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "#map .gm-style"))): item.click() wait.until(EC.staleness_of(item)) driver.quit() Signs visible on that map like: Post script: I know that this is their API https://www.findapetwash.com/api/locations/getAll/ using which I can get the JSON content but I would like to stick to the Selenium way. Thanks.
tagged with: python
upvote count: 13
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/52192392
has title: Unable to click on signs on a map
possible better answer: http://stackoverflow.com/a/52161076
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52161076
tagged with: selenium
linked to: http://stackoverflow.com/q/45347675
score: 13
tagged with: web-scraping
type: Question
accepted answer: http://stackoverflow.com/a/52192392
answer count: 2
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/91389692
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52220595
has text: Thank you !! How do you pickle it ? I would like to save the results onto a hard drive for long time storage. This is why I chose txt. Does it also work with pickle ? How would you do it.

http://stackoverflow.com/comment/91288222
comment on: http://stackoverflow.com/q/52168491
score: 0
has text: are you sure is a rtsp stream? sounds more like onvif ? which model of camera you have?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91699954
comment on: http://stackoverflow.com/q/52189260
score: 0
type: Comment
has text: The code from https://stackoverflow.com/questions/49799109/win32file-readdirectorychangesw-doesnt-find-all-moved-files#49888600 could be "broken up in pieces". I made it "editable", but I didn't imagine such a scenario. Anyway, it can be nicely wrapped up.
type: QuestionComment

http://stackoverflow.com/comment/91368004
type: QuestionComment
comment on: http://stackoverflow.com/q/52209043
has text: @BryanOakley : because the id is random generated. So we can’t rely on this id.
score: 0
type: Comment

http://stackoverflow.com/q/52243121
has comment: http://stackoverflow.com/comment/91435323
has answer: http://stackoverflow.com/a/52243758
has comment: http://stackoverflow.com/comment/91434986
has comment: http://stackoverflow.com/comment/91435373
has title: Tkinter not letting me insert a text in a Text Widget
type: AnsweredQuestion
upvote count: 0
has body: from tkinter import * from PIL import Image, ImageTk import time schermata = Tk() screen_width = schermata.winfo_screenwidth() screen_height = schermata.winfo_screenheight() indice = 0 schermata.iconbitmap("immagini\icona.ico") screen_resolution = str(screen_width)+'x'+str(screen_height) large_font = ('Verdana',30) schermata.geometry(screen_resolution) schermata.title("Jovan's RPG") class GUI(Frame): def __init__(self, master): super(GUI, self).__init__(master) self.pack() self.bg() self.immagine() self.testo() self.statistiche() self.inserimenti() def bg(self): load = Image.open("immagini\\background.png") render = ImageTk.PhotoImage(load) img = Label(schermata, image = render) img.image = render img.pack() def immagine(self): load = Image.open("immagini\\dn.png") render = ImageTk.PhotoImage(load) img = Label(schermata, image = render) img.image = render img.place( x = 10, y = 10 ) def testo(self): self.testo = Text(schermata, width = 110, height = 35, border = 5, bg = "black", fg ="white") self.testo.place( x = 400, y = 20 ) def statistiche(self): self.stats = Text(schermata, width = 40, height = 10, border = 5, bg = "black", fg ="white") self.stats.place( x = 10, y = (screen_height - 200)) def inserisci(self): fraseInserita = self.inserimento.get() scrivere(fraseInserita) self.inserimento.delete('0', END) def inserimenti(self): self.inserimento = Entry(schermata,font=large_font, width = 25, border = 5, bg = "black", fg ="white") self.inserimento.place( x = 400, y = (screen_height - 100)) self.bottone = Button(schermata, width = 30, height = 3, border = 5, text = "Inserisci", command = self.inserisci) self.bottone.place( x = (screen_width - 300), y = (screen_height - 100)) g = GUI(schermata) def scrivere(scrittura): g.testo.insert('1.0', scrittura) def cancellaTesti(): g.testo.delete('0',END) def wait(secondi): time.sleep(secondi) Levels class from GUI import * g = GUI(schermata) class Livelli(): def __init__(self): pass def cicloLivelli(self): self.presentazione(…
accepted answer: http://stackoverflow.com/a/52243758
favorite count: 0
type: Question
tagged with: python
score: -2
tagged with: tkinter
downvote count: 2
answer count: 1

http://stackoverflow.com/q/52238125
type: AnsweredQuestion
score: 2
has body: I was wondering what happens if I call a module on different file, which imports the same python module that is already imported on the main call, is it imported twice? If yes, how can I prevent it? What is recommended way for this? On the following example time module is imported on the both files. As alternative solution, I passed time module as an argument to the module call that is located on different file. Example: hello.py from module import module import time time.sleep(1) module(); module.py import time; # Already imported in hello.py def module(): #{ time.sleep(1) print('hello') #} Alternative: I am passing time module as argument into module() function that is located under module.py. hello.py from module import module import time time.sleep(1) module(time); module.py def module(time): #{ time.sleep(1) print('hello') #}
downvote count: 0
tagged with: import
type: Question
upvote count: 2
answer count: 1
linked to: http://stackoverflow.com/q/296036
favorite count: 0
has title: Import same python module if I call a function of different file
has comment: http://stackoverflow.com/comment/91424897
tagged with: python
has answer: http://stackoverflow.com/a/52238422
tagged with: module
accepted answer: http://stackoverflow.com/a/52238422

http://stackoverflow.com/comment/100542396
score: 0
comment on: http://stackoverflow.com/q/52242405
type: QuestionComment
type: Comment
has text: Possible duplicate of [How to input matrix (2D list) in Python?](https://stackoverflow.com/questions/22741030/how-to-input-matrix-2d-list-in-python)

http://stackoverflow.com/comment/91382009
score: 0
has text: @HarshadHolkar, are you sure the device id you selected same with the device_id in your code when you use device explorer to generate SAS token? Please check it. The code works fine for me.
comment on: http://stackoverflow.com/a/52215796
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52260912
has body: I run the following command to record video thru ffmpeg ffmpeg -y -rtbufsize 100M -f gdigrab -framerate 10 -i desktop -c:v libx264 -r 10 -tune zerolatency -pix_fmt yuv420p record.mp4 This works fine when I run it thru PowerShell(I stop the recording manually by pressing ctrl + c). I am trying to do the same thing thru Python and I have created two functions to start and stop the operation. def recThread(): cmd = 'ffmpeg -y -rtbufsize 100M -f gdigrab -framerate 10 -i desktop -c:v libx264 -r 10 -tune zerolatency -pix_fmt yuv420p ' + videoFile global proc proc = subprocess.Popen(cmd) proc.wait() def stop(): proc.terminate() However when I run this, the video is corrupted. I have tried using os.system command instead of subprocess and got the same result. Any help would be appreciated.
has answer: http://stackoverflow.com/a/52330436
answer count: 1
downvote count: 0
favorite count: 0
tagged with: ffmpeg
accepted answer: http://stackoverflow.com/a/52330436
tagged with: python
type: AnsweredQuestion
score: 1
has title: ffmpeg video recording gets corrupted
upvote count: 1
type: Question

http://stackoverflow.com/comment/91303854
type: Comment
comment on: http://stackoverflow.com/q/52173272
type: QuestionComment
score: 0
has text: The number of heaps to generate is still going to be at least exponential in the size of the input. You should find a different way to solve your underlying problem.

http://stackoverflow.com/a/52170552
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/91294412
has comment: http://stackoverflow.com/comment/91294398
has body: This is normal and intended. Decimal tracks significant digits, and the Decimal repr is intended to preserve significant digits. Decimal('3.3E+3') has two significant digits, while Decimal('3300') has four.
type: AcceptedAnswer
upvote count: 7
type: Answer
accepted answer of: http://stackoverflow.com/q/52170369
answers question: http://stackoverflow.com/q/52170369

tika-server
tags question: http://stackoverflow.com/q/52196544
tag name: tika-server
type: Tag

amazon-elastic-beanstalk
tag name: amazon-elastic-beanstalk
type: Tag
tags question: http://stackoverflow.com/q/52215189
tags question: http://stackoverflow.com/q/52141780

http://stackoverflow.com/a/52159289
answers question: http://stackoverflow.com/q/52158930
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: Even shorter: with open(filname,'r') as f: print([line.split() for line in f if line.split()])

http://stackoverflow.com/comment/91418970
comment on: http://stackoverflow.com/q/52235221
has text: Please consider creating an MCVE: https://stackoverflow.com/help/mcve You might want to have a look at the pandas library.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52135148
linked to: http://stackoverflow.com/q/20910075
has comment: http://stackoverflow.com/comment/91220269
has answer: http://stackoverflow.com/a/52135242
tagged with: pandas
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91220336
favorite count: 0
has title: Calculate column from two others using a function with Pandas
type: UnansweredQuestion
tagged with: python
has body: First of all, apologies if this question is repeated but I'm unable to solve my problem using the explanation in similar questions... I have a funcion that takes two parameters into account (longitud and latitude) and then it enters in Google API to extract the city and the country of these coordinates. This funcion is the following: from urllib.request import urlopen import json def getplace(lat, lon): url = "http://maps.googleapis.com/maps/api/geocode/json?" url += "latlng=%s,%s&amp;sensor=false" % (lat, lon) v = urlopen(url).read() j = json.loads(v) components = j['results'][0]['address_components'] country = town = None for c in components: if "country" in c['types']: country = c['long_name'] if "administrative_area_level_2" in c['types']: town = c['long_name'] return town, country I also have a database with items where most of them (but not all) contains a field with the longitud and a DIFFERENT field with the latitude. There is also some data missing in some rows. reference name lon lat 0 name1 34.0055 1.0041 1 name1 NaN NaN 2 name1 39.5632 3.6854 .... How can I create a new field attached to the DataFrame that cointains the calculated value? I have tried the following statements with no success: df['city'] = getplace(df['lon'], df['lat']) And: df['city'] = df.apply(lambda x : coords(x['lon'], x['lat']) , axis=1) What would be the best way to do this? Thank you very much in advance. EDIT: So I changed the full code to this: from urllib.request import urlopen import json def getplace(lat, lon): if np.isnan(lat)==False: url = "http://maps.googleapis.com/maps/api/geocode/json?" url += "latlng=%s,%s&amp;sensor=false" % (lat, lon) v = urlopen(url).read() j = json.loads(v) components = j['results'][0]['address_components'] country = town = None for c in components: if "country" in c['types']: country = c['long_name'] if "administrative_area_level_2" in c['types']: town = c['long_name'] return town, country import pandas as pd import numpy as np import matplotlib as…
downvote count: 0
score: 1
type: Question

http://stackoverflow.com/q/52233671
answer count: 1
tagged with: laravel
score: 0
has comment: http://stackoverflow.com/comment/91416666
has title: Script executing manually but not executing through PHP.
type: UnansweredQuestion
has body: We have one of the our python script which when executed manually works 100% fine,but when I try to execute it through PHP it is not getting executed. Does not give any exception or error. There is no problem with script path. Is there any way to identify this ??
has comment: http://stackoverflow.com/comment/91416260
has comment: http://stackoverflow.com/comment/91416898
has answer: http://stackoverflow.com/a/52233988
type: Question
tagged with: python
tagged with: php

http://stackoverflow.com/a/52270759
answers question: http://stackoverflow.com/q/52270579
upvote count: 1
has body: Here: body= {now, data2['pagespeed_score'], data2['yslow_score'], Loadedtime, pagesize, data2['page_elements'],} you're passing a set, which doesn't have any equivalent in JSON. You'll have to check the google sheet API documentation for the expected type (probably a dict actually).
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/52162794
has title: Python matplotlib UnicodeEncodeError when resetting rcParams in interactive mode
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91276154
has comment: http://stackoverflow.com/comment/91282317
score: 2
tagged with: matplotlib
has body: Python shows a UnicodeEncodeError when resetting rcParams and using Latex in interactive mode. I use PyCharm 2018.1.4 together with iPython 5.8. Python version is 2.7.15, Matplotlib version is 2.2.2. Input 1 creates the plot, but gives the UnicodeEncodeError: Python 2.7.15 |Anaconda custom (64-bit)| (default, May 1 2018, 23:32:55) [GCC 7.2.0] on linux2 In[2]: import matplotlib.pyplot as plt ...: import numpy as np ...: ...: plt.ion() ...: plt.rcParams['text.usetex'] = True ...: ...: x = np.linspace(-10,10,1000) * 2*np.pi ...: y = np.sin(x) * 10**(-10) ...: ...: plt.plot(x,y) ...: plt.savefig('/home/proxauf/test_unicode1.png') ...: plt.close() ...: ...: plt.rcParams['text.usetex'] = False ...: ...: print "plot 1 successful" ...: Output 1: Backend Qt5Agg is interactive backend. Turning interactive mode on. plot 1 successful Traceback (most recent call last): File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/backends/backend_qt5.py", line 519, in _draw_idle self.draw() File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 433, in draw self.figure.draw(self.renderer) File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper return draw(artist, renderer, *args, **kwargs) File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/figure.py", line 1475, in draw renderer, self, artists, self.suppressComposite) File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/image.py", line 141, in _draw_list_compositing_images a.draw(renderer) File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper return draw(artist, renderer, *args, **kwargs) File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 2607, in draw mimage._draw_list_compositing_images(renderer, self, artists) File "/scratch/seismo/proxauf/conda/lib/python2.7/si…
has comment: http://stackoverflow.com/comment/91277212
tagged with: python-unicode
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/91285865
has comment: http://stackoverflow.com/comment/91284264
tagged with: python
has comment: http://stackoverflow.com/comment/91309674
favorite count: 0
tagged with: latex

http://stackoverflow.com/q/52227687
has body: I'm trying to scrape a website with click button of selenium so i scrape table of many page : * the pattern of table is the same for almost every table suppose we have a list : this is the header of my table it contains 5 columns i put it as a static typing header = ["a", "b", "c", "d", "e"] and a corpus as a list too with 5 columns like : ["abc", "edf", "dfk", "kkk""...", "...", "...", "...", "...", "...", "...", "...", "..."] here's my problem sometimes the columns corresponding to header "b", is missing. so when i'm building my dataFrame like pd.DataFrame(line, columns = header) sometimes len(line) == line(header) so it's ok sometimes not here's my code when it's not working def function(parameters) : .... web scraping .... try : df = pd.DataFrame(table, columns = header) return df except ValueError : print("table and header columns shape mismatch") else : for line in table : # table is corpus list line.insert(1, "None") # i know that every missing columns is the 2nd one so i add None to add that missing columns # in theory shape must match so i build df df = pd.DataFrame(table, columns = header) return df But i still had columns mismatching in error, so i would like to know where's my error or a alternative way. I hope this clear. Thanks.
has title: Handle mismatching shape for dataframe
has comment: http://stackoverflow.com/comment/91405213
type: Question
has comment: http://stackoverflow.com/comment/91406688
has comment: http://stackoverflow.com/comment/91406669
has comment: http://stackoverflow.com/comment/91404932
has comment: http://stackoverflow.com/comment/91405449
tagged with: python
has comment: http://stackoverflow.com/comment/91404884
has comment: http://stackoverflow.com/comment/91405623
answer count: 0
type: UnansweredQuestion
score: 0
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/91406561

http://stackoverflow.com/q/52132207
has title: Extract information from nested dictionaries inside another dictionary
has answer: http://stackoverflow.com/a/52132726
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52132257
tagged with: pandas
has body: the dataset contains 25 columns 500 rows, one of the columns is "orderItems" that contain nested dictionaries, all keys of "orderItems" contain 1 - 15 dictionaries . take one random row, Ex: dataset.orderItems[691581] Result: [{'product': 10152, 'price': 78.76, 'quantity': 1.0}, {'product': 3584, 'price': 20.9, 'quantity': 1.0}, {'product': 20308, 'price': 9.9, 'quantity': 1.0}, {'product': 7619, 'price': 13.9, 'quantity': 1.0}, {'product': 3795, 'price': 15.9, 'quantity': 1.0}, {'product': 6504, 'price': 18.9, 'quantity': 2.0}, {'product': 13720, 'price': 75.9, 'quantity': 1.0}, {'product': 18419, 'price': 31.9, 'quantity': 1.0}] Want to create 3 columns: "product", "price" and "quantity" so that it would fit all the information of all the dictionaries in these columns. Example above would be plus 8 rows extracted from a single value of "orderItems". The price, product and quantity information extracted from "dataset.orderItems[691581]" would divided in these 3 columns each one to his proper column. Remember that somes keys have 1 dictionary, other have 15 (máx) anyone can help me?
possible better answer: http://stackoverflow.com/a/52132257
has comment: http://stackoverflow.com/comment/91215014
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/52132726
has comment: http://stackoverflow.com/comment/91214902
has comment: http://stackoverflow.com/comment/91214937
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/91372107
type: Comment
type: QuestionComment
has text: @Jean-François Fabre I gave examples for each group but I understand what confuse here so I will make it simple. I need to find regex that can match each of the groups. In the end we should end with 5 regexes.
score: 0
comment on: http://stackoverflow.com/q/52210973

http://stackoverflow.com/comment/91466602
type: QuestionComment
comment on: http://stackoverflow.com/q/52255483
has text: @cruisepandey, yes, I can click {"修改"} dropdown button, but don't know how to find && click the {"modify"} element.
score: 0
type: Comment

http://stackoverflow.com/comment/91482021
score: 0
type: Comment
type: QuestionComment
has text: Yup, that's a typo. How are you measuring memory usage?
comment on: http://stackoverflow.com/q/52266003

http://stackoverflow.com/q/52165785
has comment: http://stackoverflow.com/comment/91281840
has answer: http://stackoverflow.com/a/52165907
answer count: 2
has title: How do you programmatically pass in keywords to function in python?
score: -1
has answer: http://stackoverflow.com/a/52165817
downvote count: 1
has comment: http://stackoverflow.com/comment/91281660
favorite count: 0
has comment: http://stackoverflow.com/comment/91281966
type: UnansweredQuestion
tagged with: python
upvote count: 0
tagged with: refactoring
tagged with: keyword
has body: I have some code I'm trying to refactor, which looks a bit like this in python 3: # some_obj.query(streetaddress="burdon") # some_obj.query(area="bungo") # some_obj.query(region="bingo") # some_obj.query(some_other_key="bango") How I can DRY this up so I have something like this? # define a list of tuples like so: set_o_tuples = [ ("streetaddress", "burdon") ("area", "bungo"), ("region", "bingo"), ("some_other_key", "bango"), ]) And then call it in a function for key, val in set_o_tuples: some_obj.query(key=val) When I try to run this code, I get an exception like the following - as Python doesn't like keywords being passed in like this: SyntaxError: keyword can't be an expression What is the idiomatic way to DRY this up, so I don't have to repeat loads of code like the example above? Update: sorry folks, I think the example I put together above missed a few important details. I basically have some pytest code like so def test_can_search_by_location(self, db, docs_from_csv): """ We want to be able to query the contents of all the below fields when we query by location: [ streetaddress, locality, region, postcode] """ search = SomeDocument.search() locality_query = search.query('match', locality="some val") locality_res = locality_query.execute() region_query = search.query('match', region="region val") region_query_res = region_query.execute() postcode_query = search.query('match', postcode="postcode_val") postcode_query_res = postcode_query.execute() streetaddress_query = search.query('match', concat_field="burdon") field_query_res = field_query.execute() location_query = search.query('match', location=concat_value) location_query_res = location_query.execute() assert len(locality_query_res) == len(location_query_res) assert len(region_query_res) == len(location_query_res) assert len(streetaddress_query_res) == len(location_query_res) assert len(postcode_query_res) == len(location_query_res) I was trying to DRY up some of this, as there are similar examples I have,…
type: Question

http://stackoverflow.com/comment/91384140
score: 0
type: Comment
type: QuestionComment
has text: Yes, for every call, I face it at the end of the batch, will try
comment on: http://stackoverflow.com/q/52217422

http://stackoverflow.com/q/52195005
linked to: http://stackoverflow.com/q/186857
has answer: http://stackoverflow.com/a/52195065
upvote count: 4
has comment: http://stackoverflow.com/comment/91339661
has answer: http://stackoverflow.com/a/52195042
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52195057
downvote count: 0
favorite count: 0
type: Question
has title: Convert a comma separated string of key values pairs to dictionary
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/52195042
score: 4
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52195244
has body: I need to convert a comma separated string with key value pairs separated by colon into a dictionary where value is expected to be a float. I'm able to do this to get a dict: &gt;&gt;&gt; s = 'us:0.9,can:1.2,mex:0.45' &gt;&gt;&gt; dict(x.split(':') for x in s.split(',')) which results in: {'us': '0.9', 'can': '1.2', 'mex': '0.45'} but not sure how to force the value to be not a string ie, I'm expecting this: {'us': 0.9, 'can': 1.2, 'mex': 0.45} How to force the values to be floats? Thanks!
possible better answer: http://stackoverflow.com/a/52195254
has comment: http://stackoverflow.com/comment/116864634
has answer: http://stackoverflow.com/a/52195254
answer count: 5

http://stackoverflow.com/q/52256138
tagged with: fabric
tagged with: python
tagged with: cmd
answer count: 0
downvote count: 0
score: 6
has title: Python, Fabric, Windows command line adds weird ^@ (caret-at) symbols during input
type: Question
has comment: http://stackoverflow.com/comment/126063969
upvote count: 6
has comment: http://stackoverflow.com/comment/91655874
has body: I have a remote Ubuntu server VPS, which I connect and do commands via fabric. I using Windows PC to connect to this remote VPS, with this commands: @task def git_pull(): """ """ run("cd ~/{}/; git pull".format(env.repo_name)) When I run this command, it promts me to write my Git's login and password. When I try to input them it writes them like this: (virtualenv) D:\path\to\project\fabfile&gt;fab common.git_pull [1.2.3.4] Executing task 'common.git_pull' [1.2.3.4] run: cd ~/project/; git pull [1.2.3.4] out: Username for 'https://git.example.com': u^@s^@e^@r^@ As you can see when I try to write user it writes it as u^@s^@e^@r^@ It appends this weird caret-at ^@symbols Why windows fabric appends these weird ^@ symbols? Is it because of paramiko which is being used by fabric? I thought this happening because of different encodings and I used chcp command and it still appends these extra symbols.
has comment: http://stackoverflow.com/comment/91665883
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91667485
tagged with: windows
has comment: http://stackoverflow.com/comment/91667372

http://stackoverflow.com/a/70002786
has body: Yes. pd.quantile() will ignore NaN values when calculating the quantile. To prove this, we can compare it with np.nanquantile, which compute the qth quantile of the data along the specified axis, while ignoring nan values[source] . &gt;&gt;&gt; random.seed(7) &gt;&gt;&gt; A = [ random.randint(0,100) for i in range(10) ] &gt;&gt;&gt; B = [ random.randint(0,100) for i in range(10) ] &gt;&gt;&gt; dfAB = pd.DataFrame({'A': A, 'B': B}) &gt;&gt;&gt; dfAB.loc[5:8]=np.nan &gt;&gt;&gt; dfAB A B 0 41.0 7.0 1 19.0 64.0 2 50.0 27.0 3 83.0 4.0 4 6.0 11.0 5 NaN NaN 6 NaN NaN 7 NaN NaN 8 NaN NaN 9 74.0 11.0 &gt;&gt;&gt; dfAB.quantile(0.75) A 68.0 B 23.0 Name: 0.75, dtype: float64 &gt;&gt;&gt; np.nanquantile(dfAB, 0.75, axis=0) array([68. 23.])
score: 3
downvote count: 0
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/52171333

http://stackoverflow.com/comment/91260814
type: Comment
comment on: http://stackoverflow.com/a/52155253
has text: Like when we convert '1.0' string to float, it retains '.0' but not for '1.0e-5'..
type: AnswerComment
score: 0

newline
tags question: http://stackoverflow.com/q/52248391
tags question: http://stackoverflow.com/q/52206248
tag name: newline
type: Tag
tags question: http://stackoverflow.com/q/52196306

http://stackoverflow.com/q/52156867
tagged with: flask
favorite count: 0
tagged with: werkzeug
type: Question
has body: I want to turn incoming HTTP requests' headers into dictionaries and clone them via the "JSON trick." request.headers is an object that acts like a dictionary, but actually isn't a dictionary. json.loads(json.dumps(request.headers)) The above-mentioned line of code results in this error: TypeError: EnvironHeaders([•••]) is not JSON serializable How do I convert a werkzeug.datastructures.EnvironHeaders object to a dictionary? Attempt #1: json.loads(json.dumps({k: v for k, v in request.headers.iteritems()})) Attempt #2: json.loads(json.dumps({k: request.headers[k] for k in request.headers.keys()})) Both of them throw this exception: ValueError: too many values to unpack
has answer: http://stackoverflow.com/a/52157160
score: 5
tagged with: python
tagged with: python-2.x
upvote count: 6
linked to: http://stackoverflow.com/q/45590988
has title: TypeError: EnvironHeaders([•••]) is not JSON serializable
has answer: http://stackoverflow.com/a/77179701
answer count: 2
downvote count: 1
type: UnansweredQuestion
tagged with: python-2.7

http://stackoverflow.com/comment/91302013
comment on: http://stackoverflow.com/a/52175584
score: 0
type: AnswerComment
has text: that is baffling. post an example image?
type: Comment

http://stackoverflow.com/q/52135272
tagged with: python
accepted answer: http://stackoverflow.com/a/52135304
type: AnsweredQuestion
has body: I am a beginner in Python programming. I have checked what the methods does separately, but not getting as a whole. Here is a program was written as a answer for the problem: Write a program to print all elements of an array in reverse order: if __name__ == '__main__': #1 n = int(input()) #2 #3 arr = list(map(int, input().rstrip().split())) #4 for i in range(n): #5 print(arr[-i-1],end=' ') #6 I am not getting line 4. Can anyone explain step by step what that line is doing? How they are working and giving the output as a whole? The inputs were separated by space: 5 #length of the array 1 2 3 4 5 #inputs separated by space
upvote count: 7
has answer: http://stackoverflow.com/a/52135403
type: Question
tagged with: split
has title: Can anyone explain me what this Python 3 command do?
has answer: http://stackoverflow.com/a/52135304
answer count: 3
possible better answer: http://stackoverflow.com/a/52135292
downvote count: 0
score: 7
has answer: http://stackoverflow.com/a/52135292
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/91924010
comment on: http://stackoverflow.com/a/52281257
score: 1
type: AnswerComment
has text: I don't use an IDE, I just type the code into an editor (`vi`, not that it makes any difference) and save it and run it. I tested the code on a Mac and under debian. You know the formatting (indentation) is critical, don't you?
type: Comment

http://stackoverflow.com/q/52266377
possible better answer: http://stackoverflow.com/a/66198371
tagged with: django-forms
has answer: http://stackoverflow.com/a/66198371
type: Question
has body: I'm a newbie in Django and am trying to set up a simple contact form which redirects to a thank you page on successful submission. I'm having trouble getting it to redirect to the thanks page after submission and getting the below error: NoReverseMatch at /contact/ Reverse for 'thanks' not found. 'thanks' is not a valid view function or pattern name. This is my urls.py app_name = 'home' urlpatterns = [ url(r'^$', views.HomePageView.as_view()), url(r'^contact/$', views.ContactView, name='contact'), url(r'^thanks/$', views.ThanksView, name='thanks'), ] and my views.py def ContactView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('thanks') return render(request, 'contact.html', {'form': form}) def ThanksView(request): return render(request, 'thanks.html', {}) I added the templates directory in my settings.py TEMPLATES = [ { 'DIRS': [ os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, '/home', 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', # Third Party Apps 'social_django.context_processors.backends', # &lt;-- 'social_django.context_processors.login_redirect', # &lt;-- ], }, }, ] Can someone please point out where I'm making a mistake? Thanks!
has answer: http://stackoverflow.com/a/52266483
accepted answer: http://stackoverflow.com/a/52266483
has title: Django redirect - not a valid view function or pattern name error
has answer: http://stackoverflow.com/a/66399491
score: 4
answer count: 3
favorite count: 0
tagged with: django
tagged with: python
upvote count: 4
type: AnsweredQuestion
tagged with: django-templates
tagged with: django-views
downvote count: 0

http://stackoverflow.com/a/52201351
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52200710
type: Answer
answers question: http://stackoverflow.com/q/52200710
score: 2
downvote count: 0
has body: I think the best way to go is to split the nested arrays first and then create a facet grid with seaborn. Thanks to this post (Split nested array values from Pandas Dataframe cell over multiple rows) I was able to split the nested array in your dataframe: unnested_lst = [] for col in df.columns: unnested_lst.append(df[col].apply(pd.Series).stack()) result = pd.concat(unnested_lst, axis=1, keys=df.columns).fillna(method='ffill') Then you can make the facet grid with this code: import seaborn as sbn fg = sbn.FacetGrid(result, row='b', col='a') fg.map(plt.scatter, "x", "y", color='blue')
has comment: http://stackoverflow.com/comment/91351779

http://stackoverflow.com/comment/91397230
comment on: http://stackoverflow.com/q/52177889
score: 0
type: Comment
type: QuestionComment
has text: YourProgram() the code you want to run once succesfull so lets say you have a function inside YourProgram.py thats called starta and you want to run this function when user is succesfull then you write YourProgram.starta() if you want the whole file executed simply move the import to the YourProgram() and replace it.

http://stackoverflow.com/comment/91373265
type: QuestionComment
has text: If I am reading your code right, I think `col = X[i]` selects row i; did you want to select column i?
comment on: http://stackoverflow.com/q/52201744
score: 0
type: Comment

http://stackoverflow.com/a/52173630
score: 0
answers question: http://stackoverflow.com/q/52173576
has comment: http://stackoverflow.com/comment/91298241
type: Answer
has comment: http://stackoverflow.com/comment/91304347
has body: I would recommend you to use click. It makes these things very simple http://click.pocoo.org/5/ You need to use groups and maybe multicommand chaining http://click.pocoo.org/5/commands/#group-invocation-without-command http://click.pocoo.org/5/commands/#multi-command-chaining You can create groups and subcommands. Then in each subcommand call the original functions that you are integrating with.

http://stackoverflow.com/comment/91402059
type: Comment
type: QuestionComment
has text: If you just took the repo and ran it without changing anything, you're going to run into issues since you haven't updated the paths - doesn't pertain to the model per se.
score: 0
comment on: http://stackoverflow.com/q/52224820

http://stackoverflow.com/comment/91401977
comment on: http://stackoverflow.com/a/52225940
has text: I'm not sure I understand what you mean by "If the user has permission to the interpreter". Are you saying that I need to create a shared folder from the guest OS to the host OS so that the interpreter that's installed on the guest is available to the host? Would the host computer even be able to execute that Python binary since they are different operating systems?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52126359
has comment: http://stackoverflow.com/comment/91204968
has comment: http://stackoverflow.com/comment/91205069
has body: Try this, in your select {% if paper %} {% for p in paper %} &lt;option value="{{ p.id }}"&gt;{{ p.year }} {{ p.month }} Paper {{ p.number }} &lt;/option&gt; {% endfor %} {% endif %} Also go through this tutorial, django tutorial part 3. Also django models have a default primary key attribute you can use that also.
answers question: http://stackoverflow.com/q/52124719
has comment: http://stackoverflow.com/comment/91204611
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/91209858
has comment: http://stackoverflow.com/comment/91203672
has comment: http://stackoverflow.com/comment/91204202
type: Answer
has comment: http://stackoverflow.com/comment/91203344
has comment: http://stackoverflow.com/comment/91203469
has comment: http://stackoverflow.com/comment/91204580
accepted answer of: http://stackoverflow.com/q/52124719
has comment: http://stackoverflow.com/comment/91203580
has comment: http://stackoverflow.com/comment/91205246

http://stackoverflow.com/comment/91444576
score: 1
has text: @bigwillydos not gonna disagree with that. I'm taking a small step into the unknown to assume that there's actually a valid string, or should we just be close-voting right now?
type: QuestionComment
comment on: http://stackoverflow.com/q/52248287
type: Comment

http://stackoverflow.com/comment/91349406
comment on: http://stackoverflow.com/q/52200155
type: QuestionComment
has text: Impossible to answer without knowledge how your dataframe is supposed to look like.
type: Comment
score: 0

http://stackoverflow.com/comment/91373068
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52210849
type: QuestionComment
has text: The issue is more likely your web-server software (Apache/nginx/lighttpd) and how it is configured. Please show which web-server you use and the corresponding config file.

http://stackoverflow.com/q/52121606
tagged with: django
type: Question
has answer: http://stackoverflow.com/a/52121687
answer count: 1
has body: I am trying to create a django membership models with 2 model classes: Target and Group. I want to have targets attributable to certain groups, but also to be able to query which targets are in which group. This is what I have so far and I am able to see that "targets" is a field of Group but it shows up as empty in the query set when I access Group.objects.get(pk=1) through a variable. I also want both groups and targets to be attributable to certain users. Here are my models, what am I doing wrong? I've tried doing this a few different ways so far: class Target(models.Model): first_name = models.CharField(max_length=50, default='Target First name') last_name = models.CharField(max_length=50, default='Target last name') email = models.EmailField(max_length=100, default='email@example.com') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) date_time = models.DateTimeField(auto_now=True) group = models.ForeignKey(Group, on_delete=models.DO_NOTHING, null=True, blank=True) def __str__(self): return self.email def __unicode__(self): return self.email class Group(models.Model): group_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=50, default='Group name') created_date = models.DateTimeField(auto_now=True) modified_date = models.DateTimeField(null=True, blank=True) targets = models.ManyToManyField(Target, related_name='targets', blank=True, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) def __str__(self): return self.name def __unicode__(self): return self.name
has title: Django - how to create membership models with foreign keys and manytomanyfield
type: UnansweredQuestion
tagged with: python
score: 0

http://stackoverflow.com/a/52238673
has body: with open("text.txt","r") as f: filo = f.readline() l = filo.split(",") k = input("type to chat: ") fila = open("text.txt", "w") fila.write(filo+","+k) fila.close() print(l+[k]) is this what you wanted?
has comment: http://stackoverflow.com/comment/91432180
has comment: http://stackoverflow.com/comment/91431494
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52238539

http://stackoverflow.com/q/52219202
tagged with: odoo
score: 0
has body: I have added a Sync button on the top of tree view header which is supoosed to populate data coming from the api in the tree view This sync button triggers a python function in models.py which is getting data from the api . I want to populate that data in this tree view when i click the Sync button? I am not able to figure it out how to do this?
accepted answer: http://stackoverflow.com/a/52229314
has comment: http://stackoverflow.com/comment/91393335
tagged with: api
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52229314
tagged with: synchronization
type: Question
tagged with: python
has title: Odoo: Adding data which is coming from a api in the tree view by click of a button
answer count: 1

http://stackoverflow.com/comment/91633382
comment on: http://stackoverflow.com/a/52267214
type: AnswerComment
has text: Thanks a lot for the answer. Doing that results to a wrong figure. Instead eg Scen 1 a is the value 13 and for Scen 1 b is 15 I should get 2 and not - 8. Just to say it simple I want to subtract instead to add.
score: 0
type: Comment

http://stackoverflow.com/q/52182433
has answer: http://stackoverflow.com/a/52182865
tagged with: for-loop
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/52182677
possible better answer: http://stackoverflow.com/a/52182513
has answer: http://stackoverflow.com/a/52182513
tagged with: python
answer count: 4
has title: How to change case for alternative letters of a string
has answer: http://stackoverflow.com/a/52182531
score: 0
upvote count: 1
downvote count: 1
type: AnsweredQuestion
has body: I would like to convert every other letter of a string into uppercase. For example provided the input is 'ahdjeryu', the result should be 'AhDjErYu'. I was trying this: def mycode(letters): myword = letters.split() for i in letters: if i%2 == 0: return i.upper() else: return i.lower() print(mycode('ahdjeryu')) The error thrown as: if i%2==0: TypeError: not all arguments converted during string formatting
has comment: http://stackoverflow.com/comment/91314881
accepted answer: http://stackoverflow.com/a/52182531
type: Question

http://stackoverflow.com/comment/91246442
comment on: http://stackoverflow.com/a/52148084
type: Comment
has text: It's always good to learn about some basic CS algorithms and understand their time and space complexity (use a [cheat sheet, no need to memorise specifics](http://bigocheatsheet.com/)). Sort vs heap is one of those fundamental building blocks.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52121773
has title: Preserve capitalization when rotating characters in a string
has comment: http://stackoverflow.com/comment/91195589
has comment: http://stackoverflow.com/comment/91196873
has comment: http://stackoverflow.com/comment/91194992
has comment: http://stackoverflow.com/comment/91196771
has comment: http://stackoverflow.com/comment/91194861
favorite count: 0
has body: I need to edit my rotate function to consider capital letters and I am confused on how to do that Below is my Python code: from helper import alphabet_position, rotate def encrypt(text,key): #Declare variable cipher = '' #Compute length l = len(key) #Assign value idx = 0 #Loop for i in text: #if condition satisfies if i.isalpha(): #Call method cipher += rotate(i,alphabet_position(key[idx])) #Update to next idx = (idx+1)%len(key) #Otherwise else: #Increment cipher += i #Return return cipher #Define main def main(): #Get text from user text = input("Type a message:" ) #Get key from user key = input("Encrption key:" ) #Call method cipher = encrypt(text,key) #Display result print(cipher) #Call main if __name__ == "__main__": main() But returns the following error ✖ ︎For vigenere.encrypt('Sailing &lt;3 ships thru br0ken harbors', You should have returned this: 'Feqwgba &lt;3 fnvta effo ox0xiv syfvbxf' But you actually returned this: 'feqwgba &lt;3 fnvta effo ox0xiv syfvbxf' ✖ ︎For vigenere.encrypt('BaRFoo', 'BaZ') You should have returned this: 'CaQGon' But you actually returned this: 'caqgon' How do I get it to capitalize the first letter? Alphabet position and rotation character are below: import string alphabet_pos = "abcdefghijklmnopqrstuvwxyz" def alphabet_position(letter): pos = alphabet_pos.index(letter.lower()) return pos def rotate(letter, rot): pos = alphabet_position(letter) new_pos = (pos + rot) % 26 new_char = alphabet_pos[new_pos] return new_char
has comment: http://stackoverflow.com/comment/91194934
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91196888
tagged with: python
has comment: http://stackoverflow.com/comment/91196837
has comment: http://stackoverflow.com/comment/91196982
has comment: http://stackoverflow.com/comment/91195062
answer count: 0
upvote count: 3
score: 0
downvote count: 3
has comment: http://stackoverflow.com/comment/91201762
has comment: http://stackoverflow.com/comment/91196313
type: Question

http://stackoverflow.com/a/52147212
downvote count: 0
has comment: http://stackoverflow.com/comment/91301600
has comment: http://stackoverflow.com/comment/91281060
has comment: http://stackoverflow.com/comment/91258368
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52142539
score: 1
has body: You need to set your global variables outside of your event FeastActive = False Feast = True FeastCount = 0 @theclient.event async def on_message(message): global FeastActive global Feast global FeastCount #rest of your code Here is the complete code that works on my end @theclient.event async def on_message(message): global FeastActive global Feast global FeastCount if message.author == theclient.user: return if FeastActive == True: FeastCount += 1 await theclient.send_message(message.channel, ' NOM NOM NOM') if message.content.startswith('!hello'): msg = 'Hello {0.author.mention}'.format(message) await theclient.send_message(message.channel, msg) if message.content.startswith('!joke'): r = requests.get('https://icanhazdadjoke.com', headers={"Accept":"application/json"}).text l = json.loads(r) await theclient.send_message(message.channel, "&lt;@" + message.author.id + "&gt; " + l['joke']) if message.content.startswith('!et_as'): if Feast == True and FeastActive == False: Feast = False FeastActive = True await theclient.send_message(message.channel, "&lt;@" + message.author.id + "&gt; has begun a feast! Hurry, 10 seconds!") await asyncio.sleep(10) FeastActive = False await theclient.send_message(message.channel, "@everyone We have feasted on " + str(FeastCount) +" as! Next feast can start in 3 hours") await asyncio.sleep(5) Feast = True
has comment: http://stackoverflow.com/comment/91306893

http://stackoverflow.com/comment/91177918
comment on: http://stackoverflow.com/q/52113696
score: 0
type: Comment
type: QuestionComment
has text: What have you tried so far?

http://stackoverflow.com/q/52249017
upvote count: 1
answer count: 1
tagged with: numpy
has body: I have the following pandas.core.series.Series: Color Red 4 Green 7 and also the following multiindex dataframe. My goal is to create the Target column in the dataframe by checking if the Value column in the dataframe is less than the corresponding color value in the pandas.core.series.Series and return 1 if that is the case. For example, in the first row, value in Value column within the dataframe is 12 which is more than the corresponding matched index value of 4 in the pandas series object and thus Target returns 0. Value Target Color Animal Red Tiger 12 0 Tiger 3 1 Green Lion 6 1 Lion 35 0 My following attempt gets a ValueError: Can only compare identically-labeled Series objects. import pandas as pd import numpy as np x = pd.Series([4,7], index=['Red','Green']) x.index.name = 'Color' dt = pd.DataFrame({'Color': ['Red','Red','Green','Green'], 'Animal': ['Tiger','Tiger','Lion','Lion'], 'Value': [12,3,6,35]}) dt.set_index(['Color','Animal'], inplace=True) dt['Target'] = np.where(dt['Value'] &lt; x ,1 ,0 )
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/52249053
tagged with: pandas
has title: Comparing non-identical pandas dataframe with a series object
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/52249053

http://stackoverflow.com/q/52170069
favorite count: 0
type: UnansweredQuestion
tagged with: data-visualization
has comment: http://stackoverflow.com/comment/91290783
has comment: http://stackoverflow.com/comment/91290738
upvote count: 1
tagged with: python
has body: I have a dataframe showing sequence of events per session on weblog data, looking like this SessionID EventSequence UrlPath 00001 1 Login 00001 2 Overview 00001 3 Account 00001 4 LogOff 00002 1 Login 00002 2 LogOff 00003 1 Login 00003 2 Account 00003 3 Overview 00003 4 Overview 00003 5 LogOff .... I want to visualize this data in the most efficient, user-friendly way to show the most common paths within sessions in general (thinking of the tree mainly, but can be something else). What would be the most optimal way to visualize sequence of events within data? Can you please share any examples in different domains?
score: 0
has title: What's the best way to visualize sequence of events within pandas in Python?
downvote count: 1
has answer: http://stackoverflow.com/a/52170217
type: Question
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/91421134
score: 0
type: Comment
has text: Works very fast, nice. When I published the question I was also interesting what was the problem is my code, so I hope that if someone sees it he can tell me.
type: AnswerComment
comment on: http://stackoverflow.com/a/52230645

http://stackoverflow.com/q/52240956
has title: What is the difference between the parameters and the shape of a Numpy Binomial Distribution?
tagged with: numpy
tagged with: random
answer count: 2
score: 0
tagged with: python
has body: I am working on a project doing some Bayseian Statistics in Python and am using the Numpy Random Binomial function. However while putting in the keyword arguments/parameters I am a bit confused with some of the basic theory behind this. My set up is the following: trial = np.random.binomial(n, .10, 1) (Where n = 1000) Problem: Say you flip a biased coin (p = .10). Question: Is there a difference between 1000 tosses with .10 probability done once or 1 toss with .10 probably done 1000 times? Which is preferable? Is one more computationally efficient than the other? ie. what is, if there is one, the difference between: np.random.binomial(1000, .10, 1) and np.random.binomial(1, .10, 1000) Or, phrased a different way, what is the difference between the parameters of a distribution and the shape? I have read the Numpy Binomial Docs found here If someone could explain the theory or basic intuition behind this that would be really helpful!
linked to: http://stackoverflow.com/q/23561551
has answer: http://stackoverflow.com/a/52249230
has answer: http://stackoverflow.com/a/52241015
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52249230
accepted answer: http://stackoverflow.com/a/52241015

http://stackoverflow.com/comment/91361453
type: Comment
comment on: http://stackoverflow.com/a/52205790
has text: Definitely a helpful answer but not quite what I'm looking for (since the from column is repeating the dates rather than filling in as a range).
score: 0
type: AnswerComment

http://stackoverflow.com/a/52172876
has comment: http://stackoverflow.com/comment/96699946
upvote count: 11
has comment: http://stackoverflow.com/comment/91300707
answers question: http://stackoverflow.com/q/52168971
accepted answer of: http://stackoverflow.com/q/52168971
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91300773
has body: Aside from the issues with __metaclass__ and the fast-path for an exact type match, __instancecheck__ works in the opposite direction from what you're trying to do. A class's __instancecheck__ checks whether other objects are considered virtual instances of that class, not whether instances of that class are considered virtual instances of other classes. If you want your objects to lie about their type in isinstance checks (you really shouldn't), then the way to do that is to lie about __class__, not implement __instancecheck__. class BadIdea(object): @property def __class__(self): return tuple print(isinstance(BadIdea(), tuple)) # prints True Incidentally, if you want to get the actual type of an object, use type rather than checking __class__ or isinstance.
has comment: http://stackoverflow.com/comment/96699831
type: Answer
score: 11

http://stackoverflow.com/a/52160790
has comment: http://stackoverflow.com/comment/91271291
has body: extraction from bs4 Another alternative is the pure-Python html5lib parser, which parses HTML the way a web browser does. Depending on your setup, you might install html5lib with one of these commands: $ apt-get install python-html5lib $ easy_install html5lib $ pip install html5lib with that being said, you need to still use plural form of find_next_siblings() Also, you will need a parameter to your find_next_siblings() function. example: get_html = 'https://archiwum.polityka.pl/art/sciganiewnbsp;organach,378798.html' soup = bs4(get_html, 'html5lib') find_location = soup.find('div', {'id' : 'container'}) \ .find('div', {'class' : 'middle'}) \ .find('div', {'class', 'right'}) \ .find('div', {'class' : 'box'}) \ .find('p', {'class' : 'box_text'}) \ .find_next_siblings('p') for content in find_location: print(content) Simply change 'html.parser' to 'html5lib' and find_next_siblings('p') then iterate the list() better still, add a conditional statement to remove empty tags for content in find_location: if content.get_text() is not '': print(content) Try it and let me know if it works.
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91274438
answers question: http://stackoverflow.com/q/52160524
has comment: http://stackoverflow.com/comment/91275008
accepted answer of: http://stackoverflow.com/q/52160524

http://stackoverflow.com/comment/96862412
score: 0
type: AnswerComment
has text: Hi there. I am very sorry for just now getting back with you on this matter. Thank you so much for taking the time to respond. I really appreciate your input. It was very helpful.
type: Comment
comment on: http://stackoverflow.com/a/52956868

http://stackoverflow.com/comment/91209230
comment on: http://stackoverflow.com/q/52129445
type: Comment
type: QuestionComment
score: 1
has text: Please read and edit your question according to: [How to make a great R reproducible example?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)

http://stackoverflow.com/comment/91496410
type: Comment
type: QuestionComment
has text: So it means that you have OpenCV 2, because `StereoBM`'s presets like `FISH_EYE_PRESET` were removed in OpenCV 3.0. You should add this in your question.
comment on: http://stackoverflow.com/q/52223767
score: 0

http://stackoverflow.com/comment/91339683
type: QuestionComment
has text: Try `docker exec -it your_container bash` to enter your container and have a check about that file.
comment on: http://stackoverflow.com/q/52194998
score: 0
type: Comment

http://stackoverflow.com/comment/91386720
type: Comment
score: 0
type: QuestionComment
has text: what if 2 lines , how you want to return output ?
comment on: http://stackoverflow.com/q/52219149

http://stackoverflow.com/comment/91188724
type: Comment
comment on: http://stackoverflow.com/q/52118745
has text: The point of `vectorize` is to take a function that only works on one value at a time (e.g., a float) and turn it into a function that takes an array of values and automatically loops over them. That means your code should be expecting `x` to be a float, and using float methods on it, not NumPy array methods. Or, better, it _should_ be using array methods, so you don’t need to use `vectorize` in the first place.
score: 2
type: QuestionComment

http://stackoverflow.com/a/68811771
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52141785
type: Answer
has body: By default, the dictionary is sorted based on keys, but the sorted function takes a function as a parameter using which you can alter the behaviour for program. d={'a':6,'b':4,'k':3} print(sorted(d)) sorted_by_values= sorted(d,key=lambda x:d[x]) print(sorted_by_values)
upvote count: 5
score: 5
answers question: http://stackoverflow.com/q/52141785
type: AcceptedAnswer

http://stackoverflow.com/q/52210323
has comment: http://stackoverflow.com/comment/91370114
has answer: http://stackoverflow.com/a/52210477
tagged with: python
answer count: 4
type: AnsweredQuestion
has body: I'm trying to use Python to solve my maths homework (you have a two digit number ab, and ab+ba=88) and my program doesn't work. a=10 b=10 for i in range(100): a+=1 for i in range(100): b+=1 if int(str(a+b))+int(str(b+a))==88: print((str(a+b))+"+"+str(b+a)) It gives the output of 44. This isn't the good answer, because a and b have to be different numbers, but I didn't code that restriction yet. More important, the code should find 26;62 and other solutions. How can I find all the solutions? I know the answers, but I want to solve it in this way too.
has answer: http://stackoverflow.com/a/52210547
type: Question
has answer: http://stackoverflow.com/a/52210588
possible better answer: http://stackoverflow.com/a/52210477
linked to: http://stackoverflow.com/q/931092
accepted answer: http://stackoverflow.com/a/52210783
has title: What's the problem with my Python script?
score: 0
has comment: http://stackoverflow.com/comment/91370242
has answer: http://stackoverflow.com/a/52210783
tagged with: python-3.x

http://stackoverflow.com/comment/91437560
type: AnswerComment
score: 0
type: Comment
has text: I've editetd the first post to add the ListView. When I use your indication is shown this message: "Cannot find 'key_concepts' on PostModel object, 'key_concepts' is an invalid parameter to prefetch_related()". What is wrong? About the notes that you have add, you are rigth but this is my first project in Django and this type of naming is important to me in development phase. After this phase I will use your indications to have a correct naming.
comment on: http://stackoverflow.com/a/52242871

python-typing
tags question: http://stackoverflow.com/q/52244188
tags question: http://stackoverflow.com/q/52236411
tags question: http://stackoverflow.com/q/52171982
tags question: http://stackoverflow.com/q/52264233
tags question: http://stackoverflow.com/q/52262822
tags question: http://stackoverflow.com/q/52121291
tags question: http://stackoverflow.com/q/52204733
tags question: http://stackoverflow.com/q/52220962
type: Tag
tags question: http://stackoverflow.com/q/52153879
tags question: http://stackoverflow.com/q/52255875
tag name: python-typing

http://stackoverflow.com/comment/91341895
has text: @Bill I don't think I understand. What do you mean by "order might not be the same"?
type: AnswerComment
comment on: http://stackoverflow.com/a/52196192
score: 0
type: Comment

http://stackoverflow.com/comment/91214358
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52131699
has text: @gibbz00 I added an additional setup step where you create a `flag` column. Try that, then try my approaches
type: AnswerComment

http://stackoverflow.com/comment/91375246
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52210272
has text: General solutions and links for dealing with unknown numbers of IN parameters are in https://oracle.github.io/node-oracledb/doc/api.html#sqlwherein I know this is for a different language, but the solutions apply to cx_Oracle, PHP OCI8, and APIs for other languages.
type: AnswerComment

http://stackoverflow.com/q/52158793
has title: Remove duplicates in python dictionary
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52159038
has answer: http://stackoverflow.com/a/52159137
type: Question
score: -4
has body: I have a list of dictionaries in python and I would like to override old value with duplicate value. Please let me know how can I do. {'message': [{'name': 'raghav', 'id': 10}, {'name': 'raghav', 'id': 11}]} Output should be: {'message': [ {'name': 'raghav', 'id': 11}]}
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/91267597
upvote count: 0

http://stackoverflow.com/a/52197710
has comment: http://stackoverflow.com/comment/91349643
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91344840
has comment: http://stackoverflow.com/comment/91350033
has comment: http://stackoverflow.com/comment/91350105
has comment: http://stackoverflow.com/comment/91351442
score: 0
has comment: http://stackoverflow.com/comment/91350225
has comment: http://stackoverflow.com/comment/91351102
has comment: http://stackoverflow.com/comment/91350988
has comment: http://stackoverflow.com/comment/91351227
type: Answer
answers question: http://stackoverflow.com/q/52197472
accepted answer of: http://stackoverflow.com/q/52197472
has body: you can you use geopy https://pypi.org/project/geopy/ &gt;&gt;&gt; from geopy.geocoders import Nominatim &gt;&gt;&gt; geolocator = Nominatim(user_agent="your_app_name") &gt;&gt;&gt; location = geolocator.geocode("jayanagar bangalore") &gt;&gt;&gt; print((location.latitude, location.longitude)) (12.9292731, 77.5824229) &gt;&gt;&gt;
has comment: http://stackoverflow.com/comment/91346298

http://stackoverflow.com/a/52137822
score: 1
answers question: http://stackoverflow.com/q/52135916
type: Answer
has body: For this error : global name 'TimeoutException' is not defined that means u must declare your custom exception .. the simple way to do so is by adding this to your code : class TimeoutException(Exception): pass one thing to mention is that selenium has an exception named TimeoutException which is not an exception type present in the standard library but specific to the selenium library : from selenium.common.exceptions import TimeoutException and finally you will run to an another error ,because your signal handler must recieve the stack frame as the second argument (The handler is called with two arguments: the signal number and the current stack frame) : def handler(signum, frame): raise TimeoutException("Timeout occurred!") please read the following example from the docs minimal example program
upvote count: 1
downvote count: 0

http://stackoverflow.com/a/52198233
has body: to_excel would not append sheets to your existing file: use openpyxl instead:(something like below) import pandas from openpyxl import load_workbook book = load_workbook('path+filename_you_want_to_write_in.xlsx') writer = pandas.ExcelWriter('path+filename_you_want_to_write_in.xlsx', engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) df.to_excel(writer, "Sheet_name_as_per_your_choice",index=False) writer.save() Also if you dynamically want to read through the sheets and not specific sheets: f = pd.ExcelFile(file) sheet_names = df.sheet_names for i in list(sheet_names): df = pd.read_excel(f,i) This iterates through all your sheets and provides a dataframe based on the sheets.
has comment: http://stackoverflow.com/comment/91346311
downvote count: 0
has comment: http://stackoverflow.com/comment/91346751
type: Answer
has comment: http://stackoverflow.com/comment/91346377
answers question: http://stackoverflow.com/q/52197807
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91346282

http://stackoverflow.com/q/52120530
score: 0
has body: Guys i want copy nick of followers Instagram. This is my code but don't work: browser = webdriver.Chrome('./chromedriver') "GO INSTAGRAM PAGE FOR LOGIN" browser.get('https://www.instagram.com/accounts/login/?hl=it') sleep(2) "ID AND PASSWORD" elem = browser.find_element_by_name("username").send_keys('test') elem = browser.find_element_by_name("password").send_keys('pswtest') "CLICK BUTTON AND OPEN INSTAGRAM" sleep(5) good_elem = browser.find_element_by_xpath('//*[@id="react-root"]/section/main/div/article/div/div[1]/div/form/span/button').click() sleep(5) browser.get("https://www.instagram.com") sleep(2) browser.get("https://www.instagram.com/test/") sleep(10) copy = browser.find_element_by_class_name('FPmhX notranslate zsYNt').Text This is Instagram: " a class="FPmhX notranslate zsYNt " title="s_yagami_" href="/s_yagami_/"&gt;s_yagami_ a" I want copy title, help me.
answer count: 1
has answer: http://stackoverflow.com/a/52120586
has comment: http://stackoverflow.com/comment/91203349
tagged with: instagram
has comment: http://stackoverflow.com/comment/91229335
tagged with: python
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/91211774
has title: Copy Title by class INSTAGRAM, selenium python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91277350
tagged with: selenium
type: Question

http://stackoverflow.com/comment/91408136
type: QuestionComment
has text: Did you read the second answer on that question?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52229274

http://stackoverflow.com/comment/91350927
comment on: http://stackoverflow.com/q/52200599
score: 1
has text: Can you post the error as well, please?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91376865
has text: You can just use `enumerate`. Also, if you use `n%i`, you do not need to set counter to 0. for example, `3%3 == 6%3 == 9%3 = 0`, etc ...
type: QuestionComment
comment on: http://stackoverflow.com/q/52213678
type: Comment
score: 1

http://stackoverflow.com/comment/91389273
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52220223
has text: Another trick I tried to fix this was to download the file as "temp" and then rename it to the correct name but I still run into the exact same issue.
score: 0

http://stackoverflow.com/a/52237187
type: Answer
answers question: http://stackoverflow.com/q/52234780
has body: I'm still learning TensorFlow and tfrecordfile usage so I'm not a master of these things, but I've found this guide that was useful in my case and might be useful also for you.
score: 0

algorithm
tags question: http://stackoverflow.com/q/52131390
tags question: http://stackoverflow.com/q/52173272
tag name: algorithm
tags question: http://stackoverflow.com/q/52130087
tags question: http://stackoverflow.com/q/52177162
tags question: http://stackoverflow.com/q/52267964
tags question: http://stackoverflow.com/q/52266049
tags question: http://stackoverflow.com/q/52203775
tags question: http://stackoverflow.com/q/52147403
tags question: http://stackoverflow.com/q/52232880
tags question: http://stackoverflow.com/q/52241264
tags question: http://stackoverflow.com/q/52146019
tags question: http://stackoverflow.com/q/52131612
tags question: http://stackoverflow.com/q/52238780
tags question: http://stackoverflow.com/q/52231686
tags question: http://stackoverflow.com/q/52222756
tags question: http://stackoverflow.com/q/52250960
tags question: http://stackoverflow.com/q/52127288
tags question: http://stackoverflow.com/q/52137431
tags question: http://stackoverflow.com/q/52147351
type: Tag
tags question: http://stackoverflow.com/q/52118889
tags question: http://stackoverflow.com/q/52204231
tags question: http://stackoverflow.com/q/52160366
tags question: http://stackoverflow.com/q/52208453
tags question: http://stackoverflow.com/q/52231442
tags question: http://stackoverflow.com/q/52197656
tags question: http://stackoverflow.com/q/52141874
tags question: http://stackoverflow.com/q/52166501
tags question: http://stackoverflow.com/q/52244225
tags question: http://stackoverflow.com/q/52249551
tags question: http://stackoverflow.com/q/52209977

http://stackoverflow.com/q/52233448
has comment: http://stackoverflow.com/comment/91416152
tagged with: text-recognition
has comment: http://stackoverflow.com/comment/91416462
tagged with: opencv
score: 3
has comment: http://stackoverflow.com/comment/91416735
has comment: http://stackoverflow.com/comment/91417656
has comment: http://stackoverflow.com/comment/91416210
has body: I am using python, PIL, opencv and numpy to detect single color texts (i.e one is red, one is green). I want to detect these colorful text up to 6 meters away during live stream. I have used color detection methods but they did not work after 30-50 cm. Camera should be close to colors. As a second method to detect these texts, I used ctpn method. Although it detects texts, It does not provide the coordinate of these texts since I need coordinate points of texts also. I also tried OCR method in Matlab to automatically detect text in natural image but it failed since it finds another small objects as text. I am so stuck about what to do. Let say for example, there are two different texts in an image that is captured 6 meters away. One text is green, the other one is red. The width of these texts are approximately 40-50 cm. In addition, they are only two different words, not long texts. How can I detect them and specify their location as (x1,y1) and (x2,y2)? Is that possible ? needy for any succesfull hint ? import numpy as np from PIL import Image # Open image and make RGB and HSV versions RGBim = Image.open("AdjustedNewMaze3.jpg").convert('RGB') HSVim = RGBim.convert('HSV') # Make numpy versions RGBna = np.array(RGBim) HSVna = np.array(HSVim) # Extract Hue H = HSVna[:,:,0] # Find all green pixels, i.e. where 100 &lt; Hue &lt; 140 lo,hi = 100,140 # Rescale to 0-255, rather than 0-360 because we are using uint8 lo = int((lo * 255) / 360) hi = int((hi * 255) / 360) green = np.where((H&gt;lo) &amp; (H&lt;hi)) # Make all green pixels black in original image RGBna[green] = [0,0,0] def find_nearest(array, value): array = np.asarray(array) idx = (np.abs(array - value)).argmin() return array[idx] value = 120 &amp; 125 green = find_nearest(RGBna, value) print(green) count = green[0].size print("Pixels matched: {}".format(count)) Image.fromarray(green).save('resultgreen.png')
tagged with: color-detection
type: Question
has comment: http://stackoverflow.com/comment/91416032
has title: How to detect colored text from 6 meters away?
has comment: http://stackoverflow.com/comment/91416595
downvote count: 0
has comment: http://stackoverflow.com/comment/91416362
has comment: http://stackoverflow.com/comment/91415880
tagged with: python
has comment: http://stackoverflow.com/comment/91416781
has comment: http://stackoverflow.com/comment/91416878
tagged with: ocr
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/91418325
upvote count: 3
has comment: http://stackoverflow.com/comment/91416006
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/52179821

http://stackoverflow.com/q/52210577
has comment: http://stackoverflow.com/comment/91370798
linked to: http://stackoverflow.com/q/32122868
type: Question
has comment: http://stackoverflow.com/comment/91370566
has comment: http://stackoverflow.com/comment/91370755
upvote count: 5
has title: Python 2 print functionality in Python 3
has answer: http://stackoverflow.com/a/52210634
has comment: http://stackoverflow.com/comment/91370817
tagged with: python-2.7
has body: I learned that Python 3 print statements require parentheses, but I was told I could do: from __past__ import print but this doesn't seem to work. It gives me an error SyntaxError: Missing parentheses in call to 'print' Any idea what's wrong? Full code: from __past__ import print print 'hello'
answer count: 1
has comment: http://stackoverflow.com/comment/91370768
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91370570
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91370543
has comment: http://stackoverflow.com/comment/91370914
tagged with: python
score: 2
duplicate of: http://stackoverflow.com/q/32122868
downvote count: 3

http://stackoverflow.com/comment/91461514
type: QuestionComment
comment on: http://stackoverflow.com/q/52256983
has text: `DCheck()` quite certainly does take `self.num` into account; the problem is more likely in the code or data that originally set that value. And are you even sure that's where the problem is coming from? (I ask because the time comparison logic in `ACheck()` is broken, you should only be comparing the minutes if the hours were equal.)
score: 0
type: Comment

http://stackoverflow.com/comment/91477652
has text: I did this, but this instance returns the author of the post. Not sure of the syntax to call a specific field?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52264788
type: Comment

http://stackoverflow.com/a/52217541
has body: You can send directly a request using requests, since IE doesn't support settings configuration, and you should handle a popup. A possible implementation could be: import requests def download_pdf_file(url, filename=None, download_dir=None): """ Download pdf file in url, save it in download_dir as filename. """ if download_dir is None: # set default download directory download_dir = r'C:\Users\{}\Downloads'.format(os.getlogin()) if filename is None: # set default filename available index = 1 while os.path.isfile(os.path.join(download_dir, f'pdf_{index}')): index += 1 filename = os.path.join(download_dir, f'pdf_{index}') response = requests.get(url) # get pdf data with open(os.path.join(download_dir, filename), 'wb') as pdf_file: pdf_file.write(response.content) # save it in new file driver.implicitly_wait(5) driver.find_element_by_name("invNumSrchTxt_H").send_keys("ABCDE") #sending the parameters I need driver.find_element_by_name("invDt_B").clear() # Clearing out some preset params driver.find_element_by_name("invDt_A").clear() # This is where I click the button and this pops open a new IE window with my pdf file in it. s=driver.find_element_by_name("Print_Invoice") s.click() driver.download_pdf_file = download_pdf_file driver.download_pdf_file(driver.current_url, # pdf url of the new tab filename='myfile.pdf', # custom filename download_dir='') # relative path to local directory
answers question: http://stackoverflow.com/q/52211657
has comment: http://stackoverflow.com/comment/91401870
has comment: http://stackoverflow.com/comment/91400653
has comment: http://stackoverflow.com/comment/91401702
score: 0
has comment: http://stackoverflow.com/comment/91400814
has comment: http://stackoverflow.com/comment/91404142
has comment: http://stackoverflow.com/comment/91401363
has comment: http://stackoverflow.com/comment/91398789
type: Answer
has comment: http://stackoverflow.com/comment/91401432
has comment: http://stackoverflow.com/comment/91400983
has comment: http://stackoverflow.com/comment/91405945
has comment: http://stackoverflow.com/comment/91399324
has comment: http://stackoverflow.com/comment/91405799
has comment: http://stackoverflow.com/comment/91399402
has comment: http://stackoverflow.com/comment/91403489

http://stackoverflow.com/q/52251292
score: -2
has comment: http://stackoverflow.com/comment/91450459
tagged with: python-2.7
downvote count: 2
has answer: http://stackoverflow.com/a/52251769
accepted answer: http://stackoverflow.com/a/52251769
answer count: 1
has title: Getting index out of bound error in Python
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91450098
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/91450327
has body: I have a list of list in Python table = [[30,100],[25,100],[20,100],[15,00],[10,100],[5,100]] Now I want to implement a logic like below, if 30 > 25 then divide first list second value (100) by 2 and add that value to second list second value (100 + 50) and so on , so in the end result should be like below [30 , 50] [25, 75] [20, 87.5] and so on. I have done like below table = [[30,100],[25,100],[20,100],[15,00],[10,100],[5,100]] print len(table) for i in range(len(table)): print i if table[i][0] &gt; table[i+1][0]: table[i][1] = table[i][1]/2 table[i+1][1]=table[i+1][1] + table[i][1] print table[i][0] , table[i][1] from pprint import pprint pprint(table) but getting error if table[i][0] &gt; table[i+1][0]: IndexError: list index out of range
type: Question

http://stackoverflow.com/comment/91236558
score: 1
has text: I just don't bother with using `six.text_type` - if your code base **must** work under both Python 2 AND Python 3 at the same time, the only way I found reliability is to always prefix human text strings with `u''` and things that are to be `bytes` with `b''`. Don't bother with `six.text_type` because it adds complexity that makes it not work mixing across so many API boundaries (logging/printing/error handling/stack traces).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52143333

http://stackoverflow.com/comment/91291927
type: AnswerComment
comment on: http://stackoverflow.com/a/52161434
type: Comment
has text: Thank you so much. This has given me huge help towards what i want to do. :)
score: 0

http://stackoverflow.com/comment/91227122
type: QuestionComment
has text: input is text strings stored in CSV file. For example: "JavaScript in Internet Explorer 3.x and 4.x" and we need to extract some information like the application version, any file name, variable name that exists in the text. these keyword ["application version", "variable", "file"] can be explicitly or implicitly mentioned in the input. In this example 3.x and 4.x are outputs as application version. The program should be able to detect them and extract. it can work with POS tree and focuses on only NP (noun phrase) of the parse tree to extract these information.
score: 0
comment on: http://stackoverflow.com/q/52134226
type: Comment

http://stackoverflow.com/comment/91273840
score: 1
comment on: http://stackoverflow.com/q/52162165
type: QuestionComment
type: Comment
has text: can you post an example of input-desired output?

http://stackoverflow.com/q/52216247
has title: Using Boolean Flags in Python Click Library (command line arguments)
upvote count: 51
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52224691
type: Question
tagged with: command-line-arguments
has answer: http://stackoverflow.com/a/54509587
accepted answer: http://stackoverflow.com/a/52224691
answer count: 2
tagged with: python-click
possible better answer: http://stackoverflow.com/a/54509587
downvote count: 0
favorite count: 0
score: 51
has body: I'm trying to make a verbose flag for my Python program. Currently, I'm doing this: import click #global variable verboseFlag = False #parse arguments @click.command() @click.option('--verbose', '-v', is_flag=True, help="Print more output.") def log(verbose): global verboseFlag verboseFlag = True def main(): log() if verboseFlag: print("Verbose on!") if __name__ == "__main__": main() It'll never print "Verbose on!" even when I set the '-v' argument. My thoughts are that the log function needs a parameter, but what do I give it? Also, is there a way to check whether the verbose flag is on without global variables?

http://stackoverflow.com/a/52260190
has comment: http://stackoverflow.com/comment/91470907
has body: It sounds like you haven't changed the default ROBOTXT_OBEY setting Set ROBOTXT_OBEY = False and then try. I'll work.
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52259173
answers question: http://stackoverflow.com/q/52259173
has comment: http://stackoverflow.com/comment/91473097
type: Answer

http://stackoverflow.com/comment/91309295
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52179250
has text: These arguments return the class name, not the parent class name. for example, if I have class B which inherits this class, I want the related name field to be B
score: 0

http://stackoverflow.com/comment/91331766
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52190856
has text: Thanks for letting me know. If you're happy I would appreciate it if you could accept the answer :)

http://stackoverflow.com/comment/91255757
score: 0
type: Comment
type: QuestionComment
has text: I cannot get it work.
comment on: http://stackoverflow.com/q/52150763

http://stackoverflow.com/comment/91304412
type: Comment
comment on: http://stackoverflow.com/a/52176711
type: AnswerComment
score: 0
has text: @user2357112: Yeah, that might be good. But it's only intended to show the algorithm. It's also possible to do it functionally, but Python isn't really a functional language. (Also, if most heaps will be rejected immediately, the copy would be a waste of time; better to copy only the ones you need.)

http://stackoverflow.com/q/52117156
has answer: http://stackoverflow.com/a/52126143
accepted answer: http://stackoverflow.com/a/52126143
tagged with: file
has body: I want to upload a file as JSON from the client to a Python webserver (Tornado) and save it on the server. This is my simplified setup: Client HTML: &lt;input type="file" id="myFile" onchange="fileChange" /&gt; Client JS: function fileChange(event) { const file = event.target.files[0]; const fileReader = new FileReader(); fileReader.onload = (e) =&gt; uploadFile(e.target.result, file.name); fileReader.readAsText(file); } function uploadFile(fileContent, fileName) { const data = {fileContent, fileName}; axios.post('http://localhost:8080/api/uploadFile', JSON.srtingify(data)); } Python Webserver: class UploadFileHandler(tornado.web.RequestHandler): def post(self): requestBody = tornado.escape.json_decode(self.request.body) file = open(requestBody["fileName"], "w+") file.write(requestBody["fileContent"].encode("UTF-8")) file.close() All uploaded files are empty (blank pages in a PDF, file type of JPG is 'not supported', Word file cannot be opened) and are nearly twice as big as the original file. How can I fix this? Is there a way to improve this setup?
type: Question
has comment: http://stackoverflow.com/comment/91185250
tagged with: javascript
has comment: http://stackoverflow.com/comment/91185376
score: 0
answer count: 1
tagged with: upload
has title: Upload file as JSON to Python webserver
linked to: http://stackoverflow.com/q/246801
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/52233884
has comment: http://stackoverflow.com/comment/91424920
has body: Try this: from bs4 import BeautifulSoup import requests import pandas as pd from openpyxl import load_workbook book = load_workbook('my2nd_webscrape.xlsx') writer = pd.ExcelWriter('my2nd_webscrape.xlsx') writer.book = book url = 'http://www.baseballpress.com/lineups' soup = BeautifulSoup(requests.get(url).text, 'html.parser') players = [i.text for i in soup.find_all('a', {'class': 'player-link'})] my_dict = (players) df = pd.DataFrame(pd.Series(my_dict)) df.to_excel(writer,'Sheet1') writer.save() writer.close()
upvote count: 1
downvote count: 1
accepted answer of: http://stackoverflow.com/q/52233336
answers question: http://stackoverflow.com/q/52233336
has comment: http://stackoverflow.com/comment/91445147
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/91332190
has text: Did you try Explicit/Implicit wait? Did you check whether element is located inside an iframe?
comment on: http://stackoverflow.com/q/52191015
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91313776
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52181638
score: 0
has text: So you want some method to compute a 3dimensional correlation cube?

http://stackoverflow.com/q/52252528
has answer: http://stackoverflow.com/a/52252886
has comment: http://stackoverflow.com/comment/91452927
tagged with: python-2.7
tagged with: pandas
has body: I have dataframe like this id1 id2 Entry_Date 0 5344265358 55111095504 2018-07-13 00:00:00 1 5344265358 55111095504 2018-07-13 00:00:00 2 5344265358 55111095501 2018-08-13 00:00:00 3 5344265358 55111095502 2018-07-14 00:00:00 4 5441440119 55111366675 2018-08-13 00:00:00 5 5441440119 55111366676 2018-08-20 00:00:00 6 5441440119 55111366677 2018-09-21 00:00:00 7 5441440119 55111366677 2018-09-21 00:00:00 I want to add a new column based on existing column I want to groupby by id1 and id2 then sort on the basis of date and then asign date of next group to previous group but as you can see data has repetitions id1 id2 Entry_Date Next_Date 0 5344265358 55111095504 2018-07-13 00:00:00 2018-07-14 00:00:00 1 5344265358 55111095504 2018-07-13 00:00:00 2018-07-14 00:00:00 2 5344265358 55111095501 2018-08-13 00:00:00 NAN 3 5344265358 55111095502 2018-07-14 00:00:00 2018-08-13 00:00:00 4 5441440119 55111366675 2018-08-13 00:00:00 2018-08-20 00:00:00 5 5441440119 55111366676 2018-08-20 00:00:00 2018-09-21 00:00:00 6 5441440119 55111366677 2018-09-21 00:00:00 NAN 7 5441440119 55111366677 2018-09-21 00:00:00 NAN
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91452802
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
has title: How to add new column on the basis existing columns
type: Question
downvote count: 0

http://stackoverflow.com/comment/91252899
type: Comment
type: QuestionComment
has text: static, not changing.
comment on: http://stackoverflow.com/q/52140930
score: 0

http://stackoverflow.com/q/52254079
answer count: 1
has title: py.test fixtures with global scope
tagged with: python
tagged with: pytest
type: UnansweredQuestion
tagged with: fixtures
type: Question
tagged with: testing
has answer: http://stackoverflow.com/a/52264669
score: 0
has comment: http://stackoverflow.com/comment/91456764
has body: I am looking for a way to use something like "global fixtures" in py.test. It seems that scope="session" would be closest to what I need, but it seems it works similarly to a scope="module" level option. The fixture is initiated total of n times, where n is the number of modules. Basically, I have this slow-to-initialize and resource hungry service that does morphological analysis @pytest.fixture(scope='session', autouse=True) def morfanalyzer(): from myapp.nlp.morfservice import MorfAnalyzerService morfservice = MorfAnalyzerService() def f(): morfservice.run(debug=True) thread = Thread(target=f) thread.start() yield morfservice morfservice.stop() thread.join() And I use it like @pytest.mark.usefixtures(morfanalyzer.__name__) def test_this_stage(morfanalyzer): assert False What I would like to have is that exactly one copy of the service would be spun up before running all the tests and teared down after everything has run.

http://stackoverflow.com/comment/91313685
comment on: http://stackoverflow.com/a/52179264
type: AnswerComment
score: 0
has text: So those daemons are just child threads for which parent process don't wait for completion...? Is this the definition of "daemon"?
type: Comment

http://stackoverflow.com/comment/91455363
type: Comment
comment on: http://stackoverflow.com/q/52250821
score: 0
has text: @NiteyaShah I added the dataset and the complete code. Thank you
type: QuestionComment

http://stackoverflow.com/comment/91399638
has text: I also thought so, but then I tried to use the same batch generator for both training and testing, and the result is the one you see above.
comment on: http://stackoverflow.com/q/52224797
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91325269
type: QuestionComment
has text: No need of repeating the same value unless the same value is included in two or more places in the 6 by 6 matrix.
score: 0
comment on: http://stackoverflow.com/q/52187683
type: Comment

http://stackoverflow.com/comment/91365416
score: 0
comment on: http://stackoverflow.com/a/52205514
type: Comment
has text: It's generally okay not to close the file after reading it unless you're opening a huge number of files and risk running out of file descriptors, or you somehow need to delete it within the same script in Windows.
type: AnswerComment

http://stackoverflow.com/q/52171778
has title: webiopi: html to python to serial
score: 0
answer count: 1
has body: maybe it is an easy fix, maybe I messed up badly. I am lost. Thank you in advance for any help you can give me! So, I have a raspberry pi 2 b+ that has to be mounted on a rover (RC Crawler). I decided to use WebIOPi but I can't find anything useful. My project should work like this: HTML/JS -> PYTHON -> SERIAL TX -> ARDUINO I already have everything I need, and a PWM shield for raspberry is quite expensive here. I managed to get two sliders displaying on my HTML and arduino is ready to receive the command strings. But somewhere in between something is not working. The full codes are at the bottom, here are just some pieces: Here I have one of the two sliders. here I run a script that writes the value on the HTML page formatted as a -89 to 89 range. And I call a WebIOPi Macro called new_steering, passing the value vs (vs should be the value of the slider, from 1 to 179). @webiopi.macro def new_steering(nsv): f = open("slog.txt", "a+") f.write(nsv) news_string = "S{}".format(nsv) f.write(news_string) serial.writeString(news_string) f.close() Within the python code I have the macro that read the incoming value, writes it to a text document (not working nor needed, just to check if it receives the variable), it creates a string with S as leading character and tries to send it trough serial port Something is wrong. I don't know what and how bad. Please help! My tiny head is boiling. I have set up WebIOPi like this: [GPIO] [~GPIO] [SCRIPTS] botler1 = /home/pi/botler1/python/interface.py [HTTP] enabled = true port = 8786 passwd-file = /etc/webiopi/passwd prompt = "BOTLER1_hello" doc-root = /home/pi/botler1 welcome-file = index.html #------------------------------------------------------------------------# [COAP] enabled = true port = 5683 multicast = true [DEVICES] usb1 = Serial device:ttyACM0 baudrate:9600 [REST] gpio-export = 17 gpio-post-value = true gpio-post-function = false [ROUTES] this is the HTML- Web interface WebIOPi | Light Control Steering: Throttle: this is t…
tagged with: webiopi
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/53963543
tagged with: javascript

http://stackoverflow.com/q/52177162
tagged with: breadth-first-search
type: Question
tagged with: graph-theory
answer count: 2
has comment: http://stackoverflow.com/comment/91304582
tagged with: algorithm
linked to: http://stackoverflow.com/q/15013956
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/91305820
downvote count: 1
has body: This is my node definition : class Node(object): def __init__(self, val, children): self.val = val self.children = children Now I've to find max depth in the tree. I'm using breadth-first search to mark the level of each node, then returning the max of levels. This is my code : def maxDepth(self, root): """ :type root: Node :rtype: int """ if(root == None): return 0 q = [] q.append(root) level={root.val:1} while(len(q)&gt;0): s = q.pop(0) for c in s.children: q.append(c) level[c.val]=level[s.val]+1 return max(level.values()) It's working on some cases but giving the wrong answer in many cases. I don't understand where I'm missing the concept?
has answer: http://stackoverflow.com/a/52179570
favorite count: 0
has comment: http://stackoverflow.com/comment/91304639
has comment: http://stackoverflow.com/comment/91304611
has title: How to find max depth of n-ary tree using bfs?
tagged with: python
has comment: http://stackoverflow.com/comment/91305416
possible better answer: http://stackoverflow.com/a/52179570
has answer: http://stackoverflow.com/a/52177750
tagged with: tree
accepted answer: http://stackoverflow.com/a/52177750
type: AnsweredQuestion

http://stackoverflow.com/comment/91443291
has text: Smells like premature optimization (and I'm hesitant to even call it that). Most likely all you need is to grab two ROIs, which has negligible cost. Even if you had to copy the two halves, the cost will be quite trivial compared to any meaningful processing. | I'd say focus on the important part, the processing. When you've got that working and your measurements identify image acquisition as a bottleneck, you can always come back and try to improve it.
comment on: http://stackoverflow.com/q/52247001
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52189935
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/91373553
tagged with: javascript
score: 0
tagged with: extjs
has title: The problem is when changing the proxy type to ajax in Ext.data.Store on ExtJs
tagged with: django
tagged with: python
has body: My problem is when I change the type in the Store to ajax. The store in my application looked like this: var urlRoot = 'data?model=Operation&amp;method='; Ext.define('BookApp.store.BookStore', { extend: 'Ext.data.Store', model: 'BookApp.model.Book', autoLoad: true, storeId: 'BookStore', proxy: { type: 'jsonp', noCache: false, api: { create: urlRoot + 'Create', read: urlRoot + 'Read', update: urlRoot + 'Update', destroy: urlRoot + 'Destroy' }, reader: { type: 'json', metaProperty: 'meta', rootProperty: 'data', idProperty: 'id', totalProperty: 'meta.total', successProperty: 'meta.success' }, writer: { type: 'json', encode: true, writeAllFields: true, rootProperty: 'data', allowSingle: false } } }); When I change the store type to ajax ..... proxy: { type: 'ajax', ..... then when I download the application I get error 500 (Internal Server Error) I know that the jsonp type is required to load data from another domain on which my application is running, but I have the entire application and the database included, is on the same local machine, so I set the type of ajax. But with this type a problem arises. On the backend side, the answer is as follows: ... # Form the answer dict_out= {"data" : list, "meta": { "success": "true", "msg": "", "total": str(count) }} # Translate it into the format Json jsonFormat = json.dumps(dict_out) # Add to the answer callback read_out = dict['callback'] +'(' + jsonFormat + ')' return HttpResponse(read_out) .... Error in browser Why can this problem occur? Thank you
answer count: 0
has comment: http://stackoverflow.com/comment/91333839

http://stackoverflow.com/q/52242954
has body: I'm reading someone's code, and there is written get_object_or_404(Order, id=-1) Could someone explain the purpose of id=-1?
score: 1
favorite count: 0
type: Question
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91434398
upvote count: 2
has answer: http://stackoverflow.com/a/52243028
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91434167
has title: What does it mean when written id=-1 in django request?
accepted answer: http://stackoverflow.com/a/52243028
type: AnsweredQuestion

http://stackoverflow.com/a/52211316
has body: So, one obvious approach that works is to use the database's built-in iterator: &gt;&gt;&gt; m_t_f_l_u = next(_a for _a in Database('ei3.4 cutoff') \ if _a['name'] == 'market for transport, freight, lorry, unspecified' \ and _a['location'] == 'GLO') This works. It doesn't seem very efficient, though, and it takes several seconds to run.
answers question: http://stackoverflow.com/q/52194357
score: 0
has comment: http://stackoverflow.com/comment/91612005
type: Answer

http://stackoverflow.com/comment/91265935
type: Comment
type: QuestionComment
has text: @alvas It will be grt if you can show how to implement my case since I am getting lost. If you want me to change the way I am converting to tuples to dictionary then please show that rather than giving a github link
score: 0
comment on: http://stackoverflow.com/q/52148690

http://stackoverflow.com/a/52117356
has body: If you already have a script the does the testing and notifies you (for example via email or Pushover, the implementation in Python is not too hard), set up a cron job: Open a terminal and type crontab -e, select your editor if you are asked and add the following line: * */X * * * python /path/to/testscript.py where X should be replaced by how often you want to test. For example, if you write 3 instead of X, every 3 hours your script will be executed.
answers question: http://stackoverflow.com/q/52117056
score: 0
accepted answer of: http://stackoverflow.com/q/52117056
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/91265533
comment on: http://stackoverflow.com/q/52157604
score: 0
type: Comment
has text: No, it's not equivalent to that at all. It assigns the result of `var2 == var3` to `var1`
type: QuestionComment

http://stackoverflow.com/q/52235537
has body: I have a list of strings that follow a pattern such that in some position in the string there may be a substring RAM. ex: sdfjhsk_sdkjfhs_RAM_lkfdgjls Sometimes this string may have another character after it. ex: aaaa_RAMA_sfsffgd I'd need to have the whole context between the nearest underscores, so RAM in the first case, RAMA in the second. And it may not even exist at all in the string ex: sfdks_sdfsdf_sdfsdf_sdfsdfsdf Matches at the start or end of the string are allowed: RAMsdoa_saeorfioa_noutd -&gt; RAMsdoa aetu_eaei_sdsdf_RAMSdoa -&gt; RAMsdoa as are matches in strings without underscores: sdasids -&gt; nothing sdfRAMso -&gt; sdfRAMso What is the best way to search the string and if it contains the pattern RAM and if it does, grab everything in between the nearest delimiters _ (or the start or end of the string, if nearer)?
tagged with: python
tagged with: regex
answer count: 1
downvote count: 3
accepted answer: http://stackoverflow.com/a/52235587
has comment: http://stackoverflow.com/comment/91419544
tagged with: find
upvote count: 0
has title: Python If substring exists in string, get its context between relimiters
score: -3
tagged with: search
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91419574
has answer: http://stackoverflow.com/a/52235587
favorite count: 0
type: Question

http://stackoverflow.com/comment/91313096
has text: @JPG I don't think that has anything for many-to-many with duplicates.
score: 0
comment on: http://stackoverflow.com/q/52181389
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91476191
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52260093
score: 1
has text: You can add it in the `setup.py` which is just a normal Python script where you call the special `setup` function

peewee
tag name: peewee
type: Tag
tags question: http://stackoverflow.com/q/52194872
tags question: http://stackoverflow.com/q/52183057

http://stackoverflow.com/q/52147751
tagged with: python
has comment: http://stackoverflow.com/comment/91253131
has answer: http://stackoverflow.com/a/52148913
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/91253419
tagged with: django-models
has comment: http://stackoverflow.com/comment/91253711
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91252976
has body: Description: I want to add a new field to an existing Django model. The value of this field for each instance can be computed using an external API. Since there are already a large number of instances saved in the database and the external API has a quota, it is not a good idea to compute this field for every instance on database migration. It worths mentioning that this field will be rarely accessed. Question: Is it possible to compute the value, only on the first access to that specific field and save it in the database for future uses? Is there an standard way of handling this situation?
answer count: 1
has title: Compute Django Model Field Value on First Access (Lazy Field)
has comment: http://stackoverflow.com/comment/91245393
has comment: http://stackoverflow.com/comment/91253566

http://stackoverflow.com/comment/91422586
score: 0
type: AnswerComment
has text: Note, there are a good few other errors in your code. Things like: "if a[0] and b[0] is 'a' or 'b' or 'c' or 'd' or 'e'" are not going to evaluate the way you think they are. I just addressed the main question in the post.
type: Comment
comment on: http://stackoverflow.com/a/52237031

encode
tags question: http://stackoverflow.com/q/52202924
type: Tag
tags question: http://stackoverflow.com/q/52202630
tag name: encode
tags question: http://stackoverflow.com/q/52179465

http://stackoverflow.com/comment/91492285
type: Comment
comment on: http://stackoverflow.com/q/52260568
score: 0
type: QuestionComment
has text: do you always have to give the `type`? If your `id` is unique, you could order the list by id and then directly access the element at a specific position

http://stackoverflow.com/comment/91461655
type: Comment
has text: Thanks for contributing and welcome to stackoverflow! Please describe what you changed and why you did it, so that the question's author and future visitors can learn from your answer.
score: 2
comment on: http://stackoverflow.com/a/52255395
type: AnswerComment

http://stackoverflow.com/q/52171736
possible better answer: http://stackoverflow.com/a/52172018
has answer: http://stackoverflow.com/a/52172018
tagged with: pandas
favorite count: 0
accepted answer: http://stackoverflow.com/a/52171828
has comment: http://stackoverflow.com/comment/91294379
has body: I currently have this df where the rect column is all strings. I need to extract the x, y, w and h from it into separate columns. The dataset is very large so I need an efficient approach df['rect'].head() 0 &lt;Rect (120,168),260 by 120&gt; 1 &lt;Rect (120,168),260 by 120&gt; 2 &lt;Rect (120,168),260 by 120&gt; 3 &lt;Rect (120,168),260 by 120&gt; 4 &lt;Rect (120,168),260 by 120&gt; So far this solution works however it's very messy as you can see df'x', 'y', 'w', 'h' = df['rect'].str.replace('&lt;Rect \(', '').str.replace('\),', ',').str.replace(' by ', ',').str.replace('&gt;', '').str.split(',', n=3, expand=True) Is there a better way? Possibly a regex approach
has title: Pandas extract numbers from column into new columns
has answer: http://stackoverflow.com/a/52171838
answer count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/91294733
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52171831
has answer: http://stackoverflow.com/a/52171799
type: Question
score: 5
has answer: http://stackoverflow.com/a/52171828
upvote count: 5
downvote count: 0

http://stackoverflow.com/comment/91246102
score: 2
comment on: http://stackoverflow.com/q/52147485
type: Comment
type: QuestionComment
has text: Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Super User](http://superuser.com/) or [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) would be a better place to ask.

http://stackoverflow.com/a/52215271
score: 1
upvote count: 1
has body: You can use Q objects to filter results with oring Something like below from django.db.models import Q Entry.objects.filter(Q(number=123) | Q(name="abc")) There are more ways to use Q objects refer the docs.
accepted answer of: http://stackoverflow.com/q/52215194
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52215194

http://stackoverflow.com/comment/91333988
type: Comment
type: QuestionComment
has text: You can develop your own Jinja template loader to load templates from a different source. But your "immediately used by the live application" is not that easy because templates are cached.
score: 1
comment on: http://stackoverflow.com/q/52174695

http://stackoverflow.com/q/52155939
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91262411
has answer: http://stackoverflow.com/a/52156092
has body: I have a 1D array of numbers from which I need to plot a histogram in Python3. The bin boundaries are also available with me: bins = [1,2,3,4,5] plt.hist(data, bins=bins, histtype='step') Now, if I want to shift the histogram horizontally by 1 unit on the x-axis, how can I achieve that? I don't want the shape or the bin boundaries to change, I just want the whole histogram to move on the x-axis. If the histogram can be represented as f(x), I am looking for f(x-x0).
downvote count: 2
has answer: http://stackoverflow.com/a/52156002
type: Question
has answer: http://stackoverflow.com/a/52156015
score: 0
has title: How to horizontally shift a histogram in Python?
answer count: 3
has comment: http://stackoverflow.com/comment/91262152

http://stackoverflow.com/comment/91414509
comment on: http://stackoverflow.com/q/52232548
score: 0
has text: @JohanL Yeah , you are right!
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/102257405
has text: yes they are immutable because the second line creates a new string. `s` is only a name or label assigned to the string. In the first line `s` is assigned to 'Hello World'. In the second line `s` is assigned to the new string 'Heiio Worid'. The original string 'Hello World' is still there, but is not assigned to any variable and will therefore be removed from memory by the garbage collector. Neither of the strings have changed, only the variables are reassigned.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/57919468

http://stackoverflow.com/q/52169137
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91288766
has comment: http://stackoverflow.com/comment/91288950
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91292861
tagged with: django
tagged with: python
has body: Hi I am completely new to python and implementing ORM for first time in mysql. we have three two tables and one intermediary table as shown in below diagram below is the code we are using to create models class Roles(models.Model): """ A class that stores all the types of roles that are available to the user """ role_id = models.CharField(max_length=200, blank=False,primary_key=True) role_name = models.CharField(max_length=200) class Meta: db_table = 'roles' managed = False class User(AbstractBaseUser): # class ChannelUser(models.Model): """ An abstract base class implementing a fully featured User model with admin-compliant permissions. """ user_id = models.CharField(max_length=200, blank=False,primary_key=True) user_email = models.EmailField(max_length=200, blank=False, unique=True) roles=models.ManyToManyField( Roles, through='UserRole', # through_fields=('user_id', 'role_id'), ) USERNAME_FIELD = 'user_email' class Meta: db_table = 'user' managed = False class UserRole(models.Model): """ A class that stores user ids and role ids """ user = models.ForeignKey(User, on_delete=models.PROTECT, db_column='user_id') role = models.ForeignKey(Roles, on_delete=models.PROTECT, db_column='role_id') timestamp = models.DateTimeField(default=timezone.now) class Meta: db_table = 'user_roles' managed = False We are trying to fetch all the Roles associated with User, but it gives None for roles. I am not sure, what we are doing wrong here. can somebody please point it out. Below is the code I am using to fetch roles user_detail = User.objects.get(user_email=username) print(user_detail.user_email) //prints user email print(user_detail.roles) // prints Roles.None settings.py AUTH_USER_MODEL = "login_api.User"
has answer: http://stackoverflow.com/a/52171861
has comment: http://stackoverflow.com/comment/91292856
type: Question
has comment: http://stackoverflow.com/comment/91295561
has title: many to many relationship in django database model
tagged with: django-models
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/91295449

kivy
tags question: http://stackoverflow.com/q/52202960
tags question: http://stackoverflow.com/q/52202538
type: Tag
tags question: http://stackoverflow.com/q/52239029
tags question: http://stackoverflow.com/q/52207252
tags question: http://stackoverflow.com/q/52246202
tags question: http://stackoverflow.com/q/52146482
tags question: http://stackoverflow.com/q/52242296
tags question: http://stackoverflow.com/q/52140710
tags question: http://stackoverflow.com/q/52254560
tags question: http://stackoverflow.com/q/52177947
tags question: http://stackoverflow.com/q/52129333
tags question: http://stackoverflow.com/q/52151553
tags question: http://stackoverflow.com/q/52168199
tags question: http://stackoverflow.com/q/52232740
tags question: http://stackoverflow.com/q/52242939
tags question: http://stackoverflow.com/q/52134151
tags question: http://stackoverflow.com/q/52266572
tags question: http://stackoverflow.com/q/52119287
tags question: http://stackoverflow.com/q/52125938
tags question: http://stackoverflow.com/q/52118695
tags question: http://stackoverflow.com/q/52222205
tags question: http://stackoverflow.com/q/52181072
tags question: http://stackoverflow.com/q/52171916
tags question: http://stackoverflow.com/q/52176106
tags question: http://stackoverflow.com/q/52126516
tag name: kivy
tags question: http://stackoverflow.com/q/52152053
tags question: http://stackoverflow.com/q/52136449
tags question: http://stackoverflow.com/q/52203580
tags question: http://stackoverflow.com/q/52267177
tags question: http://stackoverflow.com/q/52259995
tags question: http://stackoverflow.com/q/52200823
tags question: http://stackoverflow.com/q/52154496
tags question: http://stackoverflow.com/q/52230227
tags question: http://stackoverflow.com/q/52218031
tags question: http://stackoverflow.com/q/52122218
tags question: http://stackoverflow.com/q/52234171
tags question: http://stackoverflow.com/q/52180246
tags question: http://stackoverflow.com/q/52160225
tags question: http://stackoverflow.com/q/52193511

http://stackoverflow.com/comment/91375582
comment on: http://stackoverflow.com/a/52212966
type: AnswerComment
has text: I also think the package is broken as I am not getting any functions under help(wordcloud). By the way thanks.
type: Comment
score: 0

http://stackoverflow.com/a/52217792
score: 0
has body: "Aim:" must be in each line of "data" so I'll find the index for this word("Aim:") p = "Automatic Product Title Tagging Aim: To automate the process of product title tagging using manually tagged data." index = p.find("Aim:") # 33 print(p[33:]) output: "Aim: To automate the process of product title tagging using manually tagged data." w_lenght = len("Aim:") # 4 : for exclude word "Aim:" print(p[37:]) output: " To automate the process of product title tagging using manually tagged data." example: s = ['tagged', 'product title', 'tagging', 'analyze'] skills = [] for line in data.split("\n"): index = line.find("Aim:") + len("Aim:") #4 if index != -1: for word in line[index:].split(): if word.lower() in s: skills.append(word) print(word)
type: Answer
answers question: http://stackoverflow.com/q/52217036

http://stackoverflow.com/a/52250197
score: 3
answers question: http://stackoverflow.com/q/52250025
downvote count: 0
has comment: http://stackoverflow.com/comment/91522547
has body: What is stacking ? Stacking is an ensemble learning technique to combine multiple classification models via a meta-classifier. The individual classification models are trained based on the complete training set; then, the meta-classifier is fitted based on the outputs -- meta-features -- of the individual classification models in the ensemble. Source : StackingClassifier-mlxtend So meta_classifier parameter helps us to choose the classifier to fit the output of the individual models. Example: Assume that you have used 3 binary classification models say LogisticRegression, DT &amp; KNN for stacking. Lets say 0, 0, 1 be the classes predicted by the models. Now we need a classifier which will do majority voting on the predicted values. And that classifier is the meta_classifier. And in this example it would would pick 0 as the predicted class. You can extend this for prob values also. Refer mlxtend-API for more info
type: Answer
upvote count: 3

http://stackoverflow.com/q/52148141
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/52158044
answer count: 1
favorite count: 0
upvote count: 2
tagged with: lmfit
linked to: http://stackoverflow.com/q/26502597
has body: I need to fit a two dimensional Gaussian to a data set I read in. My choice of fitting routine is lmfit, as it allows easy implementation of boundary conditions and fixing of parameters. As I am not the most efficient progammer, I have problems implementing my needs. Here is what I did: from numpy import * from math import * from lmfit import Parameters,minimize,report_fit ## fails to run # from https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-79.php x,y = meshgrid(linspace(-1,1,10),linspace(-1,1,10)) #d = sqrt(x*x+y*y) #sigma, mu = 1.0, 0.0 #g = exp(-( (d-mu)**2 / ( 2.0 * sigma**2 ) ) ) def gaussian2D(p,x,y): height = p["height"].value centroid_x = p["centroid_x"].value centroid_y = p["centroid_y"].value sigma_x = p["sigma_x"].value sigma_y = p["sigma_y"].value background = p["background"].value return height*exp(-(((centroid_x-x)/sigma_x)**2+((centroid_y-y)/sigma_y)**2)/2.0)+background def residuals(p,x,y,z): return z - gaussian2D(p,x,y) initial = Parameters() initial.add("height",value=1.) initial.add("centroid_x",value=0.) initial.add("centroid_y",value=0.) initial.add("sigma_x",value=1.) initial.add("sigma_y",value=3.) initial.add("background",value=0.) xx,yy = meshgrid(x,y) fit = minimize(residuals,initial,args=(array(xx).flatten(),array(yy).flatten(),array(g).flatten())) popt = fit.params print report_fit(fit) First of all, the sample code to generate a 2D Gaussian fails to run and gives a "TypeError: only size-1 arrays can be converted to Python scalars" for d = sqrt(xx+yy). As I am using data from a file anyway, I am working with the sample data given on the website here. Some research told me to convert the 2D arrays into 1D data in order for lmfit to be able to process them. My attempts to implement that using the flatten method on my arrays is unsuccessful, giving the same error (TypeError: only size-1 arrays can be converted to Python scalars). I am not versed enough to fully understand the code in the link. I would appreciate any…
tagged with: curve-fitting
tagged with: python
has title: 2D Gaussian fit using lmfit
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/52158044

http://stackoverflow.com/q/52199446
downvote count: 2
answer count: 1
has body: For example: Positives=negatives=[] If True: Positives += [number] else: Negatives += [number] Now this part of code actually breaks the list into two others. But why the method append which does exactly the same doesn't work,and just puts objects in the same list?
type: UnansweredQuestion
has title: How to break two variables that address to the same list in Python
upvote count: 0
has comment: http://stackoverflow.com/comment/91348003
has answer: http://stackoverflow.com/a/52199504
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/91347970
tagged with: python
score: -2

http://stackoverflow.com/comment/91267236
type: Comment
comment on: http://stackoverflow.com/a/52151005
score: 0
type: AnswerComment
has text: In that case pass self as parameter into the new_window function. That should fix the problem :)

http://stackoverflow.com/q/52263338
has comment: http://stackoverflow.com/comment/91479072
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91513890
tagged with: miniconda
tagged with: anaconda
tagged with: conda
type: Question
has title: Conda doesn't find local package to install, although it's present in the environment's conda-bld directory
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91476775
has answer: http://stackoverflow.com/a/60093922
has comment: http://stackoverflow.com/comment/91480603
tagged with: packaging
favorite count: 0
score: 3
tagged with: python
has comment: http://stackoverflow.com/comment/91510377
has body: I have built a conda package from my PyPI package using conda-build. $ cd $ conda skeleton pypi climate_indices $ ll climate_indices/ total 6 -rw-r--r-- 1 DELL 197121 107 Sep 10 10:02 bld.bat -rw-r--r-- 1 DELL 197121 81 Sep 10 10:02 build1.sh -rw-r--r-- 1 DELL 197121 1088 Sep 9 15:29 meta.yaml $ conda-build climate_indices $ ls -l /c/home/miniconda3/envs/packaging/conda-bld/win-64/ total 73 -rw-r--r-- 1 DELL 197121 58736 Sep 10 13:11 climate_indices-1.0.0-py37h39e3cac_0.tar.bz2 -rw-r--r-- 1 DELL 197121 2091 Sep 10 13:11 index.html -rw-r--r-- 1 DELL 197121 707 Sep 10 13:11 repodata.json -rw-r--r-- 1 DELL 197121 417 Sep 10 13:11 repodata.json.bz2 -rw-r--r-- 1 DELL 197121 825 Sep 10 13:11 repodata2.json I next try to install it into the environment and this step fails: $ conda install --use-local climate_indices Solving environment: ...working... failed PackagesNotFoundError: The following packages are not available from current channels: - climate_indices Current channels: - https://repo.anaconda.com/pkgs/main/win-64 - https://repo.anaconda.com/pkgs/main/noarch - https://repo.anaconda.com/pkgs/free/win-64 - https://repo.anaconda.com/pkgs/free/noarch - https://repo.anaconda.com/pkgs/r/win-64 - https://repo.anaconda.com/pkgs/r/noarch - https://repo.anaconda.com/pkgs/pro/win-64 - https://repo.anaconda.com/pkgs/pro/noarch - https://repo.anaconda.com/pkgs/msys2/win-64 - https://repo.anaconda.com/pkgs/msys2/noarch To search for alternate channels that may provide the conda package you're looking for, navigate to https://anaconda.org and use the search bar at the top of the page. It looks to me that it's maybe ignoring the --use-local option. Why is this not working as I expect (i.e. as described here)?

http://stackoverflow.com/comment/91894103
score: 0
type: Comment
type: QuestionComment
has text: Is there an error msg?
comment on: http://stackoverflow.com/q/52252269

http://stackoverflow.com/q/52190243
downvote count: 0
favorite count: 0
has body: I have a dataframe (named df) sorted by identifier, id_number and contract_year_month in order like this so far: **identifier id_number contract_year_month collection_year_month** K001 1 2018-01-03 2018-01-09 K001 1 2018-01-08 2018-01-10 K001 2 2018-01-01 2018-01-05 K001 2 2018-01-15 2018-01-18 K002 4 2018-01-04 2018-01-07 K002 4 2018-01-09 2018-01-15 and would like to add a column named 'date_difference' that is consisted of contract_year_month minus collection_year_month from previous row based on identifier and id_number (e.g. 2018-01-08 minus 2018-01-09), so that the df would be: **identifier id_number contract_year_month collection_year_month date_difference** K001 1 2018-01-03 2018-01-09 K001 1 2018-01-08 2018-01-10 -1 K001 2 2018-01-01 2018-01-05 K001 2 2018-01-15 2018-01-18 10 K002 4 2018-01-04 2018-01-07 K002 4 2018-01-09 2018-01-15 2 I already converted the type of contract_year_month and collection_year_month columns to datetime, and tried to work on with simple shift function or iloc but neither doesn't work. df["date_difference"] = df.groupby(["identifier", "id_number"])["contract_year_month"] Is there any way to use groupby to get the difference between the current row value and previous row value in another column, separated by two identifiers? (I've searched for an hour but couldn't find a hint...) I would sincerely appreciate if you guys give some advice.
has comment: http://stackoverflow.com/comment/91330751
tagged with: python
has answer: http://stackoverflow.com/a/52190528
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52190602
has title: pandas subtracting value in another column from previous row
has comment: http://stackoverflow.com/comment/91330913
type: Question
possible better answer: http://stackoverflow.com/a/52190602
accepted answer: http://stackoverflow.com/a/52190528
score: 4
upvote count: 4
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/91331195

http://stackoverflow.com/comment/91335362
comment on: http://stackoverflow.com/q/52173535
has text: @MichaelButscher fantastic, after redirecting `sys.stderr` produced `'ImportError: Missing required dependencies ['numpy']'`. make it an answer if you need points
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52134811
answers question: http://stackoverflow.com/q/52134538
has comment: http://stackoverflow.com/comment/91219753
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91219652
has comment: http://stackoverflow.com/comment/91219780
has body: i think the problem lies here def insert(self,val): currentNode = self.root if currentNode is None: currentNode = Node(val) elif currentNode.info &gt; val: currentNode.left = insert(currentNode.left,val) elif currentNode.info &lt; val: currentNode.right = insert(currentNode.right,val) return currentNode as you can see you do "insert" the node but you dont assign it, the code block if currentNode is None: currentNode = Node(val) should be if currentNode is None: self.root = Node(val) you keep on trying to traverse a Null tree EDIT: Its possible that this is not the problem, please provide the full code the create() function is missing from your code but is called
has comment: http://stackoverflow.com/comment/91219765
has comment: http://stackoverflow.com/comment/91219668
has comment: http://stackoverflow.com/comment/91219687

http://stackoverflow.com/q/52203512
tagged with: plot
type: Question
accepted answer: http://stackoverflow.com/a/74403047
type: AnsweredQuestion
score: 1
tagged with: plotly
has title: Wrong dates in the index plotly with a second graph I did not ask for
tagged with: graph
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91356444
has answer: http://stackoverflow.com/a/74403047
tagged with: candlestick-chart
has body: I am trying to plot some graphs with plotly and, after several times having the wrong graph, i backed to the basics and tried to plot an example from the plotly web, but the same error appears: My dates are not dates, but an extremely high number (10^18 order) and I get a second small graph that noone asked for. import plotly.plotly as py import plotly.graph_objs as go import pandas_datareader as web from datetime import datetime import fix_yahoo_finance as yf yf.pdr_override() df = web.DataReader("aapl", 'robinhood').reset_index() trace = go.Candlestick(x=df.Date, open=df.Open, high=df.High, low=df.Low, close=df.Close) data = [trace] py.plot(data, filename='simple_candlestick') I just changed the source (morningstar is down) and used the offline version instead of the live program, but the error still appeared if I used the web anyways, so It does not matter. EDIT: After a previous edit, the images are no longer appearing in the post, sorry for the inconveniences.
tagged with: python
has comment: http://stackoverflow.com/comment/91356019
upvote count: 1

http://stackoverflow.com/q/52231034
answer count: 3
has answer: http://stackoverflow.com/a/52231148
tagged with: python
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
tagged with: python-3.x
has title: Selenium python, Click only under certain conditions
score: 0
tagged with: selenium
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52231148
type: Question
has answer: http://stackoverflow.com/a/52233729
possible better answer: http://stackoverflow.com/a/52231270
has answer: http://stackoverflow.com/a/52231270
has body: My code works, but not in all cases Basically the functionality is to click a load_more button until it no longer appears. As of right now, I simply have a loop which finds the loadmore button and clicks it twice, but there are cases that it will click on something else when the load more button disappears. I was planning on making a while loop, which would constantly find the click the load_more option until the loadmore disappeared then break the loop. Here is the code: (This simply finds and clicks it twice) load_more = browser.find_element_by_css_selector("#mainContent &gt; div.left-panel &gt; div &gt; div.result-list &gt; div &gt; div.content") WebDriverWait(browser, timeout).until(EC.visibility_of(load_more)) #Need bugfix, for i in range(2): browser.execute_script("return arguments[0].scrollIntoView(true);", load_more) ActionChains(browser).move_to_element(load_more).click().perform() I noticed when playing around with the load more button that. &lt;div class="progressbtnwrap" data-search-type="search" style="display: block;"&gt; When the load more button is present on the site, the element is set to "display: block;" But once the load more button disappears, &lt;div class="progressbtnwrap" data-search-type="search" style="display: none;"&gt; the element changes to none, notice "display: none;" Any suggestions how I can search for this? When looking through the selenium documentations I couldn't find any way of searching for this element and specifically checking if the style is triggered to none, https://selenium-python.readthedocs.io/locating-elements.html My goal here is to create something like this while(True): if browser.find_element_by_notsurewhat == "block": ActionChains(browser).move_to_element(load_more).click().perform() if browser.find_element_by_notsurewhat == "none": break browser.execute_script("return arguments[0].scrollIntoView(true);", load_more) I'm sure the logic must be much more complicated than that, or even if what I want to achieve is …

http://stackoverflow.com/q/52247813
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/52247856
has body: Im just learning Python, I' using Flask and I have a problem: I try to pass values from one page to my decorator, but this value comes from and this does not have name property. This is my html: ID Name Autor Year Genre Excluir Actualizar {% for album in listalbumes %} {{ album._id }} {{ album.name }} {{ album.autor }} {{ album.year }} {{ album.name_genre }} X Actualizar {% endfor %} I try to pass {{ album.autor }} with the id, but I can't. And this is my py code: @app.route('/artist/<string:autor>', methods=['GET', 'POST']) def artista(autor): autor = request.form.get("autor") alb = db.session.query(Album._id, Album.name, Album.autor, Album.year, Album.media, Album.continent).filter(Album.autor == autor).all() if request.method == "GET": for g in alb: print("Album {} skill points.".format(g)) # testing db values, It works if I set manually values if alb: return render_template("artist.html", alb=alb) Please, I hope anyone can help me best Regards
tagged with: flask
favorite count: 0
has title: Passing value to decorator
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/52356314
downvote count: 2
type: Question
tagged with: href
score: -2

http://stackoverflow.com/comment/91185956
has text: Your best bet is probably to figure out a way to install something like `openpyxl`. What's preventing you from installing this package?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52117485

http://stackoverflow.com/q/52186716
has comment: http://stackoverflow.com/comment/91324098
type: Question
tagged with: hashable
accepted answer: http://stackoverflow.com/a/52187536
tagged with: nltk
score: 0
has answer: http://stackoverflow.com/a/52187536
answer count: 1
has comment: http://stackoverflow.com/comment/91339351
has comment: http://stackoverflow.com/comment/91323192
has body: i'm following the original code for bleu scoring as below: from nltk.translate.bleu_score import sentence_bleu reference = [['this', 'is', 'a', 'test'], ['this', 'is' 'test']] candidate = ['this', 'is', 'a', 'test'] score = sentence_bleu(reference, candidate) print(score) and the code working fine. but i'm trying to change the reference and candidate by importing the csv file as the following code: import nltk import csv import itertools from nltk.translate.bleu_score import sentence_bleu print("Opening references file...") with open('bleu-ref.csv', newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') sentences = [] for row in spamreader: # print(', '.join(row)) sentences.append(' '.join(row)) sent = [[i] for i in sentences] reference = [] for i in range(len(sent)): sent[i] chink = [] for j in sent[i]: chink = chink + nltk.word_tokenize(j) reference.append(chink) print("Opening candidates file...") with open('bleu-can.csv', newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') sentences_can = [] for row in spamreader: # print(', '.join(row)) sentences_can.append(' '.join(row)) sent_can = [[i] for i in sentences_can] candidate = [] for i in range(len(sent_can)): sent_can[i] chink_can = [] for j in sent_can[i]: chink_can = chink_can + nltk.word_tokenize(j) candidate.append(chink_can) score = sentence_bleu(reference, candidate) but it encountered an error: Traceback (most recent call last): File "nltk-bleu-score.py", line 56, in &lt;module&gt; score = sentence_bleu(reference, candidate) File "C:\Users\Fachri\Anaconda3\lib\site-packages\nltk\translate\bleu_score.py", line 89, in sentence_bleu emulate_multibleu) File "C:\Users\Fachri\Anaconda3\lib\site-packages\nltk\translate\bleu_score.py", line 162, in corpus_bleu p_i = modified_precision(references, hypothesis, i) File "C:\Users\Fachri\Anaconda3\lib\site-packages\nltk\translate\bleu_score.py", line 292, in modified_precision counts = Counter(ngrams(hyp…
tagged with: tuples
has comment: http://stackoverflow.com/comment/91324244
has title: NLTK: TypeError: unhashable type: 'list'
tagged with: python
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/q/52136388
has title: xarray select\interpolate custom 1D slice out auf multidimensional data (aka zip vs itertools.product)
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52136658
type: Question
accepted answer: http://stackoverflow.com/a/52136658
score: 4
upvote count: 4
tagged with: python-xarray
has body: I have a (large) multidimensional xarray Dataarray or Dataset and would like to select or interpolate data along a 1D path without slow for loops or list comprehension (e.g. there is 2D data defined on Latitudes and Longitudes, and i would like to get the data along a path given by latitudes and longitudes): import xarray as xr import numpy as np lats, lons = np.arange(0, 6), np.arange(10, 17) path_lats, path_lons = np.arange(0.3, 5, 0.5), np.arange(10.6, 15.6, 0.5) da = xr.DataArray(np.random.rand(len(lats), len(lons)), coords=[lats, lons], dims=['latitude', 'longitude']) The following returns a 2D DataArray containing all combinations of path_lats and path_lons, similar to a for loop using itertools.product(path_lats, path_lons): da_path = da.interp(latitude=path_lats, longitude=path_lons) For larger Dataarrays\Datasets with more than two dimension this will consume a lot of memory because it contains a lot of data that is not needed for this task. What i would like to have is a fast version of a for loop \ list comprehension using zip(path_lats, path_lons), e.g. something like (not valid syntax here) da_pathZIP = da.interp((latitude, longitude) = (path_lats, path_lons)) which would return a 1D Dataarray (coordinate: index of the path) and maybe the latitudes and longitudes additional to the data. The resulting Datarray should contain the following data: [float(da.interp(latitude=p_lat, longitude=p_lon)) for p_lat, p_lon in zip(path_lats, path_lons)] Is this possible in xarray without using loops?
answer count: 1
downvote count: 0
favorite count: 0
tagged with: multidimensional-array

http://stackoverflow.com/comment/91325573
score: 0
comment on: http://stackoverflow.com/q/52153881
type: QuestionComment
type: Comment
has text: i think the ex: output data was good to understand what i'm asking.BTW i got the answer. thank you!

http://stackoverflow.com/q/52150653
tagged with: python
possible better answer: http://stackoverflow.com/a/52150914
answer count: 4
favorite count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/91251461
has body: Say I have these lines of code index = 1 test = lambda t : t[index]+1 index = 0 print(test([5, 0])) The result is 6, I would expect the result to be 1. How can I make the index inside the lambda expression static without writing t[1]+1, i.e. using a variable?
tagged with: lambda
has answer: http://stackoverflow.com/a/52150758
tagged with: indexing
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/52150755
has answer: http://stackoverflow.com/a/52150900
accepted answer: http://stackoverflow.com/a/52150900
has answer: http://stackoverflow.com/a/52150914
type: Question
upvote count: 2
has title: How to make an index static for a python lambda expression

http://stackoverflow.com/comment/91451792
comment on: http://stackoverflow.com/a/52251775
type: AnswerComment
has text: `[2,4,6]` I hope! this is a list. But, `[2 4 6]` has no `,` between values. Is this still be a list?
score: 0
type: Comment

http://stackoverflow.com/comment/91206927
score: 0
type: Comment
has text: Thank you very much! That helps a lot. The .apply() function also confused me for such a while. With your example, I get to understand its usage. Really appreciated it!
comment on: http://stackoverflow.com/a/52127828
type: AnswerComment

http://stackoverflow.com/a/52267219
type: Answer
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/91482237
has body: Using loc sr.value_counts().loc[lambda x : x==3].index Out[162]: Int64Index([8, 6, 5], dtype='int64')
has comment: http://stackoverflow.com/comment/91482256
downvote count: 0
answers question: http://stackoverflow.com/q/52267157

http://stackoverflow.com/comment/91246731
type: Comment
has text: "One of the way to change the value on a string is to save it in an array." => this is not going to "change the value on a string", whatever "save it in an array" might be supposed to mean (I assume you actually meant "build a list from it").
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52148041

http://stackoverflow.com/q/52136212
tagged with: python
accepted answer: http://stackoverflow.com/a/52136399
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91222222
has answer: http://stackoverflow.com/a/52136268
tagged with: matplotlib
has answer: http://stackoverflow.com/a/52136399
possible better answer: http://stackoverflow.com/a/52136268
answer count: 2
has title: Use custom tick marks on axes coordinates
downvote count: 0
has body: I'm plotting some function in matplotlib. But I want to change the usual x and y coordinates. For example I plot y=sin(x) in [-pi, pi]. But the x-axis shows 1, 2, 3,... in this way whereas I want x: -pi, 0, pi,... Is it possible? My Code import matplotlib as mpl mpl.rc('text', usetex = True) mpl.rc('font', family = 'serif') import matplotlib.pyplot as plt import numpy as np plt.gca().set_aspect('equal', adjustable='box') plt.style.use(['ggplot','dark_background']) x = np.arange(-np.pi,np.pi,0.001) y = np.sin(x) plt.xlabel('$x$') plt.ylabel('$y$') plt.plot(x,y, label='$y=\sin x$') plt.legend() plt.show() Output How to change the marks on the axes coordinates? Thank you.
favorite count: 0

addition
tags question: http://stackoverflow.com/q/52195927
type: Tag
tag name: addition

http://stackoverflow.com/comment/91282690
has text: Your solution seems to be OK. What is the question? Where is the problem?
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52166465

http://stackoverflow.com/comment/91374469
type: QuestionComment
comment on: http://stackoverflow.com/q/52208987
score: 0
has text: @ImportanceOfBeingErnest here is the data that I am testing, spectrum : https://drive.google.com/file/d/1qNm0VkUOWSM__1RShWOtUN97wGt0SSAy/view?usp=sharing and wavelength : https://drive.google.com/file/d/1E7Pmini5X-9mWfOMGcTzbj4vxl6XmPNk/view?usp=sharing
type: Comment

http://stackoverflow.com/q/52136449
has title: How to real-time character recognition with python and camera?
tagged with: python-3.x
type: UnansweredQuestion
has body: I'm making kivy app to recognize character with camera on real-time. However, there is no document except recognizing face. I think there is a way because picamera is almost doing similar thing (creating opencv file from camera). Would someone tell me to achieve this? * PS * I'm on the way to capture image when camera sees the number, but I don't know how to make that trigger. Now this is the code, and I want to know when to break true sentence. cap = cv2.VideoCapture(0) while(True): ret, image = cap.read() cv2.imshow('image', image) results = tes.image_to_string(image, boxes=True) if results: break cap.release() cv2.destroyAllWindows() print(results) but this one is too slow
tagged with: opencv
linked to: http://stackoverflow.com/q/32943227
linked to: http://stackoverflow.com/q/24574637
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/52136519
score: 0
tagged with: python
tagged with: kivy

http://stackoverflow.com/q/52179419
has answer: http://stackoverflow.com/a/52183247
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/91309294
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91310608
downvote count: 0
score: 1
has body: This is my HTML Table. MyGrp1 Item0.1 Header Item0.1 Value MyGrp Item1.1 Header Item1.1 Value Item1.2 Header Item1.2 Value Item1.3 Header Item1.2 Value I want the table to parsed as below MyGrp1<new line> <tab char>Item0.1 Header<tab char>Item0.1 Value<new line> MyGrp2<new line> <tab char>Item1.1 Header<tab char>Item1.1 Value<new line> <tab char>Item1.2 Header<tab char>Item1.2 Value<new line> <tab char>Item1.3 Header<tab char>Item1.3 Value<new line> I can get all the nodes of 'tr' or 'th'. But I don't know how to iterate the table node by node. How can I scrape the Html table and get my above result?
type: Question
tagged with: html-table
has title: Python Web Scraping Html Table using beautiful soup
has answer: http://stackoverflow.com/a/52182886
has answer: http://stackoverflow.com/a/52179676
answer count: 3
upvote count: 1

http://stackoverflow.com/comment/91285700
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52167807
has text: Are you look for how to use apply method with series?
score: 0

http://stackoverflow.com/q/52140922
type: AnsweredQuestion
type: Question
answer count: 2
score: 0
tagged with: pandas
has body: I am writing a program that needs to read a csv/text file with football scores that looks like this: Lions 3, Snakes 3 Tarantulas 1, FC Awesome 0 Lions 1, FC Awesome 1 Tarantulas 3, Snakes 1 Lions 4, Grouches 0 If the teams draw, each team gets 1 point, if a team wins they get 3 points. The output should ideally look like this: 1. Tarantulas, 6 pts 2. Lions, 5 pts 3. FC Awesome, 1 pt 3. Snakes, 1 pt 4. Grouches, 0 pts This is the code I have so far: import pandas as pd data = pd.read_csv("sample_input.csv", header=None, names=['left_team', 'right_team']) data_dict = data.to_dict(orient='list') def splitter(row): left_team, right_team = row.split(',') return { 'left_team': left_team[:-2].strip(), 'left_score': int(left_team[-2:].strip()), 'right_team': right_team[:-2].strip(), 'right_score': int(right_team[-2:].strip()) } My question is how do I get the data fram the dataframe to compare the values? I have also tried coding the solution without pandas but I am struggling with that. Any help will be greatly appreciated! Thanks! This is the other solution that I have tried: from collections import defaultdict import csv reader = csv.DictReader(open('sample_input.csv', 'r')) dict_list = [] for line in reader: dict_list.append(line) data_list = [splitter(row) for row in reader] def splitter(row): left_team, right_team = row.split(',') return { 'left_team': left_team[:-2].strip(), 'left_score': int(left_team[-2:].strip()), 'right_team': right_team[:-2].strip(), 'right_score': int(right_team[-2:].strip()) } data_dicts = [splitter(row) for row in reader] team_scores = defaultdict(int) for game in data_dicts: if game['left_score'] == game['right_score']: team_scores[game['left']] += 1 team_scores[game['right']] += 1 elif game ['left_score'] &gt; game['right_score']: team_scores[game['left']] += 3 else: team_scores[game['right']] += 3 teams_sorted = sorted(team_scores.items(), key=lambda team: team[1], reverse=True) for line in teams_sorted: print(line)
possible better answer: http://stackoverflow.com/a/52141167
tagged with: python
has answer: http://stackoverflow.com/a/52141167
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52141144
has title: How to compare integer values in pandas dataframe
accepted answer: http://stackoverflow.com/a/52141144

http://stackoverflow.com/comment/91449402
has text: Your dimensions don't match. As in the error: `(m,m),(m,n)->(m,n)`. Your `a` is 12x12 and `b` is 60x60. At a guess your `a` needs to be 12x60 or `b` needs to be 12x60
comment on: http://stackoverflow.com/q/52250762
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52227001
type: UnansweredQuestion
tagged with: elasticsearch-py
has answer: http://stackoverflow.com/a/52236749
has title: How to store objects/dict in elasticsearch using python
type: Question
answer count: 1
has body: I am trying to save object inside elastic using elasticsearch library in python. Below is my class which I am using from elasticsearch_dsl import DocType, Date, InnerDoc, Text, Object class Child(Object): child1 = Text() child2 = Text() class Parent(DocType): parent1 = Object() parent2 = Date() parent3 = Date() parent4 = Text() parent5 = Child() class Meta: index = 'my_index' And below is my elastic mapping { "mappings": { "doc": { "properties": { "parent5": { "type": "object", "child1": { "tracking_number": { "type": "text" }, "child2": { "type": "text" }, } }, "parent1": { "type": "object" }, "parent2": { "type": "text" }, "parent3": { "type": "date" }, "parent4": { "type": "date" } } } } } If I change the type to 'Object' and retrieve the document in python code it gives me below error. TypeError: Object of type 'InnerDoc' is not JSON serializable And if I change the type to 'InnerDoc' I am able to retrieve the document but then I am not able to save it in elastic. I am assuming my mapping are wrong but not really sure. Any kind of help/insights will be appreciated. Thanks in advance
score: 0
tagged with: elasticsearch
tagged with: python

http://stackoverflow.com/a/52258077
has comment: http://stackoverflow.com/comment/91486251
answers question: http://stackoverflow.com/q/52258002
score: 1
upvote count: 1
has body: Use DataFrameGroupBy.agg with DatetimeIndex.month and DatetimeIndex.year, for ordering add sort_index and last use reset_index for columns from MultiIndex: import pandas as pd import numpy as np np.random.seed(2018) #changed 300 to 600 df = pd.DataFrame(np.random.randint(0,10,size=(600, 2)), columns=list('AB')) df['date'] = pd.DataFrame(pd.date_range(start='1/1/2018', end='8/23/2019')) df = df.set_index('date') df1 = (df.groupby([df.index.month.rename('month'), df.index.year.rename('year')]) .agg({'A':'sum', 'B':'mean'}) .sort_index(level=['year', 'month']) .reset_index()) print (df1) month year A B 0 1 2018 147 4.838710 1 2 2018 120 3.678571 2 3 2018 114 4.387097 3 4 2018 143 3.800000 4 5 2018 124 3.870968 5 6 2018 129 4.700000 6 7 2018 143 3.935484 7 8 2018 118 5.483871 8 9 2018 150 5.500000 9 10 2018 139 4.225806 10 11 2018 136 4.933333 11 12 2018 141 4.548387 12 1 2019 137 4.709677 13 2 2019 120 4.964286 14 3 2019 167 4.935484 15 4 2019 121 4.200000 16 5 2019 133 4.129032 17 6 2019 140 5.066667 18 7 2019 189 4.677419 19 8 2019 100 3.695652
downvote count: 0
has comment: http://stackoverflow.com/comment/91463687
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52258002
type: Answer

http://stackoverflow.com/comment/91460502
type: Comment
has text: If you want to overwrite the file than use 'w' instead of 'a+': f = csv.writer(open("instance_count.csv", "w"), lineterminator="\n")
comment on: http://stackoverflow.com/a/52256072
type: AnswerComment
score: 0

http://stackoverflow.com/q/52172153
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91325647
has body: I am using SerpentAI, and I have to run a python script and it gives me this error. PermissionError: [Errno 13] Permission denied: '/Applications/OpenEmu.app' Here the Python code from serpent.game import Game from .api.api import OpenEmuAPI from serpent.utilities import Singleton class SerpentOpenEmuGame(Game, metaclass=Singleton): def __init__(self, **kwargs): kwargs["platform"] = "executable" kwargs["window_name"] = "Open Emu" kwargs["executable_path"] = "/Applications/OpenEmu.app" super().__init__(**kwargs) self.api_class = OpenEmuAPI self.api_instance = None @property def screen_regions(self): regions = { "SAMPLE_REGION": (0, 0, 0, 0) } return regions @property def ocr_presets(self): presets = { "SAMPLE_PRESET": { "extract": { "gradient_size": 1, "closing_size": 1 }, "perform": { "scale": 10, "order": 1, "horizontal_closing": 1, "vertical_closing": 1 } } } return presets I am using MacOS Is there a solution to this or is it just SerpentAI that is messing up?
has comment: http://stackoverflow.com/comment/91333314
type: Question
has comment: http://stackoverflow.com/comment/91343806
score: 0
has title: Getting Errno 13 Permission Denied error when running a python code
tagged with: macos
tagged with: python
has comment: http://stackoverflow.com/comment/91295121

http://stackoverflow.com/q/52170209
has comment: http://stackoverflow.com/comment/91313962
favorite count: 0
has comment: http://stackoverflow.com/comment/91291361
has comment: http://stackoverflow.com/comment/91292340
tagged with: python
upvote count: 4
has body: I want to convert to an executable this python 2.7 project that has a module structure: (.venv) ip-192-168-22-127:indictrans loretoparisi$ tree -L 1 . ├── __init__.py ├── __init__.pyc ├── __init__.spec ├── _decode ├── _utils ├── base.py ├── build ├── mappings ├── models ├── script_transliterate.py ├── tests ├── transliterator.py └── trunk I'm using pyinstaller for this at first stage I'm just doing: pyinstall --onefile __init__.py and I get a executable built: 192 INFO: PyInstaller: 3.3.1 192 INFO: Python: 2.7.10 201 INFO: Platform: Darwin-17.7.0-x86_64-i386-64bit 202 INFO: wrote /Users/loretoparisi/Documents/Projects/AI/indic-trans/indictrans/__init__.spec 208 INFO: UPX is not available. 209 INFO: Extending PYTHONPATH with paths ['/Users/loretoparisi/Documents/Projects/AI/indic-trans', '/Users/loretoparisi/Documents/Projects/AI/indic-trans/indictrans'] 210 INFO: checking Analysis 218 INFO: checking PYZ 223 INFO: checking PKG 224 INFO: Bootloader /Users/loretoparisi/Documents/Projects/AI/indic-trans/.venv/lib/python2.7/site-packages/PyInstaller/bootloader/Darwin-64bit/run 224 INFO: checking EXE 225 INFO: Rebuilding out00-EXE.toc because __init__ missing 225 INFO: Building EXE from out00-EXE.toc 225 INFO: Appending archive to EXE /Users/loretoparisi/Documents/Projects/AI/indic-trans/indictrans/dist/__init__ 230 INFO: Fixing EXE for code signing /Users/loretoparisi/Documents/Projects/AI/indic-trans/indictrans/dist/__init__ 234 INFO: Building EXE from out00-EXE.toc completed successfully. But when I run it I get an import error Traceback (most recent call last): File "indictrans/__init__.py", line 9, in &lt;module&gt; ValueError: Attempted relative import in non-package [30629] Failed to execute script __init__ This library is built using Cython via cythonize setup, so another option would be to build a executable embedded module using the --embed Cython option. My setup.py is the following: #!/usr/bin/env python import os from setuptools import setup from setuptools.e…
downvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/22507592
has title: Create Executable from a Python module with Pyinstaller or Cython
tagged with: cython
type: Question
has comment: http://stackoverflow.com/comment/91290991
score: 4
tagged with: cythonize
answer count: 1
has answer: http://stackoverflow.com/a/58904179

http://stackoverflow.com/comment/91411404
has text: `setdefault` doesn't return None - in this case it returns a list, and the None comes from the subsequent `list.append` call.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52215041
type: Comment

http://stackoverflow.com/comment/91289101
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52169297
has text: `bazaar`, `mercurial`, `git`? or do you mean something like `sqlalchemy` or `alembic`?

http://stackoverflow.com/comment/91452244
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52245262
type: Comment
has text: yes you are correct, I have copied the xpath straight from the inspect tool. For some other elements such as the name of the product this has worked ... but not for the perfume notes. I have chosen your answer as the solution to this question however my reputation is low thus I cannot upvote.

http://stackoverflow.com/q/52126620
score: 1
tagged with: formatting
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/91203994
has title: Python 3, print list with scientific notations
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/91203969
answer count: 0
type: UnansweredQuestion
has body: I just got started with python, and need help on a school assignment. The assignment is: Below is a list of the SI prefixes from 1e18 to 1e-18 (with step size 3). Print a table with the prefixes and the corresponding power. prefixes = ['exa','peta','tera','giga','mega','kilo',' ',\ 'milli','micro','nano','pico','femto','atto'] I know how to print two tables next to each other using the zip-function, but I'm having trouble printing out a table with scientific notations. I've been trying to create a table like this: table = range(1e-18, 1e18, 1e-3) And then I get: TypeError: 'float' object cannot be interpreted as integer. I've tried formatting it, but I must be doing something wrong. I've also tried writing the list manually, table = [1e-18, 1e-15, 1e-12, 1e-9, 1e-6, 1e-3, 0, 1e3, 1e6, 1e9, 1e12, 1e15], but when I print it it becomes decimals. I've tried formatting with: ["{:.e}".format(i[table]) for i in table] This only gives me the TypeError: 'float' object is not subscriptable. Any help would be appreciated! I'm new to this, so please try putting it as simple as possible. Thanks!
upvote count: 1
has comment: http://stackoverflow.com/comment/91203950
tagged with: list

compilation
tags question: http://stackoverflow.com/q/52129116
tags question: http://stackoverflow.com/q/52217113
tags question: http://stackoverflow.com/q/52217688
tag name: compilation
tags question: http://stackoverflow.com/q/52252512
type: Tag

http://stackoverflow.com/comment/91321511
has text: Is there any way where we can see which URL got which response code?
comment on: http://stackoverflow.com/a/52155467
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52153270
accepted answer: http://stackoverflow.com/a/52153297
type: Question
has body: I have an object with different attributes and a list that contains those objects. Before adding an object to the list, I'd like to check if an attribute of this new object is present in the list. This attribute is unique, so this is done to make sure that every object in the list is unique. I would do something like this: for post in stream: if post.post_id not in post_list: post_list.append(post) else: # Find old post in the list and replace it But obviously line 2 doesn't work as I'm comparing the post_id to the object list.
has comment: http://stackoverflow.com/comment/91256939
has comment: http://stackoverflow.com/comment/91257785
has comment: http://stackoverflow.com/comment/91256791
score: 0
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52153297
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52153335
has answer: http://stackoverflow.com/a/52153335
has title: Check if Object attribute is present in list of Object

http://stackoverflow.com/a/52263514
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52263492
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52263492
upvote count: 2
type: Answer
score: 2
has body: You can simply fix it by prepending url with /: our story But better to use Django's named url feature: our story
has comment: http://stackoverflow.com/comment/91475174

http://stackoverflow.com/comment/91295734
comment on: http://stackoverflow.com/a/52170919
score: 0
type: AnswerComment
has text: In my dataset I just ran into a instance where say "id" 25 had a "code" 3 and the "sec" was summed to "code" 1. So sec for id 25 code 1 ended up being higher then it should have been. How would I add the code to set a restriction to say code != 3
type: Comment

http://stackoverflow.com/a/52270603
has body: Use the pandas' dropna() function to remove nan and then plot it with a scatter() plot of matplotlib. import pandas as pd import matplotlib.pyplot as plt enter code here df = &lt;your dataset&gt; plot_df = df.dropna() plt.scatter(plot_df['Number of kids'], plot_df['GDP per capita']) If your dataset is very large consider to use the sample function to randomly sample data: df = df.sample(1000)
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52270503
answers question: http://stackoverflow.com/q/52270503
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52225847
has comment: http://stackoverflow.com/comment/91401612
upvote count: 1
downvote count: 1
has body: I think what you want is the result of each number multiplied by the other ints in the list? Thus for list[3,4,7] you would want 9,16,49,12,21,28. You can try this. l = [3,4,7] s = set() for count, num in enumerate(l): for each in l: s.add(each * l[count]) s {9, 12, 16, 49, 21, 28} if you dont want the squares (9,49,16) add if list[count] == each: countinue underneath the second for loop
answers question: http://stackoverflow.com/q/52225520
has comment: http://stackoverflow.com/comment/91401820
score: 0
type: Answer

http://stackoverflow.com/comment/91218368
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52131690
has text: No, I was just using it because of consistency

http://stackoverflow.com/q/52126767
accepted answer: http://stackoverflow.com/a/52128842
favorite count: 0
tagged with: seaborn
tagged with: python
has body: I have the following issue. If I want to plot a line chart without using any style with a colormap this works fine. However, as soon as I apply a style the colormap is not picked up. Let's make an example: import pandas as pd import seaborn as sns from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt plt.style.use('ggplot') df = pd.DataFrame(data=[[100, 100],[105, 110],[107, 118],[112, 110]]) my_cmap = ListedColormap(sns.color_palette("GnBu_d", len(df.columns)).as_hex()) df.plot(colormap=my_cmap, alpha=0.8, rot=0, xticks=df.index, linewidth=2) plt.show() This plot generates a correct color scheme: However when using the style parameter df.plot(colormap=my_cmap, alpha=0.8, rot=0, xticks=df.index, linewidth=2, style=['o-', 's:']) plt.show() it overrides somehow that: How can I use the style with the desired colormap?
type: AnsweredQuestion
score: 1
tagged with: matplotlib
upvote count: 1
has answer: http://stackoverflow.com/a/52128842
type: Question
has comment: http://stackoverflow.com/comment/91205427
has comment: http://stackoverflow.com/comment/91205459
has title: Why is colomap not applied when I use style in pandas plot?
has comment: http://stackoverflow.com/comment/91205602
tagged with: pandas
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/91419702
type: Comment
has text: Yes. I need to utilize a built in function, that calls `plot` on the data frame object.
comment on: http://stackoverflow.com/a/52235472
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139200189
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52162807
type: Comment
has text: In the thread mentioned by @mc2 the comment posted on May 6th 2024 worked for me, using the observe method.

http://stackoverflow.com/q/52136306
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
has answer: http://stackoverflow.com/a/52136376
accepted answer: http://stackoverflow.com/a/52136376
has title: Grouping and indenting json created from pandas dataframe
has answer: http://stackoverflow.com/a/52136382
answer count: 3
tagged with: pandas
upvote count: 1
possible better answer: http://stackoverflow.com/a/52136366
favorite count: 0
has answer: http://stackoverflow.com/a/52136366
has body: I currently have a dataframe like the following: ln 7,26 7,27 7,28 name 26443 G G G Product 1 27953 G G G Product 2 This is from a csv which is generated daily and the numbers (7,26; 7,27...) are dates, which means they are different every day. I'd like to create a json which looks like this: [{ "index": 0, "ln": "26443", "availability": { "7,26": "G", "7,27": "G", "7,28": "G", }, "name": "Product 1" }, { "index": 1, "ln": "27953", "availability": { "7,26": "G", "7,27": "G", "7,28": "G", }, "name": "Product 2" }] The current code I'm using to create a json is like the following, but it just dumps it all as is: with open('output.json', 'w', encoding='utf-8') as file: df2.reset_index().to_json(file, orient='records', force_ascii=False) Is it possible to make this happen? If so, how? Thanks in advance for any advice!
tagged with: python

http://stackoverflow.com/a/52113599
score: 0
answers question: http://stackoverflow.com/q/52113222
has body: You can create a file with the built-in open function from Python: with open('output.txt', 'w') as outfile: outfile.write("pline\n") l = int(input('l=')) r = int(input('r=')) for x in range(0, l + 1, 2): y = round(((x ** 3) / (6 * l * r)), 4) for x in range(0, l + 1, 2): outfile.write("{},{}\n".format(x, round(((x ** 3) / (6 * l * r)), 4))) Output pline 0,0.0 2,0.0002 4,0.0013 6,0.0044 8,0.0104 10,0.0204 12,0.0352 14,0.0558 16,0.0834 18,0.1187 20,0.1628 22,0.2167 24,0.2813 26,0.3577 28,0.4467 30,0.5495 32,0.6668 34,0.7998 36,0.9495 38,1.1166 40,1.3024 42,1.5077 The function outfile.write writes the text to the file, in the example above outfile. To write a line you must append the newline character \n at the end of each string you write.
type: Answer
has comment: http://stackoverflow.com/comment/91178056

http://stackoverflow.com/comment/91226032
has text: @Bazingaa, See update, you may see a small benefit for larger arrays.
comment on: http://stackoverflow.com/a/52137973
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/65400913
type: Answer
answers question: http://stackoverflow.com/q/52129909
score: 0
has body: For the last-axis gathering, we can use the 2D-reshape trick for general ND cases, and then employ @LiShaoyuan 2D code above # last-axis gathering only - use 2D-reshape-trick for Torch's style nD gathering def torch_gather(param, id_tensor): # 2d-gather torch equivalent from @LiShaoyuan above def gather2d(target, id_tensor): idx = tf.stack([tf.range(tf.shape(id_tensor)[0]),id_tensor[:,0]],axis=-1) result = tf.gather_nd(target,idx) return tf.expand_dims(result,axis=-1) target = tf.reshape(param, (-1, param.shape[-1])) # reshape 2D target_shape = id_tensor.shape id_tensor = tf.reshape(id_tensor, (-1, 1)) # also 2D-index result = gather2d(target, id_tensor) return tf.reshape(result, target_shape)

http://stackoverflow.com/q/52196134
has answer: http://stackoverflow.com/a/52196192
has body: I know this must be easy but I can't figure it out or find an existing answer on this... Say I have this dataframe... &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; dates = pd.date_range('20130101', periods=6) &gt;&gt;&gt; df = pd.DataFrame(np.nan, index=dates, columns=list('ABCD')) &gt;&gt;&gt; df A B C D 2013-01-01 NaN NaN NaN NaN 2013-01-02 NaN NaN NaN NaN 2013-01-03 NaN NaN NaN NaN 2013-01-04 NaN NaN NaN NaN 2013-01-05 NaN NaN NaN NaN 2013-01-06 NaN NaN NaN NaN It's easy to set the values of one series... &gt;&gt;&gt; df.loc[:, 'A'] = pd.Series([1,2,3,4,5,6], index=dates) &gt;&gt;&gt; df A B C D 2013-01-01 1 NaN NaN NaN 2013-01-02 2 NaN NaN NaN 2013-01-03 3 NaN NaN NaN 2013-01-04 4 NaN NaN NaN 2013-01-05 5 NaN NaN NaN 2013-01-06 6 NaN NaN NaN But how do I set the values of all columns using broadcasting? &gt;&gt;&gt; default_values = pd.Series([1,2,3,4,5,6], index=dates) &gt;&gt;&gt; df.loc[:, :] = default_values Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/billtubbs/anaconda/envs/py36/lib/python3.6/site-packages/pandas/core/indexing.py", line 189, in __setitem__ self._setitem_with_indexer(indexer, value) File "/Users/billtubbs/anaconda/envs/py36/lib/python3.6/site-packages/pandas/core/indexing.py", line 651, in _setitem_with_indexer value=value) File "/Users/billtubbs/anaconda/envs/py36/lib/python3.6/site-packages/pandas/core/internals.py", line 3693, in setitem return self.apply('setitem', **kwargs) File "/Users/billtubbs/anaconda/envs/py36/lib/python3.6/site-packages/pandas/core/internals.py", line 3581, in apply applied = getattr(b, f)(**kwargs) File "/Users/billtubbs/anaconda/envs/py36/lib/python3.6/site-packages/pandas/core/internals.py", line 940, in setitem values[indexer] = value ValueError: could not broadcast input array from shape (6) into shape (6,4) Other than these ways: &gt;&gt;&gt; for s in df: ... df.loc[:, s] = default_values ... Or: &gt;&gt;&gt; df.loc[:, :] = n…
upvote count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52196503
has answer: http://stackoverflow.com/a/52196236
tagged with: broadcasting
favorite count: 0
tagged with: assign
tagged with: python
answer count: 4
has title: How to broadcast and assign a series of values across all columns in a Pandas dataframe?
type: AnsweredQuestion
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52196503
has answer: http://stackoverflow.com/a/57791322
tagged with: dataframe
type: Question
accepted answer: http://stackoverflow.com/a/52196236

javascript
tags question: http://stackoverflow.com/q/52119710
tags question: http://stackoverflow.com/q/52179551
tags question: http://stackoverflow.com/q/52211968
tags question: http://stackoverflow.com/q/52206760
tags question: http://stackoverflow.com/q/52138510
tags question: http://stackoverflow.com/q/52261050
tags question: http://stackoverflow.com/q/52216318
tags question: http://stackoverflow.com/q/52128535
tags question: http://stackoverflow.com/q/52218050
tags question: http://stackoverflow.com/q/52225155
tags question: http://stackoverflow.com/q/52181366
tags question: http://stackoverflow.com/q/52171778
tags question: http://stackoverflow.com/q/52231715
tags question: http://stackoverflow.com/q/52264156
tags question: http://stackoverflow.com/q/52189935
tag name: javascript
tags question: http://stackoverflow.com/q/52166468
tags question: http://stackoverflow.com/q/52156945
tags question: http://stackoverflow.com/q/52179181
tags question: http://stackoverflow.com/q/52117156
tags question: http://stackoverflow.com/q/52205651
tags question: http://stackoverflow.com/q/52241986
tags question: http://stackoverflow.com/q/52163199
tags question: http://stackoverflow.com/q/52229876
tags question: http://stackoverflow.com/q/52206679
tags question: http://stackoverflow.com/q/52202137
tags question: http://stackoverflow.com/q/52132876
type: Tag
tags question: http://stackoverflow.com/q/52179629
tags question: http://stackoverflow.com/q/52121073
tags question: http://stackoverflow.com/q/52129856
tags question: http://stackoverflow.com/q/52267064
tags question: http://stackoverflow.com/q/52202630
tags question: http://stackoverflow.com/q/52248600
tags question: http://stackoverflow.com/q/52166973
tags question: http://stackoverflow.com/q/52261414
tags question: http://stackoverflow.com/q/52260556
tags question: http://stackoverflow.com/q/52269272
tags question: http://stackoverflow.com/q/52124836
tags question: http://stackoverflow.com/q/52117533
tags question: http://stackoverflow.com/q/52144245
tags question: http://stackoverflow.com/q/52113219
tags question: http://stackoverflow.com/q/52121730
tags question: http://stackoverflow.com/q/52222334
tags question: http://stackoverflow.com/q/52208875
tags question: http://stackoverflow.com/q/52174867
tags question: http://stackoverflow.com/q/52135161
tags question: http://stackoverflow.com/q/52191396
tags question: http://stackoverflow.com/q/52187248
tags question: http://stackoverflow.com/q/52242843

http://stackoverflow.com/q/52231294
accepted answer: http://stackoverflow.com/a/52231992
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/11470572
score: 4
has answer: http://stackoverflow.com/a/75861673
has body: The django template folder requires creating a subfolder with the name of the app which then contains the template files. Why is this necessary, when python manage.py collectstatic can infer this information while traversing all directories? It seems very redundant.
answer count: 2
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/15411164
upvote count: 5
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/75861673
has comment: http://stackoverflow.com/comment/91412213
has title: What is the reason for the nested template directory structure in Django?
has answer: http://stackoverflow.com/a/52231992

apache
tag name: apache
tags question: http://stackoverflow.com/q/52168027
tags question: http://stackoverflow.com/q/52256121
tags question: http://stackoverflow.com/q/52133582
tags question: http://stackoverflow.com/q/52136724
tags question: http://stackoverflow.com/q/52127601
tags question: http://stackoverflow.com/q/52256428
type: Tag
tags question: http://stackoverflow.com/q/52176392
tags question: http://stackoverflow.com/q/52225841

c++
tags question: http://stackoverflow.com/q/52133035
tags question: http://stackoverflow.com/q/52150395
tags question: http://stackoverflow.com/q/52177390
tags question: http://stackoverflow.com/q/52143225
tags question: http://stackoverflow.com/q/52247001
tags question: http://stackoverflow.com/q/52255191
tags question: http://stackoverflow.com/q/52197918
tags question: http://stackoverflow.com/q/52162125
type: Tag
tags question: http://stackoverflow.com/q/52199057
tags question: http://stackoverflow.com/q/52249803
tags question: http://stackoverflow.com/q/52191948
tags question: http://stackoverflow.com/q/52222864
tags question: http://stackoverflow.com/q/52186821
tags question: http://stackoverflow.com/q/52169356
tags question: http://stackoverflow.com/q/52147785
tags question: http://stackoverflow.com/q/52139846
tags question: http://stackoverflow.com/q/52136385
tags question: http://stackoverflow.com/q/52194859
tags question: http://stackoverflow.com/q/52142982
tags question: http://stackoverflow.com/q/52262669
tag name: c++

http://stackoverflow.com/comment/91258643
has text: Well, that's one solution. But a better one is to properly separate the POST and GET cases, following the pattern shown in the docs rather than this `request.POST or None` stuff.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52152886
type: Comment

http://stackoverflow.com/q/52115749
tagged with: django-models
has comment: http://stackoverflow.com/comment/91183014
has answer: http://stackoverflow.com/a/52117520
type: Question
answer count: 1
tagged with: django-validation
has comment: http://stackoverflow.com/comment/91182334
has comment: http://stackoverflow.com/comment/91240679
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91183269
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
has body: I have the following model: class MyModel(models.Model): RED = 'red' BLUE = 'blue' EMPTY_COLOR = None COLORS = ( (EMPTY_COLOR, '---'), (RED, 'red'), (BLUE, 'blue'), ) color = models.CharField(max_length=255, null=True, blank=True, choices=COLORS, default=EMPTY_COLOR) I want the model to validate as valid (using full_clean() on an instance) if the color is set to None (or blue/red, of course) but not when it is set to an empty string. However, the empty string is happily allowed to be defined on the model and is saved in the database even though the choices are defined, in my view, to only ever be NULL, "red", or "blue". Are my assumptions incorrect? How do I go about disallowing an empty string from being a valid value while keeping model validation working when the color is None?
has comment: http://stackoverflow.com/comment/91183104
has title: Disallow empty string as a valid value on a model with choices that include NULL
score: 1

http://stackoverflow.com/comment/91213774
type: QuestionComment
comment on: http://stackoverflow.com/q/52131528
type: Comment
score: 0
has text: @zvone this is not the full code,I am trying to multilpy two polynomial def multpoly(d1,d2): d3=[] d1=dict(d1) d2=dict(d2) for key,value in list(d1.items()): for key2,value2 in list(d2.items()): r1=key*key2 v1=value+value2 print(r1,v1)

http://stackoverflow.com/a/52182959
type: AcceptedAnswer
has body: I don't think you need lookbehind pattern to do this. All the work is to substitute y=2 or x=\d y=2 to x=1 y=2, right? line="hello x=7 y=2" re.sub(r'(x=\d\s)?y=2', 'x=1 y=2', line)
has comment: http://stackoverflow.com/comment/91327793
type: Answer
accepted answer of: http://stackoverflow.com/q/52182470
has comment: http://stackoverflow.com/comment/91320342
answers question: http://stackoverflow.com/q/52182470
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/52183552
has answer: http://stackoverflow.com/a/52183616
upvote count: 3
has title: how to calculate sum|mean|median for tail of each group when pandas data aggregated in python
downvote count: 0
tagged with: tail
accepted answer: http://stackoverflow.com/a/52183616
tagged with: pandas-groupby
tagged with: pandas
type: AnsweredQuestion
score: 3
favorite count: 0
type: Question
tagged with: python
answer count: 1
has body: i am having data like following.which is in pandas data frame format. A B C D E F G 1 1 2 3 1 4 2 1 1 2 4 5 6 7 1 1 2 3 2 3 2 1 1 2 4 5 6 7 2 1 2 3 2 3 4 2 1 2 3 4 3 3 2 1 2 4 5 6 7 here agg_lvl=['A','B','C'] I want to calculate mean|median|sum for G variable by using tail(2) records in each group when data aggregated to agg_lvl. And my expected output is like this: expected output for mean: A B C G 1 1 2 4.5 2 1 2 5 the output will be same for median and sum also,but in place of mean we have to consider median and sum values. for that i tried the following code but i didn't get the expected output. df.groupby(agg_lvl,as_index=False).tail(2).agg({'G':'mean'}) can anyone help me tackle this issue. Thanks in advance.

http://stackoverflow.com/q/52212118
answer count: 1
has body: I have a binary file that contains one line of: abcd1234 In Python, reading this binary file using filecontent = f_obj.read() results in: filecontent = b'abcd1234' I want to store the result of filecontent into a byte array as: array[0] = 0xab array[1] = 0xcd array[2] = 0x12 array[3] = 0x34 Is there a Python function that can do this conversion?
favorite count: 0
tagged with: binary
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91375632
has comment: http://stackoverflow.com/comment/91373751
has comment: http://stackoverflow.com/comment/91374112
has comment: http://stackoverflow.com/comment/91373864
downvote count: 1
has title: Python: Converting binary data to hex array
type: Question
has answer: http://stackoverflow.com/a/52212375
tagged with: arrays
score: -1
has comment: http://stackoverflow.com/comment/91373696
upvote count: 0

http://stackoverflow.com/q/52239441
tagged with: python
has comment: http://stackoverflow.com/comment/91427656
has body: Right so I have just started learning time stuff in Python and I am trying to make it that if the time is lets say 22:00 at night it would tell you that it is night time and the shops are closed. Here is what I have: import time; localtime = time.asctime( time.localtime(time.time()) ) print ('Local current time :', localtime) I am sorry that I have to ask questions that are probably dumb but yeah...
has comment: http://stackoverflow.com/comment/91427799
has title: Time system for a python adventure game
type: Question
has comment: http://stackoverflow.com/comment/91427811
upvote count: 1
has comment: http://stackoverflow.com/comment/91428001
has comment: http://stackoverflow.com/comment/91427806
score: 0
downvote count: 1
favorite count: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91427545

http://stackoverflow.com/comment/91242130
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52146184
score: 0
has text: It might help if you show the install command that you used.

http://stackoverflow.com/q/52258913
has comment: http://stackoverflow.com/comment/91465633
favorite count: 0
type: Question
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91465529
accepted answer: http://stackoverflow.com/a/52259197
tagged with: django-south
has comment: http://stackoverflow.com/comment/91473972
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91465503
upvote count: 20
tagged with: database-migration
has comment: http://stackoverflow.com/comment/91465673
tagged with: django-models
has body: Can anyone please explain me the difference between south migrations and django migrations? What advantage/disadvantage one has over another?
has comment: http://stackoverflow.com/comment/97714858
score: 19
has title: What is the difference between south migrations and django migrations?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52259197

http://stackoverflow.com/q/52189915
tagged with: lag
has title: Toda-Yamamoto Granger Causality Test in Python
tagged with: causality
tagged with: var
score: 1
has answer: http://stackoverflow.com/a/52191716
upvote count: 1
type: Question
tagged with: statsmodels
has body: I am trying to perform the Toda - Yamamoto procedure of Granger Causality testing with Python statsmodels between two series: stock price and interest rate. The procedure is clearly explained here: https://davegiles.blogspot.com/2011/04/testing-for-granger-causality.html The problem is that I can't find the way to get a different lag length for the exogenous variables in Statmodels Var. Any helps would be greatly appreciated!
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/52196978
upvote count: 1
answers question: http://stackoverflow.com/q/52116574
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91361426
has body: Producing a Basemap.contourf plot is a pretty standard procedure. Your plt.imread command should return you a 2D numpy array (assuming it is grey scale), so do something like this to get the actual data and its dimensions: data = plt.imread('./pngs/9905.png') lx, ly = data.shape Next you need to provide coordinates for each point of your data. For contourf this is done providing two additional 2D fields, one with the x-coordinates and one with the y-coordinates. You can get the right form with np.linspace and np.meshgrid: lon0, lat0 = lon_air-((360*920)/(4*np.pi*6371)),lat_air-((360*920)/(4*np.pi*6371)) lon1, lat1 = lon_air+((360*920)/(4*np.pi*6371)), lat_air+((360*920)/(4*np.pi*6371)) lons = np.linspace(lon0, lon1, lx) #1D lats = np.linspace(lat0, lat1, ly) #1D lon, lat = np.meshgrid(lons,lats) #1D --&gt; 2D Now you still need to convert your map coordinates into projection coordinates and then plot the whole thing: x,y = m(lon, lat) m.contourf(x,y,data) plt.show() There may be still some issues with the arrangement of the data (it's sometimes a bit confusing), so you might have to transpose it (data.T) or invert a dimension (by indexing [::-1]). If you run into these kind of problems, please ask (or provide an example image), then I can adjust the answer accordingly. Oh, and remember to add a import numpy as np somewhere in the beginning of your script.
has comment: http://stackoverflow.com/comment/91356399
has comment: http://stackoverflow.com/comment/91361362

http://stackoverflow.com/comment/91272931
has text: If you wish, post preferably the error message, otherwise anybody can't help you much.
comment on: http://stackoverflow.com/a/52161467
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/52137351
tagged with: pyspark
answer count: 1
downvote count: 0
favorite count: 0
has title: Pyspark python reduceByKey filter by math.max
tagged with: filter
tagged with: apache-spark
has body: I have a rdd with Key as date and Value as . something like: 2017-07-03 00:00:00 (u'LANXESS', 17119) 2017-07-03 00:00:00 (u'SCHALTBAU', 225) 2018-05-08 00:00:00 (u'LINDE', 8105) 2018-05-08 00:00:00 (u'HSBC', 16084) I want to use rdd.reduceByKey and I want to choose the maximum of the "somenumber". so for the sample input I am expecting to see: 2017-07-03 00:00:00 (u'LANXESS', 17119) 2018-05-08 00:00:00 (u'HSBC', 16084) which is actually the date is my key and the values are got filtered. I am trying to do something like: test4 = test3.reduceByKey(lambda a,b: math.max(a_2)) but I assume its wrong. How would I be able to do it? Thanks
score: 1
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52145750
type: Question

http://stackoverflow.com/a/52192168
has comment: http://stackoverflow.com/comment/91365164
score: 0
has comment: http://stackoverflow.com/comment/91393906
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91396470
has body: Yes, you can do @bot.event async def on_message(message): if message.content == "Hi": await bot.send_message(message.channel,"Hello") This way you use an event instead of a command so when you write "Hi" into the chat the bot will catch it and run the method If you want to pass something to the command function you can do so just like you would with a normal method @bot.command() async def example(something): print(something) When you do !example Hello There the bot will print out Hello because from the strings it got as input (separated by whitespaces) it picked the first value and assigned it to your variable just like a normal program getting its input from the command line. To catch all elements you can use *args @bot.command() async def example(*args): print(args) which will return a tuple of all the values you gave from the chat. !example Hello There will print out ('Hello', 'There')
type: Answer
accepted answer of: http://stackoverflow.com/q/52191882
answers question: http://stackoverflow.com/q/52191882
has comment: http://stackoverflow.com/comment/91365294
has comment: http://stackoverflow.com/comment/91396142
has comment: http://stackoverflow.com/comment/91393954

http://stackoverflow.com/comment/106942219
type: Comment
score: 0
has text: @XiuchaoWu do you have any idea, how long does scheduler take to be aware of new dag's join?
comment on: http://stackoverflow.com/a/52572372
type: AnswerComment

http://stackoverflow.com/comment/91634140
type: QuestionComment
type: Comment
score: 0
has text: @Isma Yeah I haven't tried it. My PC broke and I'll get new parts probably wednesday/thursday.
comment on: http://stackoverflow.com/q/52225035

http://stackoverflow.com/q/52254211
tagged with: flask-wtforms
has answer: http://stackoverflow.com/a/52256052
tagged with: python
accepted answer: http://stackoverflow.com/a/52254369
type: AnsweredQuestion
downvote count: 0
score: 1
has body: Is it possible to do validation on a datetime field in WTForms comparing it to another datetime? I have the form class EventEdit(FlaskForm): timeIn = DateTimeField('Time In', validators=[DataRequired()]) timeOut = DateTimeField('Time Out', validators=[DataRequired()]) reason = RadioField('Reason', choices=[ ('Incident','Incident'), ('Gym','Gym'), ('Meeting','Meeting'), ('Other','Other')]) comment = StringField('Additional Comments') submit = SubmitField('Save Changes') I need to make sure when timeOut is entered it is greater than timeIn. Additionally, I haven't been able to get the timeOut field to be optional yet either. Thanks in advance.
has answer: http://stackoverflow.com/a/52254369
type: Question
tagged with: flask
answer count: 2
upvote count: 1
favorite count: 0
has title: Python Flask WTForms datetime validate another
possible better answer: http://stackoverflow.com/a/52256052

http://stackoverflow.com/comment/136682191
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52213628
score: 0
has text: There is no MWE and can mot be replicated.

http://stackoverflow.com/comment/91299830
has text: read the csv file, add each row to a list or dictionary. Then sort by the date index or key.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52174371

http://stackoverflow.com/comment/91460757
score: 0
comment on: http://stackoverflow.com/a/52249698
type: Comment
type: AnswerComment
has text: Also to your another point, I am reusing the `pool` to the extend that, IMHO, keeps code readable. Thanks to Numpy I was able to improve performance of other parts of the code significantly so I definietly appreciate the performance speed-ups that it offer but I do not think I can use it for remaining part. And at this point I am curious to find what are the limitations of multiprocessing on Windows. Could it be that for list with `1000` elements it simply does not make sense to create new process as overhead is too big?

http://stackoverflow.com/q/52195607
has body: Say I have a string: some_string = 'lorum ipsum 123 bar foo 1. \ more text 46 here 2. some more text here \ 3. and even more text here 789' How could I remove all the digits except for ones trailed with a period using Regex (or any other method)? Ideal outcome: some_string = 'lorum ipsum bar foo 1. \ more text here 2. some more text here \ 3. and even more text here' I'm a Regex beginner and have only tried [0-9]\. but this highlights what I want to keep. I'd like to keep digits in the form of 1., 2., etc Thank you.
favorite count: 0
has comment: http://stackoverflow.com/comment/91340826
has answer: http://stackoverflow.com/a/52195653
tagged with: python
accepted answer: http://stackoverflow.com/a/52195715
tagged with: regex
type: AnsweredQuestion
has title: Remove all digits from a Python string except digits followed by period
possible better answer: http://stackoverflow.com/a/52195653
downvote count: 2
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91340843
has comment: http://stackoverflow.com/comment/91340833
score: -1
has answer: http://stackoverflow.com/a/52195715
answer count: 2
has comment: http://stackoverflow.com/comment/91340822
linked to: http://stackoverflow.com/q/16721992
tagged with: string

http://stackoverflow.com/q/52229954
has title: Getting column value based on other multiple conditions
tagged with: python
has answer: http://stackoverflow.com/a/52229980
has body: I have a dataframe: cid si A 1 A 0 A 1 A 0 A 1 A 0 A 0 A 0 A 0 A 0 A 0 A 0 A 0 A 0 B 1 B 0 B 0 B 0 B 0 B 0 B 0 I need to have another column with named ide which should add the same value until next 1 in si is encountered and value in cid remains same. If value in cid gets changed the identifier starts over. Adding sample output. cid si ide A 1 aa A 0 aa A 1 bb A 0 bb A 1 cc A 0 cc A 0 cc A 0 cc A 0 cc A 0 cc A 0 cc A 0 cc A 0 cc A 0 cc B 1 aa B 0 aa B 0 aa B 0 aa B 0 aa B 0 aa B 0 aa
has comment: http://stackoverflow.com/comment/91409655
upvote count: 1
has comment: http://stackoverflow.com/comment/91409595
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91409648
score: 1
accepted answer: http://stackoverflow.com/a/52229980
has comment: http://stackoverflow.com/comment/91409557
type: Question
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91409592
favorite count: 0
tagged with: pandas

http://stackoverflow.com/comment/132926289
type: Comment
comment on: http://stackoverflow.com/a/73563211
score: 0
type: AnswerComment
has text: I figured it out. I needed to add text from SQL alchemy. "from sqlalchemy import text" then query = (text("select *from SQL"))

http://stackoverflow.com/comment/91380128
type: Comment
comment on: http://stackoverflow.com/a/52150190
has text: Hi Sharku! I modified your code so that to create different filename for each loop and multiple images were saved as desired. The only difference is in the savefig command, which I attached here. `fig.savefig("%s.png" % (df))` However, in the output console, only the last graph was outputted in the console. Although this shouldn't be too big a issue, but still will be neat if python can output all graphs in the console window!
type: AnswerComment
score: 0

http://stackoverflow.com/q/52250121
type: UnansweredQuestion
score: 6
tagged with: python
tagged with: dictionary
has body: I'm having some trouble adding a key-value pair to a nested dictionary. The new pair seems to be getting added to ALL entries in the outer dictionary, instead of just the nested dictionary that I want. Here's an example: mykeys = ['key1', 'key2', 'key3'] mydictionary = dict.fromkeys(mykeys, {}) mydictionary['key1']['subkey1'] = 'value1' mydictionary I'm expecting to see the following, with 'subkey1' only being added to the 'key1' dictionary: {'key1': {'subkey1': 'value1'}, 'key2': {}, 'key3': {}} Instead, it adds the subkey1/value1 pair to every element of the outer dictionary: {'key1': {'subkey1': 'value1'}, 'key2': {'subkey1': 'value1'}, 'key3': {'subkey1': 'value1'}} Why is this the case, and how can I re-write my code to fix this mistake?
has comment: http://stackoverflow.com/comment/91448433
upvote count: 7
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/29116226
has answer: http://stackoverflow.com/a/52250169
duplicate of: http://stackoverflow.com/q/29116226
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91448364
has title: Adding key-value pair to a nested dictionary

http://stackoverflow.com/comment/135435868
type: Comment
comment on: http://stackoverflow.com/a/52212966
has text: If the .py file is named wordcloud.py it will also return this error.
type: AnswerComment
score: 0

http://stackoverflow.com/q/52216451
favorite count: 0
has body: I'm getting into penetration testing/vulnerability exploitation, and have been working on a reverse-engineering challenge recently. For the challenge, there is a remote application that I connect to via port 2888 (I'm using netcat with the following command): nc xxx.xxx.x.xx 2888 Then, I receive a prompt asking me to enter input, which is then "encrypted" and given back to me. The challenge provides an ELF binary which it claims mirrors functionality of the Internet-connection version. I spent a lot of time analyzing that binary, and have found a classic buffer overflow vulnerability. I'm pretty sure the server has ASLR and DEP enabled, so I have used return-oriented programming to develop a ROP chain that will allow me to execute a command. (I'll post this at the bottom of the question) All I have to do to win the challenge is execute the following command: /bin/flag myemail123@gmail.com Then, the server should send me the flag. I've configured my ROP chain to launch an execve command with the above command within. For testing purposes, I ran the binary in a VM, then piped my ROP chain (generated with python) into port 2888 on the VM. python ./ropchain.py | nc localipaddress 2888 I changed the command to /bin/echo to see if I was getting the exploit right, and sure enough it echoes my email address. Also, when I strace the local binary, execve has all the inputs I expect. However, when I try to pipe my ROP chain like I did above into the live server, it writes the input into stdin before the application is ready for it, and the exploit doesn't work. (I don't get an email). I've analyzed my two commands with Wireshark and I'm getting a FIN/ACK packet when I shouldn't be when connecting to the live server. My question is, how can I write the packed addresses and such that make up my ROP chain into the remote application, but wait until it is ready for input? Am I going about this the right way? I will include my ROP chain as well for reference. Thank you!! Below is t…
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0
has title: Remote Code Execution Exploitation: Delaying Binary Input to a Web Application
score: 1
tagged with: netcat
type: Question
tagged with: network-programming
tagged with: security
upvote count: 1

http://stackoverflow.com/q/52265087
has answer: http://stackoverflow.com/a/52265492
answer count: 1
downvote count: 0
has body: I have very basic sample of Linear Regression. Implementation below (without Regularization) class Learning: def assume(self, weights, x): return np.dot(x, np.transpose(weights)) def cost(self, weights, x, y, lam): predict = self.assume(weights, x) \ .reshape(len(x), 1) val = np.sum(np.square(predict - y), axis=0) assert val is not None assert val.shape == (1,) return val[0] / 2 * len(x) def grad(self, weights, x, y, lam): predict = self.assume(weights, x)\ .reshape(len(x), 1) val = np.sum(np.multiply( x, (predict - y)), axis=0) assert val is not None assert val.shape == weights.shape return val / len(x) And I want to check gradient, that it works, with scipy.optimize. learn = Learning() INPUTS = np.array([[1, 2], [1, 3], [1, 6]]) OUTPUTS = np.array([[3], [5], [11]]) WEIGHTS = np.array([1, 1]) t_check_grad = scipy.optimize.check_grad( learn.cost, learn.grad, WEIGHTS,INPUTS, OUTPUTS, 0) print(t_check_grad) # Output will be 73.2241602235811!!! I manually checked all computation from start to end. And it's actually right implementatino. But in output I see extremely big difference! What is the reason?
favorite count: 0
upvote count: 2
tagged with: regression
tagged with: machine-learning
tagged with: python
has title: Linear Regression Gradient
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52265492
tagged with: linear-regression
tagged with: scipy
type: Question

http://stackoverflow.com/a/52464076
has comment: http://stackoverflow.com/comment/91905421
accepted answer of: http://stackoverflow.com/q/52239315
has comment: http://stackoverflow.com/comment/91870097
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I think your solution is a mixture of Child Aggregation and top_hits: POST logger-log/_search?size=0 { "aggs": { "top-loggers": { "terms": { "field": "name" }, "aggs": { "to-logs": { "children": { "type" : "log" }, "aggs": { "top-logs": { "top_hits": { "size": 1, "sort": [ { "timestamp": { "order": "desc" } } ] } } } } } } } }
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52239315

http://stackoverflow.com/q/52193142
favorite count: 0
has body: I have an html template, which is used to render an email, in that template, I want to attach verification links. I am using the following code to generate the link {% url 'verify_email' token=token email=email %} but this one generates following URL instead of absolute URL. I read this SO thread How can I get the full/absolute URL (with domain) in Django? and some initial google results but all of them seems old and not working for me. TLDR: How do I generate absolute URLs in Django2 template files
has answer: http://stackoverflow.com/a/52193869
accepted answer: http://stackoverflow.com/a/52193869
tagged with: python
linked to: http://stackoverflow.com/q/2345708
tagged with: django
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
upvote count: 1
has title: How to generate absolute urls in Django 2 templates
answer count: 1
tagged with: django-2.1

http://stackoverflow.com/q/52167460
has comment: http://stackoverflow.com/comment/91285092
has comment: http://stackoverflow.com/comment/91291139
tagged with: python
linked to: http://stackoverflow.com/q/49961991
answer count: 0
type: UnansweredQuestion
type: Question
tagged with: pyspark
has body: I have example 10 rows, 9 columns data frame in pandas and want to use it in pyspark. For some reason pyspark method collect() raises error, and error is meaningless or cryptic enough to be seen as meaningless. My question is why I am not able to use my dataframe in pyspark? Please find all details below. python 3.6.5, java 10.0.2 pyspark installed with pip, run on single machine. import pandas as pd pd.__version__ #'0.23.4' pf = pd.DataFrame.from_dict({'id1': {0: 'id046', 1: 'id041', 2: 'id036', 3: 'id067', 4: 'id047', 5: 'id003', 6: 'id052', 7: 'id024', 8: 'id051', 9: 'id048'}, 'id2': {0: 'id018', 1: 'id047', 2: 'id039', 3: 'id100', 4: 'id086', 5: 'id002', 6: 'id018', 7: 'id062', 8: 'id043', 9: 'id051'}, 'id3': {0: 'id0000006976', 1: 'id0000009477', 2: 'id0000003195', 3: 'id0000001035', 4: 'id0000005874', 5: 'id0000001900', 6: 'id0000002599', 7: 'id0000005962', 8: 'id0000003913', 9: 'id0000001059'}, 'id4': {0: 97, 1: 89, 2: 23, 3: 44, 4: 79, 5: 10, 6: 42, 7: 34, 8: 51, 9: 60}, 'id5': {0: 67, 1: 75, 2: 33, 3: 31, 4: 75, 5: 34, 6: 73, 7: 57, 8: 58, 9: 49}, 'id6': {0: 7103, 1: 699, 2: 7180, 3: 3189, 4: 5530, 5: 4013, 6: 4912, 7: 1677, 8: 9892, 9: 5903}, 'v1': {0: 3, 1: 4, 2: 1, 3: 3, 4: 5, 5: 3, 6: 5, 7: 5, 8: 3, 9: 1}, 'v2': {0: 5, 1: 4, 2: 2, 3: 2, 4: 4, 5: 1, 6: 1, 7: 5, 8: 5, 9: 4}, 'v3': {0: 2.4358, 1: 15.3333, 2: 82.1465, 3: 32.4652, 4: 2.4358, 5: 73.0214, 6: 13.958, 7: 30.7107, 8: 5.1784, 9: 63.2878}}) import pyspark as ps ps.__version__ #'2.3.1' from pyspark.sql import SparkSession spark = SparkSession.builder.appName("appname").getOrCreate() sf = spark.createDataFrame(pf) sf.collect() Error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/jan/git/my-project/spark/py-spark/lib/python3.6/site-packages/py spark/sql/dataframe.py", line 466, in collect sock_info = self._jdf.collectToPython() spark/sql/dataframe.py", line 466, in collect [63/4510] sock_info = self._jdf.collectToPython() File "/home/jan/git/my-project/…
has title: pyspark dataframe's collect method raises exception
score: 0
duplicate of: http://stackoverflow.com/q/49961991
tagged with: apache-spark

http://stackoverflow.com/comment/91222635
score: 1
comment on: http://stackoverflow.com/q/52136351
type: Comment
type: QuestionComment
has text: still would be much better if you just showed what the output you want would actually look like

http://stackoverflow.com/comment/91319290
has text: @user10319541 Need to answer a call. Will be back if nobody else answers.
comment on: http://stackoverflow.com/a/52183261
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52116929
downvote count: 0
upvote count: 2
type: Answer
has body: Simply {% for diameter, length in circuit.pipe_lengths.items %} {{ diameter.nom_diameter }} {{ length }} {% endif %} should do.
accepted answer of: http://stackoverflow.com/q/52116723
answers question: http://stackoverflow.com/q/52116723
type: AcceptedAnswer
score: 2

http://stackoverflow.com/q/52119080
linked to: http://stackoverflow.com/q/47466255
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: oop
score: 1
upvote count: 1
has title: Python class derived from pandas DataFrame with list/DataFrame attribute
type: Question
has answer: http://stackoverflow.com/a/52119158
downvote count: 0
has body: I am trying to create a class derived from pandas DataFrame. The class shall have each an attribute of type string, DataFrame and list. There is no problem with the string attribute, but DataFrame and list each cause a warning. Despite the warnings, the code seems to behave correctly. Can anyone help me to fix my code? Or suppress the warnings? Code: import pandas as pd class MyClass(pd.DataFrame): def __init__(self, arg_string, arg_dataframe, *arg_params): pd.DataFrame.__init__(self) self._string = arg_string self._dataframe = arg_dataframe self._params = arg_params if __name__=='__main__': df = pd.DataFrame() c1 = MyClass("test", df, 1, 2, 3) print(c1._string) print(c1._dataframe) print(c1._params) Warning message: so_example.py:7: UserWarning: Pandas doesn't allow columns to be created via a new attribu te name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access self._dataframe = arg_dataframe so_example.py:8: UserWarning: Pandas doesn't allow columns to be created via a new attribu te name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access self._params = arg_params Stdout: test Empty DataFrame Columns: [] Index: [] (1, 2, 3)
accepted answer: http://stackoverflow.com/a/52119158
tagged with: pandas

http://stackoverflow.com/a/52215773
accepted answer of: http://stackoverflow.com/q/52215642
answers question: http://stackoverflow.com/q/52215642
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91380421
has body: You need to iterate over the credentials array and print the values you want. response = requests.get(url, verify=False, auth=(user, api_token)) response.status_code json_data = response.json() #iterate over credentials array for credentials in json_data['credentials']: print(credentials['displayName']) print(credentials['id']) print(credentials['typeName'])
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/91380504
score: 1

http://stackoverflow.com/q/52169497
has body: class SalesRecord(): def __init__(self, *args): self.ProductID = args[0] self.Date = args[1] self.StoreNum = args[2] self.Units = args[3] self.PricePerUnit = args[4] self.Total = args[5] salesreader = csv.reader(salesfile) e1 = [] e2 = [] index = 0 for row in salesreader: if index != row: e2.append(SalesRecord(*row)) else: e1.append(row) I am trying to take the first row of the data set and assign the column headers as e1 and explode out the detail on e2. I am struggling with the iteration of a list position.
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/52189156
has comment: http://stackoverflow.com/comment/91327501
tagged with: python
has title: CSV To headers and Exploding results into custom class
type: UnansweredQuestion
upvote count: 1
score: 1
tagged with: loops
type: Question
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/91367897
score: 0
comment on: http://stackoverflow.com/q/52209274
has text: Also, breakpoint might not be the correct term here. Feel free to comment or update with correct terminology.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52226915
has title: Python Logging: How to pass logging level as an argument
answer count: 1
upvote count: 6
has body: How can we pass logging level as an argument? For example: level1 = 'DEBUG' level1lower = level1.lower() logger.setLevel(logging.level1) logger.level1lower('Some messages passed for logging's) This is the closest representation of my problem coz I want to write one function that would take logging levels as argument.
favorite count: 0
has answer: http://stackoverflow.com/a/52227030
accepted answer: http://stackoverflow.com/a/52227030
tagged with: python
downvote count: 0
score: 6
tagged with: logging
type: AnsweredQuestion
type: Question

http://stackoverflow.com/a/52132228
score: 0
has body: Try this: def chaselect(): print 'Now you must choose your race ' while player.race == None: ace = raw_input('1. Human \n2. Elf \n3. Dwarf \n4. Orc\n') if ace == '1': print 'You chose human are you sure?' con = raw_input('\n1. Confirm Race\n2. Read Lore\n3. Go Back')
type: Answer
answers question: http://stackoverflow.com/q/52132072

audio-analysis
type: Tag
tag name: audio-analysis
tags question: http://stackoverflow.com/q/52134584

http://stackoverflow.com/comment/91333863
comment on: http://stackoverflow.com/a/52191405
score: 0
type: AnswerComment
has text: @davidyeritsyan my bad, I used the java version of getAttribute instead of the python get_attribute
type: Comment

http://stackoverflow.com/comment/91402763
type: Comment
score: 2
comment on: http://stackoverflow.com/a/52214543
type: AnswerComment
has text: I don't think that's exactly what I am looking for, I want to stop adding elements to `x_train` when it reaches a certain max number, I don't care for `x_test`, I want to do this to give the smaller classes a fighting chance in the classifier.

http://stackoverflow.com/comment/91298191
comment on: http://stackoverflow.com/a/52173454
score: 1
type: AnswerComment
has text: Really well done; I appreciate your time and effort :)!
type: Comment

http://stackoverflow.com/q/52132072
favorite count: 0
possible better answer: http://stackoverflow.com/a/52132228
has comment: http://stackoverflow.com/comment/91215162
tagged with: python
has comment: http://stackoverflow.com/comment/91214751
has answer: http://stackoverflow.com/a/52132228
has comment: http://stackoverflow.com/comment/91214713
type: AnsweredQuestion
upvote count: 0
tagged with: syntax
tagged with: error-handling
accepted answer: http://stackoverflow.com/a/52133416
downvote count: 1
has body: Ok so is inside the print function is an error. And I can't seem to get rid of is here is my code: def chaselect(): print ''' Now you must choose your race ''' while player.race == None: ace = raw_input(''' 1. Human 2. Elf 3. Dwarf 4. Orc ''')) if ace == '1': print 'You chose human are you sure?' con = raw_input(''' 1. Confirm Race 2. Read Lore 3. Go Back ''')) This is python 2.7.11 so I do not need to do print('e.g') Now what happens is a syntax error happens inside the print? How do I fix this? And why is it coming up with this error?
type: Question
has answer: http://stackoverflow.com/a/52133416
score: -1
has title: Invaild Syntax Python Inside print 2.7.11
tagged with: python-2.7
answer count: 2

http://stackoverflow.com/q/52176262
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91303107
tagged with: async-await
type: Question
has title: Why await takes so many times?
has comment: http://stackoverflow.com/comment/91303330
score: 0
upvote count: 1
has body: I make a crawler to get some barrage from the website. some problem appeared.out of my expectation, it only take 30 seconds to send all requests but 9 mins for await response....is it a normal case? Otherwise,I just learned trio a few days ago. enter image description here Here is codes enter image description here # coding=utf8 import argparse import json import logging import os import time from pprint import pprint import asks import trio from pyquery import PyQuery as jq logger = logging.getLogger('TencentVideoDanmu') parser = argparse.ArgumentParser() parser.add_argument( '-u', '--url', default="https://v.qq.com/x/cover/p69wlzli02uqwms/d0023ka5gj7.html", type=str, help='TencentVideo URL') args = parser.parse_args() asks.init('trio') AsyncSession = asks.Session() AsyncSession.headers = { "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "accept-encoding": "gzip, deflate, br", "accept-language": "zh-CN,zh;q=0.9,en;q=0.8", "cache-control": "max-age=0", # "cookie": "pgv_info=ssid=s2580931560; pgv_pvid=5076745702; pgv_pvi=4425950208; pgv_si=s1770592256; ptisp=ctc; ptui_loginuin=2669082133; RK=nEJ5woVFyj; ptcz=50e9cdd6ca5afc08869af7a57c608b471a0f19bf39b7aa9925998682e417bfed; ts_uid=8763758775; pac_uid=1_2669082133; tvfe_boss_uuid=c12202d727ca41e8; ts_refer=www.google.ca/; tvfe_search_uid=2db4e25f-aeb5-49cd-b1c6-f66810ab9ea2; login_remember=qq; uin=o0418022662; skey=@RSqEKv4JE; pt2gguin=o0418022662; luin=o0418022662; lskey=000100006089c7a41592fa402e43fd746cc963aae100ef17d5b32db028640097f8dcd9ba33b3f9c6aa3344af; main_login=qq; vuserid=603827039; vusession=d91d873ac7e989b47e1c07f3f2a0; encuin=17cb5e5a4732f6fdbcfe344f11a106c5|418022662; lw_nick=%E9%A2%96|418022662|//thirdqq.qlogo.cn/g?b=sdk&amp;k=2vGdibPiatOuMmNT6L1ZSicvA&amp;s=40&amp;t=1524547387|1; uid=685097243; o_cookie=418022662; ts_last=v.qq.com/x/cover/p69wlzli02uqwms/d0023ka5gj7.html; ptag=www_google_ca|videolist:pagetab; ad_play_index=93", "referer": "http://v.qq.…
downvote count: 1
tagged with: asynchronous
favorite count: 0
answer count: 0

http://stackoverflow.com/comment/91466980
has text: Use pywinauto to basically save the entire pages html and images. Alternatively hit "Control"+P to print to pdf, again using pywinauto. Also open to any other better ways to save a webpage with all images intact.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52251019

http://stackoverflow.com/q/52258446
accepted answer: http://stackoverflow.com/a/52315272
has answer: http://stackoverflow.com/a/52312677
has answer: http://stackoverflow.com/a/52298640
has body: How do I access the constants available as file formats when saving a Powerpoint presentation through comtypes? In the following example 32 is used as the format but I would like to use the constants listed here) or at least find a documented list with value for each constant. For Word there is this list that also contains the value for each constant. import comtypes.client powerpoint = comtypes.client.CreateObject("Powerpoint.Application") pres = powerpoint.Presentations.Open(input_path) pres.SaveAs(output_path, 32)
possible better answer: http://stackoverflow.com/a/52312677
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91464391
favorite count: 0
has comment: http://stackoverflow.com/comment/91464535
has title: Using file format constants when saving PowerPoint presentation with comtypes
type: Question
has answer: http://stackoverflow.com/a/52315272
has comment: http://stackoverflow.com/comment/91576976
tagged with: python
score: 7
tagged with: comtypes
answer count: 3
tagged with: powerpoint
upvote count: 7

http://stackoverflow.com/comment/91471359
type: Comment
has text: As for performance: the way you’re testing for primes takes a quadratic number of divisions. For 2 million primes, that’s 4 trillion divisions. That’s going to take a very long time. If you want this to be faster, you have to implement a more efficient prime test algorithm. Or, better, a prime generation algorithm that doesn’t depend on testing each number, like a sieve. There are plenty of good examples online.
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52261828

http://stackoverflow.com/comment/91443960
score: 0
type: Comment
type: QuestionComment
has text: What if a character (like `a`) appears only once or appears more than twice? Do you want the tuple that follows the character in your desired result to change in length? Also, is the result really supposed to be a list of tuples or is it to be another dictionary? If a list, does the order of the items in the list matter?
comment on: http://stackoverflow.com/q/52248068

http://stackoverflow.com/comment/91317478
type: QuestionComment
score: 1
has text: Unless of course you then show a page with download links for the files your app retrieved and let the user download them manually, or something similar (you can zip the files in a single archive for example), but this will still requires TWO downloads: the flask app downloading files from tennis-warehouse and storing them on the server's filesystem, then the user downloading the files from the flask app.
comment on: http://stackoverflow.com/q/52183357
type: Comment

http://stackoverflow.com/a/52173992
answers question: http://stackoverflow.com/q/52169468
downvote count: 0
has comment: http://stackoverflow.com/comment/91314985
type: Answer
has body: There are numerous Python wrappers for Stanford CoreNLP. There is a list here (along with wrappers for other languages). You need to run the Stanford CoreNLP server first. Here is a bit of code that uses pycorenlp: from pycorenlp import StanfordCoreNLP nlp = StanfordCoreNLP('http://localhost:9000') text = "Ceci est un test de l'étiqueteur morpho-syntaxique du français." output = nlp.annotate(text, properties={ 'annotators': 'tokenize, ssplit, pos', 'outputFormat': 'json' }) from pprint import pprint pprint(output) The result is a JSON data structure (you can choose other formats by specifying a different value, for the outputFormat property e.g. 'text', 'xml'...) with all the annotations, including POS tags (the pos attribute for each token), as follows: {'sentences': [{'index': 0, 'tokens': [{'after': ' ', 'before': '', 'characterOffsetBegin': 0, 'characterOffsetEnd': 4, 'index': 1, 'originalText': 'Ceci', 'pos': 'NNP', 'word': 'Ceci'}, {'after': ' ', 'before': ' ', 'characterOffsetBegin': 5, 'characterOffsetEnd': 8, 'index': 2, 'originalText': 'est', 'pos': 'NNP', 'word': 'est'}, {'after': ' ', 'before': ' ', 'characterOffsetBegin': 9, 'characterOffsetEnd': 11, 'index': 3, 'originalText': 'un', 'pos': 'JJ', 'word': 'un'}, {'after': ' ', 'before': ' ', 'characterOffsetBegin': 12, 'characterOffsetEnd': 16, 'index': 4, 'originalText': 'test', 'pos': 'NN', 'word': 'test'}, {'after': ' ', 'before': ' ', 'characterOffsetBegin': 17, 'characterOffsetEnd': 19, 'index': 5, 'originalText': 'de', 'pos': 'IN', 'word': 'de'}, {'after': ' ', 'before': ' ', 'characterOffsetBegin': 20, 'characterOffsetEnd': 32, 'index': 6, 'originalText': "l'étiqueteur", 'pos': 'JJ', 'word': "l'étiqueteur"}, {'after': ' ', 'before': ' ', 'characterOffsetBegin': 33, 'characterOffsetEnd': 50, 'index': 7, 'originalText': 'morpho-syntaxique', 'pos': 'JJ', 'word': 'morpho-syntaxique'}, {'after': ' ', 'before': ' ', 'characterOffsetBegin': 51, 'characterOffsetEnd': 53, 'index': 8, 'originalText': 'du', …
upvote count: 1
has comment: http://stackoverflow.com/comment/91320095
score: 1

http://stackoverflow.com/comment/91255833
type: Comment
comment on: http://stackoverflow.com/q/52152482
has text: @blue_note: there would be no error in array[0]=someValue if it were to be an array of any other language.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91293677
comment on: http://stackoverflow.com/a/52171419
type: AnswerComment
has text: Please see my edit for an example of the format of my file and what I'd like from it. The problem is the new line after each line, and the fact that they are strings (including the `[` and `]` characters). I tried your suggestion just now but it didn't work with the formatting.
score: 0
type: Comment

http://stackoverflow.com/comment/91263399
score: 0
type: Comment
type: QuestionComment
has text: I used MySQL Workbench to confirm that the new records are being persisted, and I'm not sure about the second point and in fact that is what I was suspecting was happening, but I wasn't sure if that's how the session worked or not. If there's a way to refresh the session that would solve my problem.
comment on: http://stackoverflow.com/q/52156515

http://stackoverflow.com/comment/91298351
type: AnswerComment
type: Comment
has text: @thor the code I wrote also works if you use `df = pd.read_csv('C:\example.csv', usecols= ['from','to', 'month'])` , the new columns will be added automatically to the dataframe when you first try to use it. The only difference is that we order of the columns will be different. Please accept my answer, thanks.
comment on: http://stackoverflow.com/a/52157292
score: 0

http://stackoverflow.com/a/52139674
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91229187
accepted answer of: http://stackoverflow.com/q/52139610
type: Answer
has body: Your first problem is that you're comparing the strings "_number" and "random". ASCIIbetically (or, rather, Unicoderifically), "_number" &lt; "random", because the _ character is #95 and the r character is #114. If you want to compare two variables, you just refer to the variables, not strings that happen to be the same as the names of those variables. Your second problem is that random isn't your random number, it's the module you used to create that number. And, more seriously, you aren't storing that number anywhere—you're just converting it to a string to print it out and then throwing it away. Your third problem is that you need to change those ifs to elifs. Otherwise, the You Lost message gets printed whenever _number &gt; random is not true, instead of only whenever all of the three comparisons are not true. Putting that all together: choice = random.randint(1,11) for x in range(1): print ("Python chose: " + str(choice)) if (_number == choice): print ("You Won! :)") elif (_number &lt; choice): print ("Your number is less") elif (_number &gt; choice): print ("Your number is more") else: print ("You Lost :(") Of course there's no way to actually lose your game—one of the three conditions is always going to be true. (If you were using complex numbers, or floats including NaN, you could input a number that wasn't comparable in any way to the selected one, but you're not.) While we're at it: There's no reason to name your variable _number instead of number. That for x in range(1): loop doesn't do anything useful—it loops exactly once, setting x to 0, which you never use. You don't need parentheses around your conditions. You shouldn't import modules in the middle of a function like that except in special cases where you need unusual things like lazy loading. You should follow PEP 8 style, or at least pick a consistent style to follow. It's simpler to just pass multiple arguments to print, or to use string formatting, than to manually convert things to strings and …
score: 3
has comment: http://stackoverflow.com/comment/91229053
upvote count: 3
answers question: http://stackoverflow.com/q/52139610

http://stackoverflow.com/q/52200710
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has title: Pandas+seaborn faceting with multidimensional dataframes
has body: In Python pandas, I need to do a facet grid from a multidimensional DataFrame. In columns a and b I hold scalar values, which represent conditions of an experiment. In columns x and y instead I have two numpy arrays. Column x is the x-axis of the data and column y is the value of a function corresponding to f(x). Obviously both x and y have the same number of elements. I now would like to do a facet grid with rows and columns specifying the conditions, and in every cell of the grid, plot the value of column D vs column D. This could be a minimal working example: import pandas as pd d = [0]*4 # initialize a list with 4 elements d[0] = {'x':[1,2,3],'y':[4,5,6],'a':1,'b':2} # then fill these elements d[1] = {'x':[3,1,5],'y':[6,5,1],'a':0,'b':3} d[2] = {'x':[3,1,5],'y':[6,5,1],'a':1,'b':3} d[3] = {'x':[3,1,5],'y':[6,5,1],'a':0,'b':2} pd.DataFrame(d) # create the pandas dataframe How can I use already existing faceting functions to address the issue of plotting y vs x grouped by the conditions a and b? Since I need to apply this function to general datasets with different column names, I would like to avoid resorting on hard-coded solutions, but rather see whether it is possible to extend seaborn FacetGrid function to this kind of problem.
linked to: http://stackoverflow.com/q/38372016
answer count: 3
tagged with: pandas
upvote count: 1
possible better answer: http://stackoverflow.com/a/52201100
has answer: http://stackoverflow.com/a/53260164
has answer: http://stackoverflow.com/a/52201351
accepted answer: http://stackoverflow.com/a/52201351
has answer: http://stackoverflow.com/a/52201100
favorite count: 0
tagged with: facet
tagged with: seaborn
tagged with: python

http://stackoverflow.com/q/52259574
has comment: http://stackoverflow.com/comment/91467094
has comment: http://stackoverflow.com/comment/91467808
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91467049
has title: How plot a waterfall of Frequency with python
type: Question
has comment: http://stackoverflow.com/comment/91467379
linked to: http://stackoverflow.com/q/21166679
tagged with: spectrogram
has body: I have Frequency vs Magnitude, in a time. r.g. plt.plot(Frequency[0],Magnitude[0]) Now, I want to see all my Frequency vs Magnitude for each step of time, like the next image. Any framework suggestion? Thanks The image was taken from Here
answer count: 1
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/74809447
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/91181090
type: QuestionComment
has text: and how do i check that
comment on: http://stackoverflow.com/q/52114689
score: 0
type: Comment

curve-fitting
tags question: http://stackoverflow.com/q/52255824
tags question: http://stackoverflow.com/q/52114682
tags question: http://stackoverflow.com/q/52240034
tag name: curve-fitting
tags question: http://stackoverflow.com/q/52171155
tags question: http://stackoverflow.com/q/52254931
tags question: http://stackoverflow.com/q/52269680
tags question: http://stackoverflow.com/q/52146955
tags question: http://stackoverflow.com/q/52148141
type: Tag

http://stackoverflow.com/a/52246486
has comment: http://stackoverflow.com/comment/91441264
downvote count: 0
has body: Without seeing more of the source code, I guess the problem is based on where you call root.destroy() If it comes after the blocking tk.mainloop(), it will never be reached. Please read Tkinter understanding mainloop regarding this issue. A possible solution based on the above: while True: tk.update_idletasks() tk.update() if login_successful: # or whatever your login check looks like root.destroy() You replace the mainloop with your custom loop, which includes a check for a successful login.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52246412
score: 1
accepted answer of: http://stackoverflow.com/q/52246412
type: AcceptedAnswer

http://stackoverflow.com/comment/91351643
type: Comment
has text: @MartijnPieters: Ah right, I was typing `value2` instead of `print(value2)`.
type: QuestionComment
comment on: http://stackoverflow.com/q/52201197
score: 0

http://stackoverflow.com/q/52142950
has body: what i am trying in here is Make CancelCross child of Notifier class but when i do that the cross of CancelCross is not visible. But if i unparent it then it visible fine. I tried parenting it with QMainWindow as well but no luck. Is there something wrong in my code ? class CloseCrosss(QtGui.QFrame): def __init__(self, QWidgetparent = None): QtGui.QFrame.__init__(self, parent=QWidgetparent) def paintEvent(self, e): qp = QtGui.QPainter() pen = QtGui.QPen(Qt.red) qp.begin(self) qp.setPen(pen) qp.drawLine(460, 10, 470, 20) qp.drawLine(470, 10, 460, 20) qp.end() class Notifier(QtGui.QWidget): def __init__(self, message=None): QtGui.QWidget.__init__(self) self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) _desktop = QtGui.QApplication.desktop() size = _desktop.screenGeometry() self.resize(size.width() * 25 / 100, size.height() * 3 / 100) self.setAttribute(QtCore.Qt.WA_TranslucentBackground) self.main_layout = QtGui.QVBoxLayout() self.move(size.width() - (size.width() * 25 / 100) - 10, 50) self.main_layout.setContentsMargins(0, 0, 0, 0) self.main_layout.setSpacing(0) self.label = QtGui.QLabel(message) self.label.setStyleSheet("color: lightgreen; font: 14px;") self.label.setIndent(20) self.main_layout.addWidget(self.label) self.setLayout(self.main_layout) def paintEvent(self, event): s = self.size() qp = QtGui.QPainter() qp.begin(self) qp.setRenderHint(QtGui.QPainter.Antialiasing, True) qp.setPen(QtGui.QColor(255, 255, 255, 200)) qp.setBrush(QtGui.QColor(0, 0, 0, 200)) qp.drawRoundedRect(0, 0, s.width(), s.height(), 5, 5) qp.end() def closeEvent(self): self.kill() if __name__ == "__main__": QApp = QtGui.QApplication(sys.argv) window = Notifier() cross = CloseCrosss(QWidgetparent=window) window.show() cross.show() QApp.exec_()
type: Question
tagged with: pyqt
upvote count: 1
tagged with: pyqt4
answer count: 1
has comment: http://stackoverflow.com/comment/91236128
favorite count: 0
tagged with: qwidget
tagged with: qframe
accepted answer: http://stackoverflow.com/a/52143265
tagged with: python
type: AnsweredQuestion
has title: QFrame is not taking QWidget as parent?
downvote count: 0
has answer: http://stackoverflow.com/a/52143265
score: 1
has comment: http://stackoverflow.com/comment/91235780

http://stackoverflow.com/a/52177935
has comment: http://stackoverflow.com/comment/91318816
has comment: http://stackoverflow.com/comment/91376354
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52177889
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91318568
answers question: http://stackoverflow.com/q/52177889
has comment: http://stackoverflow.com/comment/91321559
has body: import YourProgram # this is the program you want to run, if the program runs automaticly when opened then move the import to the part where i wrote YourProgram() and delete the YourPregram() line import time pswd = "something" count = 0 with open("PhysxInit.txt","r") as file: file_info = file.readline() numa = file_info.count("1") count = numa while True: with open("PhysxInit.txt","r") as file: file_info = file.readline() tima = file.readline() inp = input("What is the password:") if inp == pswd: if tima == "": tima = "0" # this should solve yoúr problem with float convertion however it doesn't make sence that this step should be needed if str(file_info[:5]) != "11111" or time.time() &gt; float(tima): YourProgram() # this is just meant as the thing you want to do when when granted acces i magined you where blocking acces to a program. f = open("PhysxInit.txt", "w") f.write("\n") f.close() break else: count += 1 f = open("PhysxInit.txt", "w") f.write(("1"*count)+"\n"+str(tima)) if count == 5: f.write(str(time.time()+60*5)) f.close() #f = open("PhysxInit.txt", "w") #f.write("\n") #f.close() does this work? just make sure you have a text file called PhysxInit.txt after running the program, and having guessed wrong a few times my txt file look like this. 11111 1536328469.9134998 it should look something like mine though the numbers may be diffrent. To read a specific line as you requested you need to do: with open("PhysxInit.txt", "r") as f: for w,i in enumerate(f): if w == #the number line you want: # i is now the the line you want, this saves memory space if you open a big file
type: Answer
has comment: http://stackoverflow.com/comment/91309325
downvote count: 0
has comment: http://stackoverflow.com/comment/91317922
score: 2
has comment: http://stackoverflow.com/comment/91380978

http://stackoverflow.com/a/52246510
has comment: http://stackoverflow.com/comment/91441113
has comment: http://stackoverflow.com/comment/91441140
has comment: http://stackoverflow.com/comment/91441102
score: 0
has comment: http://stackoverflow.com/comment/91441206
type: Answer
answers question: http://stackoverflow.com/q/52246451
has comment: http://stackoverflow.com/comment/91450494
has body: tuple's can be indexed just like lists, so you can add the value for column one as get_data()[0] and for the second value in the second column you do get_data()[1] also you can do v1, v2 = get_data() and this way assign the returned tuple values to the variables v1 and v2. Take a look at this question here for further clarification.

azure-iot-hub
type: Tag
tags question: http://stackoverflow.com/q/52232205
tags question: http://stackoverflow.com/q/52201038
tag name: azure-iot-hub

http://stackoverflow.com/a/52190105
type: Answer
has body: You are incrementing x first. Try checking the value after calculating with power before entering the loop. Fixed your code. Added code to handle if you pass 0 as an argument n = int(input()) def function (n): x = 1 if not n: return 0 while n**x &lt; 500: y = n**x x += 1 return y print function (n)
answers question: http://stackoverflow.com/q/52189954
score: 0

http://stackoverflow.com/comment/91387756
score: 0
type: Comment
type: QuestionComment
has text: Does `contextlib redirect_stdout` work for you? In that case, this is a duplicate: https://stackoverflow.com/questions/6796492/temporarily-redirect-stdout-stderr
comment on: http://stackoverflow.com/q/52219393

http://stackoverflow.com/comment/91297762
has text: With a registry: The only less wasteful thing I can think of is when you let docker pull the latest version of your image before deleting the old one it will use its cache efficiently for the pulling process. Without a registry: The build cache of the image also makes the process more efficient without deleting the image before.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52172970

http://stackoverflow.com/comment/91260714
type: QuestionComment
comment on: http://stackoverflow.com/q/52149507
score: 0
has text: @newsha that does not work, I have tried it without positive results and getting same error message. However one_time_keyboard is an optional argument I can omit it. Omiting that argument also does not work.
type: Comment

plot
tags question: http://stackoverflow.com/q/52203512
tags question: http://stackoverflow.com/q/52213328
tags question: http://stackoverflow.com/q/52118110
tags question: http://stackoverflow.com/q/52153966
tags question: http://stackoverflow.com/q/52241417
tags question: http://stackoverflow.com/q/52138413
tags question: http://stackoverflow.com/q/52143951
tags question: http://stackoverflow.com/q/52223804
tags question: http://stackoverflow.com/q/52121577
tags question: http://stackoverflow.com/q/52218538
tags question: http://stackoverflow.com/q/52207583
tag name: plot
tags question: http://stackoverflow.com/q/52202538
tags question: http://stackoverflow.com/q/52257632
tags question: http://stackoverflow.com/q/52200823
tags question: http://stackoverflow.com/q/52227980
tags question: http://stackoverflow.com/q/52195354
tags question: http://stackoverflow.com/q/52140376
tags question: http://stackoverflow.com/q/52182322
tags question: http://stackoverflow.com/q/52149415
tags question: http://stackoverflow.com/q/52132970
type: Tag
tags question: http://stackoverflow.com/q/52187438
tags question: http://stackoverflow.com/q/52255416
tags question: http://stackoverflow.com/q/52191695
tags question: http://stackoverflow.com/q/52125211
tags question: http://stackoverflow.com/q/52185398
tags question: http://stackoverflow.com/q/52161219
tags question: http://stackoverflow.com/q/52139284
tags question: http://stackoverflow.com/q/52225713
tags question: http://stackoverflow.com/q/52132584
tags question: http://stackoverflow.com/q/52236169
tags question: http://stackoverflow.com/q/52229875
tags question: http://stackoverflow.com/q/52152833

http://stackoverflow.com/comment/91247164
type: AnswerComment
has text: @coder80 Indeed file must already exist while using `rb+`.
comment on: http://stackoverflow.com/a/52148623
type: Comment
score: 1

http://stackoverflow.com/q/52232548
has comment: http://stackoverflow.com/comment/91414385
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/52232657
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52236084
has body: I have written a code in Django like: phone = request.data.get("phone") password = request.data.get("password") age = request.data.get("age") name = request.data.get("name") if not phone or not password or not age or not name: #multiple not checks return Response({"status": False}) It takes multiple not checks, is here any way to write this in simpler way?
tagged with: django
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91414509
has answer: http://stackoverflow.com/a/52236084
type: Question
possible better answer: http://stackoverflow.com/a/52232657
answer count: 2
has title: How to simplify multiple condition in an if clause?
has comment: http://stackoverflow.com/comment/91414328
has comment: http://stackoverflow.com/comment/91414343

http://stackoverflow.com/a/52288598
accepted answer of: http://stackoverflow.com/q/52271243
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52271243
has body: After some research, I found that the issue came from the buffer. As indicated in the subprocess module documentation: This will deadlock when using stdout=PIPE or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use Popen.communicate() when using pipes to avoid that. There are two solutions: Use the bufsize argument to set the buffer to a size large enought to store all the output generated during the time you wait. Use readline() to read the output and flush the buffer during the waiting time. If you don't need it just discard the output. I choose the second approach ; my code is as follow: def connect(interface): stdout = [] timeout = 60 start_time = time.time() proc = subprocess.Popen(['mycommand', interface], stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1, universal_newlines=True) while time.time() &lt; start_time + timeout: line = proc.stdout.readline() stdout.append(line) proc.terminate() print(output)
type: Answer
score: 0

http://stackoverflow.com/q/52187248
tagged with: javascript
has title: selenium.common.exceptions.WebDriverException: Message: unknown error: 'script' must be a string while using execute_script() through Selenium Python
has comment: http://stackoverflow.com/comment/91324361
accepted answer: http://stackoverflow.com/a/52190604
has body: I've got an issue with browser.execute_script while using selenium with python. There is an element that i'd like to click (it's xpath below) "//*[@id='listFav_FI410_23244709400000_FAGNNURROR_IPOF_APP_P43070_W43070A_CP000A001_40']/table/tbody/tr/td[1]" I try to do it with: navMenu = browser.find_element_by_xpath("//*[@id='listFav_FI410_23244709400000_FAGNNURROR_IPOF_APP_P43070_W43070A_CP000A001_40']/table/tbody/tr/td[1]") time.sleep(3) browser.execute_script(navMenu.click()) And it works (So it clicks desired element) but right after doing it it throws an error that terminates the script: selenium.common.exceptions.WebDriverException: Message: unknown error: 'script' must be a string What am I doing wrong? Is there a way to skip this error? Thx for wasting your time on helping me :)
linked to: http://stackoverflow.com/q/49871432
answer count: 3
has comment: http://stackoverflow.com/comment/91324266
has comment: http://stackoverflow.com/comment/91324464
has answer: http://stackoverflow.com/a/52188343
has comment: http://stackoverflow.com/comment/91324343
has comment: http://stackoverflow.com/comment/91324321
linked to: http://stackoverflow.com/q/32046014
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/52187482
tagged with: selenium-webdriver
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52187482
has answer: http://stackoverflow.com/a/52190604
has comment: http://stackoverflow.com/comment/91324692
upvote count: 2
score: 1
tagged with: selenium
tagged with: webdriver
has comment: http://stackoverflow.com/comment/91324603
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91324377

dialogflow-es
tag name: dialogflow-es
tags question: http://stackoverflow.com/q/52263782
type: Tag
tags question: http://stackoverflow.com/q/52165360

http://stackoverflow.com/q/52153983
score: 0
tagged with: batch-processing
answer count: 1
tagged with: stochastic
has answer: http://stackoverflow.com/a/52161901
favorite count: 0
tagged with: gradient-descent
tagged with: python
type: AnsweredQuestion
has title: SGD implementation Python
accepted answer: http://stackoverflow.com/a/52161901
upvote count: 1
downvote count: 1
type: Question
has body: I am aware that SGD has been asked before on SO but I wanted to have an opinion on my code as below: import numpy as np import matplotlib.pyplot as plt # Generating data m,n = 10000,4 x = np.random.normal(loc=0,scale=1,size=(m,4)) theta_0 = 2 theta = np.append([],[1,0.5,0.25,0.125]).reshape(n,1) y = np.matmul(x,theta) + theta_0*np.ones(m).reshape((m,1)) + np.random.normal(loc=0,scale=0.25,size=(m,1)) # input features x0 = np.ones([m,1]) X = np.append(x0,x,axis=1) # defining the cost function def compute_cost(X,y,theta_GD): return np.sum(np.power(y-np.matmul(np.transpose(theta_GD),X),2))/2 # initializations theta_GD = np.append([theta_0],[theta]).reshape(n+1,1) alp = 1e-5 num_iterations = 10000 # Batch Sum def batch(i,j,theta_GD): batch_sum = 0 for k in range(i,i+9): batch_sum += float((y[k]-np.transpose(theta_GD).dot(X[k]))*X[k][j]) return batch_sum # Gradient Step def gradient_step(theta_current, X, y, alp,i): for j in range(0,n): theta_current[j]-= alp*batch(i,j,theta_current)/10 theta_updated = theta_current return theta_updated # gradient descent cost_vec = [] for i in range(num_iterations): cost_vec.append(compute_cost(X[i], y[i], theta_GD)) theta_GD = gradient_step(theta_GD, X, y, alp,i) plt.plot(cost_vec) plt.xlabel('iterations') plt.ylabel('cost') I was trying a mini-batch GD with a batch size of 10. I am getting extremely oscillatory behavior for the MSE. Where's the issue? Thanks. P.S. I was following NG's https://www.coursera.org/learn/machine-learning/lecture/9zJUs/mini-batch-gradient-descent

http://stackoverflow.com/q/52210916
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91371333
has comment: http://stackoverflow.com/comment/91371318
has comment: http://stackoverflow.com/comment/91371443
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/91371433
tagged with: python
has comment: http://stackoverflow.com/comment/91371263
has comment: http://stackoverflow.com/comment/91371385
tagged with: python-3.x
upvote count: 2
has body: How do I set up a if statement for multiple answers rather than conditions? So for my example, I want to say that if i equal 0, then a and b will have unique answers. df is a dataframe something like: 0 d 8 0 d 9 0 t 7 1 q 7 0 u 8 0 r 5 1 s 3 for c in range(len(df.index)): for i in df.ilocc,0]: if i == 0: a = 12 b = 'up' OUT.write('%i,%s,'%(a,b)) error is: NameError: name 'a' is not defined I have tried: for c in range(len(df.index)): for i in df.ilocc,0]: if i == 0: a = 12; b = 'up' and for c in range(len(df.index)): for i in df.ilocc,0]: if i == 0: a = 12 and b = 'up'
has comment: http://stackoverflow.com/comment/91371722
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52211327
downvote count: 2
has title: Multiple If-else statement results
type: Question
has comment: http://stackoverflow.com/comment/91371349
has comment: http://stackoverflow.com/comment/91371360
has comment: http://stackoverflow.com/comment/91371411
has answer: http://stackoverflow.com/a/52211154
has comment: http://stackoverflow.com/comment/91371328

http://stackoverflow.com/comment/137460552
score: 0
type: AnswerComment
has text: what about functions that don't have a return statement? i read you would use `def func() -> None` but `None` is not a type. It is an object and its type is `NoneType` so how come we don't do `def func() -> NoneType` ? EDIT: oh I found it https://stackoverflow.com/questions/36797282/python-void-return-type-annotation
type: Comment
comment on: http://stackoverflow.com/a/52264392

http://stackoverflow.com/q/52188770
has comment: http://stackoverflow.com/comment/91327284
linked to: http://stackoverflow.com/q/11112515
has title: How to automatically log user out when server is restarted?
has comment: http://stackoverflow.com/comment/91327560
duplicate of: http://stackoverflow.com/q/11112515
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91327632
answer count: 0
type: UnansweredQuestion
has body: Even when I restart my Django server, my user is logged in. Is there a quick way to log my user out automatically when I quit the server? I tried SESSION_EXPIRE_AT_BROWSER_CLOSE = True and it doesn't do anything Thanks!
tagged with: django
type: Question

http://stackoverflow.com/comment/125815707
has text: However within the `on_train_end` function in my callback, `self.model.history.history` is definitely filled
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52205351

http://stackoverflow.com/comment/91326448
comment on: http://stackoverflow.com/a/52180535
has text: Yes, actually it an sdk that i used, the `sf` should be the settings of the socket, so that i can get the server's `pickle.dumps` result.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52195065
has comment: http://stackoverflow.com/comment/91339958
type: Answer
answers question: http://stackoverflow.com/q/52195005
has comment: http://stackoverflow.com/comment/91339901
has comment: http://stackoverflow.com/comment/91339710
has comment: http://stackoverflow.com/comment/91340207
has body: Try this: s = 'us:0.9,can:1.2,mex:0.45' t = {k:float(v) for k, v in dict(x.split(':') for x in s.split(',')).items()} print(t) Output is: {'us': 0.9, 'can': 1.2, 'mex': 0.45}
score: 0

http://stackoverflow.com/comment/91403873
comment on: http://stackoverflow.com/q/52223722
type: Comment
type: QuestionComment
score: 0
has text: Please don't use comments to clarify, [edit] your question instead. Comments may or may not be shown initially. They do appear in order of votes. You also cannot format code properly in comments. Make it easy to help you by putting everything in one place --- the question.

http://stackoverflow.com/comment/130217619
type: Comment
has text: How does one display the left panel with "VARIABLES"?
comment on: http://stackoverflow.com/a/65883166
score: 0
type: AnswerComment

http://stackoverflow.com/a/62127015
answers question: http://stackoverflow.com/q/52177621
score: 1
upvote count: 1
has body: For read-only model you can use app django-readonly-model Install using pip: pip install django-readonly-model Add 'readonly_model' to your INSTALLED_APPS setting: INSTALLED_APPS = [ ... 'readonly_model', ] And just use: from django.db import models class Directory(models.Model): class Meta: read_only_model = True if you try to record something, you will get an exception: &gt;&gt;&gt; Directory.objects.create(name='kg') ... readonly_model.exceptions.ReadOnlyModel: Model 'app.models.Directory' is read-only
type: Answer
downvote count: 0

http://stackoverflow.com/q/52166170
has title: Is there an F# equivalent to Python's Counter collection?
downvote count: 0
accepted answer: http://stackoverflow.com/a/52167264
has comment: http://stackoverflow.com/comment/91283309
tagged with: f#
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52167264
has body: Looking to port some Python code to F#. I'm new to both languages. The Python code uses the "Counter" collection "where elements are stored as dictionary keys and their counts are stored as dictionary values". In Python for example: cnt = Counter() for word in ['red', 'blue', 'red', 'green', 'blue', 'blue'] cnt[word] += 1 cnt Counter({'blue': 3, 'red': 2, 'green': 1}) &gt;&gt; # Tally occurrences of words in a list &gt;&gt; cnt = Counter() &gt;&gt; for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: &gt;&gt; ... cnt[word] += 1 &gt;&gt; cnt &gt;&gt; Counter({'blue': 3, 'red': 2, 'green': 1}) Is there an F# equivalent to Python's Counter collection?
type: Question
answer count: 1
tagged with: counter
has comment: http://stackoverflow.com/comment/91283216
upvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/91283698
has comment: http://stackoverflow.com/comment/91281986
favorite count: 0

http://stackoverflow.com/a/52245884
has body: I was able to move past this issue by using the DOS console (i.e. cmd.exe) for this instead. If anyone can comment as to why this authentication step doesn't work as expected in the git/bash console for Windows then please chime in, as I'd like to fix that (hopefully a config setting?) so I don't have to move over to DOS for this step in my workflow.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52229497
downvote count: 0
answers question: http://stackoverflow.com/q/52229497
type: Answer
score: 3
upvote count: 3

data-visualization
tags question: http://stackoverflow.com/q/52202014
tags question: http://stackoverflow.com/q/52170069
tags question: http://stackoverflow.com/q/52189613
tag name: data-visualization
tags question: http://stackoverflow.com/q/52143951
tags question: http://stackoverflow.com/q/52162387
tags question: http://stackoverflow.com/q/52234914
type: Tag

http://stackoverflow.com/comment/91292461
comment on: http://stackoverflow.com/q/52170877
score: 0
type: Comment
has text: why don't you use the builtin selenium methods to get the element `FPmhX notranslate zsYNt`?
type: QuestionComment

http://stackoverflow.com/a/52152936
answers question: http://stackoverflow.com/q/52152067
has body: Solved You can sort your index, then get back the values as an array and slice that and place it into a .loc slicer. Below is a working example: def get_slice(slicer, df): vals = df.index.levels[0][-slicer:] return df.loc[pd.IndexSlice[vals,:], :].copy() This will slice the first index by n (starting at the end) giving you back concrete values in an array, which you can then feed into .loc which will take an array of values.
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/52152067
type: AcceptedAnswer

http://stackoverflow.com/q/52217603
has answer: http://stackoverflow.com/a/52217710
has answer: http://stackoverflow.com/a/52218150
score: 0
answer count: 2
has title: Create constant or tensor without knowing shape upfront in Keras/TF?
tagged with: keras
type: UnansweredQuestion
has body: I am working on a custom method to categorize text documents. Each document has shape (None, 3) where None represents the number of tokens in the document and it's variable. Each batch is then going to have shape (None, None, 3), where the first value represents the batch_size. In one of my custom layer, I need to create a square matrix of 0s of size equals to the number of tokens for that document. The issue is, when the graph is instantiated, I have no idea what number this is going to be. In fact, this number is likely different for each document. To make things even more difficult, this operation is done as part of K.map_fn(), which makes it impossible to create new tensors. K.constant would work just great if I knew the number of tokens beforehand (assuming it was also the same for all documents). Ideas?
tagged with: python
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/52228525
has answer: http://stackoverflow.com/a/52228571
tagged with: uppercase
downvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/52228619
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/52228779
tagged with: list
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52228619
has body: Out of a string like this "A B c de F G A" I would like to get the following list: ["A B", "F G A"]. That means, I need to get all the sequences of uppercase words. I tried something like this: text = "A B c de F G A" result = [] for i, word in enumerate(text.split()): if word[0].isupper(): s = "" while word[0].isupper(): s += word i += 1 word = text[i] result.append(s) But it produces a the following output: ['A', 'BB', 'F', 'G', 'A'] I suppose it happens because you can't skip a list element by just incrementing i. How can I avoid this situation and get the right output?
type: Question
accepted answer: http://stackoverflow.com/a/52228571
tagged with: string
has title: Extracting all uppercase words following each other from string
has answer: http://stackoverflow.com/a/52228898
score: 0
upvote count: 1

importerror
tags question: http://stackoverflow.com/q/52113158
tags question: http://stackoverflow.com/q/52157214
tags question: http://stackoverflow.com/q/52239111
type: Tag
tags question: http://stackoverflow.com/q/52136349
tag name: importerror
tags question: http://stackoverflow.com/q/52246748

http://stackoverflow.com/q/52168784
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52168841
tagged with: unit-testing
type: Question
upvote count: 4
tagged with: testing
answer count: 2
has title: How to test for order of superclass in python?
downvote count: 0
score: 4
has body: Giving following code: class X(Mixin, Y): pass How can I write a unittest to ensure Mixin class is before Y in superclass declaration of X?
has answer: http://stackoverflow.com/a/52169149
has comment: http://stackoverflow.com/comment/91289897
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91288420

http://stackoverflow.com/q/52246079
answer count: 1
tagged with: tuples
tagged with: python
has answer: http://stackoverflow.com/a/52246100
type: AnsweredQuestion
has body: I have a recursive function that moves through a binary tree and calculates the difference between the most left node and the most right one. It does this by taking an argument "count" that is count-1 if I navigate to the left child and count+1 if I go to the right one. It returns a tuple (countsx, countdx) where countsx (countdx) is the minimum (maximum) between the current count variable (for both countsx and countdx), the countsx (countdx) value returned by the left child and che countsx (countdx) value returned from the right child. This is the code. It raises an error "Int type is not iterable" on the marked line at the beginning of the recursion. def ausilioes17(tree, count): countsx = 0 countdx = 0 # If it's a leaf, just return the count parameter if not tree.sx and not tree.dx: return count if tree.sx: # it raises an error here when unpacking countsx, dummydx = ausilioes17(tree.sx, count-1) # &lt;------- if tree.dx: dummysx, countdx = ausilioes17(tree.dx, count+1) return min(countsx, dummysx, count), max(countdx, dummydx, count) if __name__ == "__main__": a = Tree() # has just left child (a.sx) and right child (a.dx) sx, dx = ausilioes17(a, 0) print(str(dx-sx))
type: Question
tagged with: recursion
has title: Python "Int object is not iterable" during variable unpacking in a recursive function
accepted answer: http://stackoverflow.com/a/52246100
score: 0

http://stackoverflow.com/comment/91469818
score: 0
type: Comment
type: QuestionComment
has text: https://docs.python.org/3/library/difflib.html This can be useful
comment on: http://stackoverflow.com/q/52261100

http://stackoverflow.com/a/52240591
score: 0
has body: OR the below, (will do the last element of any length sequence): &gt;&gt;&gt; list = [[100,200],[300,400]] &gt;&gt;&gt; list[-1][-1]=500 &gt;&gt;&gt; list [[100,200],[300,500]] By the way, also see this image: Also see: +---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 -6 -5 -4 -3 -2 -1
answers question: http://stackoverflow.com/q/52240500
type: Answer
has comment: http://stackoverflow.com/comment/91430176

http://stackoverflow.com/comment/91483919
type: Comment
type: QuestionComment
has text: Basically, I don't understand how to give the labels different names, or any name that'd different from self.label. If someone has any kind of easy explanation or tutorial on it, that would be great.
score: 0
comment on: http://stackoverflow.com/q/52267945

http://stackoverflow.com/a/52268166
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52267704
upvote count: 1
downvote count: 0
has body: Another way to describe your condition is: "Break everything up into chunks of three. If the last chunk has one element, grab one off the chunk before". textwrap.wrap provides a nice tool for breaking the strings up: from textwrap import wrap pieces = wrap(S, 3) if len(pieces[-1]) == 1: pieces [-2:] = pieces[-2][:-1], pieces[-2][-1] + pieces[-1] result = '-'.join(pieces)

distutils
tags question: http://stackoverflow.com/q/52213151
type: Tag
tag name: distutils
tags question: http://stackoverflow.com/q/52124767

http://stackoverflow.com/comment/91324796
has text: I can't believe this. And I thought I had double checked everything! Thank you so much!
comment on: http://stackoverflow.com/a/52178842
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91444038
type: Comment
has text: see also https://stackoverflow.com/a/40962714/1138523
comment on: http://stackoverflow.com/q/52246451
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91409942
score: 2
comment on: http://stackoverflow.com/q/52230037
type: Comment
type: QuestionComment
has text: I think your `_time` is Unixepoch (seconds since 1970-01-01), so try `_time > strftime('%s',DATE('now', '-5 day'))`.

http://stackoverflow.com/comment/91344719
comment on: http://stackoverflow.com/q/52197741
has text: Which backend are you using? Tensorflow? And can you post relevant code where you create that Tensor?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91236729
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52119326
has text: @user1643723 I have edited the question. I think i am using inotifywatch

http://stackoverflow.com/a/52243291
has body: Your check is incorrect, str is an object of class type which can create instances of class str the correct check is: myVar = str('some-string') if isinstance(myVar,str): print('this is a string') else: print('this is NOT a string') The same way given class A this check: if x is A is incorrect Defining a class creates a special object of class type that is responsible for creating instances of the defined class that is why you need to use isinstace() or issubclass() which uses this special object and the object given to answer the query. Because simple is checks if object x is object A and that is not true.
score: 0
answers question: http://stackoverflow.com/q/52243247
type: Answer
has comment: http://stackoverflow.com/comment/91434921

http://stackoverflow.com/a/52122693
has body: IIUC If you want a function that prints just gibberish1, then you can do the following: def gib(): print('gibberish1') Then if you type gib() it'll print what you're looking for. If you want a function that prints a 2, you do basically the same: def two(): print(2) If you want a function that concatenates both you need your number to be a string. def gib2(): var1='gibberish1' var2='2' print(var1+var2)
answers question: http://stackoverflow.com/q/52122645
type: Answer
score: 0

http://stackoverflow.com/comment/91335645
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52192840
has text: I am getting KeyError: 'Project' when I run this. What could cause this?
type: AnswerComment

http://stackoverflow.com/a/52153854
has body: The referenced pytest-selenium issue has: @pytest.fixture def firefox_options(firefox_options, pytestconfig): if pytestconfig.getoption('headless'): firefox_options.add_argument('-headless') return firefox_options Note the - (single dash) preceding headless in add_argument() (Source)
downvote count: 0
has comment: http://stackoverflow.com/comment/91261219
type: Answer
answers question: http://stackoverflow.com/q/52153076
upvote count: 1
score: 1

task
type: Tag
tags question: http://stackoverflow.com/q/52252031
tag name: task

http://stackoverflow.com/comment/91387211
score: 0
comment on: http://stackoverflow.com/a/52209361
type: AnswerComment
has text: time.sleep() is extreme case of webdriverwait. You can refer this link https://selenium-python.readthedocs.io/waits.html for more details.
type: Comment

http://stackoverflow.com/q/52162064
tagged with: view
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52179831
has title: Django add dropdown filter for a view with no class / model
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/91274321
tagged with: dropdown
score: 0
tagged with: filter
has body: I have a method mapped to a url in urls.py: urlpatterns = [ url(r'^mydir/statistics', statistics_view, name="Statistics") ] Then in mydir/statistics/views.py I have the method: def statistics_view(request): list_mystuff = Mytable.objects.all() #Mytable is defined in models .... #lots of code here to assign "enriched_models" data structure enriched_models = {bunch of stuff} ...... return render(request, 'statistics.html', {"statistics_enriched_models": enriched_models}) It all works fine and everything is rendered in using statistics.html template. Now I need to implement a dropdown filter by one of the fields of Mytable. With classes I would have to create class for Statistics in models.py, StatisticsAdmin as a proxy model in admin.py, register them both, and have list_filter=["myfield",] set in StatisticsAdmin Is there a way to set up a dropdown filter (with list_filters or whatever) and have the dropdown rendered directly without creating the classes, just with what I already have (a method that populates the template)?
has comment: http://stackoverflow.com/comment/91274898

http://stackoverflow.com/a/52144797
type: Answer
upvote count: 3
has body: sleep will never be more accurate than the operating system's tick rate, for windows it's somewhere in the 10ms-16ms range , and in linux it can be as low as 1ms depending on the OS but typically it will be higher like windows if you want a higher precision sleep and if you're on linux you can consider using nanosleep() which is a high precision sleep function that unfortunately isn't exposed by python in any built in library - so you will need to create a small .so file which exposes it to python (either by importing it as is with ctypes or by making a C python module with cpython) this function according to the docs will be as precise as the timer itself can be there are also high precision solutions for windows - but i never used any of them so i'm not qualified to recommend what to use on windows (but again you will need a .dll that exposes such methods to python) with all that said if you dont care about power usage you can just do a busy sleep: import time def busy_sleep(seconds_to_sleep): start = time.time() while (time.time() &lt; start + seconds_to_sleep): pass then you can call it like this busy_sleep(0.005) and it will "sleep" almost exactly 0.005 seconds "sleep" is in air quotes since you aren't really sleeping you're keeping the cpu busy all this time at 100% but if what's important for you is to delay execution in a precise manner it could still work for you
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52144249
answers question: http://stackoverflow.com/q/52144249
score: 3

http://stackoverflow.com/q/52181407
has comment: http://stackoverflow.com/comment/91312910
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91312870
tagged with: list
type: Question
has title: Number of preceeding words before a phrase in a string
has comment: http://stackoverflow.com/comment/91312872
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52181579
has answer: http://stackoverflow.com/a/52182115
has answer: http://stackoverflow.com/a/52181524
has body: Assuming I have a list of phrases: list = ['new york', 'school', 'new'] and a string text = 'i am going to a school in new york and therefore i have to buy a new uniform to go to new york' I would like to find the number of words preceeding each phrase (just for first appearance) ie output should be: new york = 7 school = 5 new = 7 Any idea how I can effectively achieve this?
has comment: http://stackoverflow.com/comment/91312785

http://stackoverflow.com/q/52165717
tagged with: web-scraping
tagged with: python
has title: web scraping python multiple attributes in line (div and id)
score: -1
downvote count: 1
type: Question
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52165792
tagged with: class
tagged with: http://stackoverflow.com/tag/html
tagged with: attributes
favorite count: 0
has body: I would like to webscrape this page. So, I started with this script: import requests from bs4 import BeautifulSoup import numpy as np import pandas as pd import matplotlib.pyplot as plt links = {"Copa do Brasil": "http://www.oddsportal.com/soccer/brazil/copa-do- brasil/results/"} headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'} data = [] for club, link in links.items(): response = requests.get(link, headers = headers) #print(response.status_code) #200 is OK soup = BeautifulSoup(response.text, 'lxml') #print(soup.prettify()) #to check if soup downloads correctly. table = soup.find_all('div', attrs ={'id', 'tournamentTable'}) print(table) The problem is in the following lines when inspecting the html code: &lt;div id="tournamentTable" style = "display: block;"&gt; &lt;table class =" table-main" id="tournamentTable"&gt; &lt;/table&gt; ==$0 I am wondering, what I should do, to get the table of all matches. I got stuck in the fact that class, id and style are used together.
type: UnansweredQuestion

http://stackoverflow.com/q/52257843
has comment: http://stackoverflow.com/comment/91462934
has answer: http://stackoverflow.com/a/52257948
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Python selenium webscraping
downvote count: 1
has comment: http://stackoverflow.com/comment/91462891
tagged with: selenium
score: -1
has answer: http://stackoverflow.com/a/52263262
type: Question
has comment: http://stackoverflow.com/comment/91464504
answer count: 2
has body: 68.40 -19.81 -2.59 Hi I am trying to get the values 68.40, -19.81 and -2.59 within the code using python selenium. However, when I use css_selector I keep getting error. Can someone give me the correct code to locate and produce the values without calling the value itself. Thanks alot!
upvote count: 0

dicom
tag name: dicom
type: Tag
tags question: http://stackoverflow.com/q/52144073

http://stackoverflow.com/a/52145908
answers question: http://stackoverflow.com/q/52145803
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91243158
score: 0
type: Answer
has body: min(a+b) add the two arrays and use the min function to find the min

http://stackoverflow.com/comment/91332380
type: Comment
comment on: http://stackoverflow.com/a/52190072
has text: to clarify, I know you can use os.system() to run terminal commands but how would I access the received message on the pi in python?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91204320
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52119281
has text: Thank you for the anser! Can you please explain, what your regex code does?
type: AnswerComment

http://stackoverflow.com/comment/91399996
has text: Thanks, I got it working. I actually removed the `fouts` list entirely and just created file handles inside the processes. But why do I have to lock the `proc_id` variable? When I'm creating a file handle, like `openfile`, shouldn't it be separated from other 3 instances/processes since each one is opening different files?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52225133
score: 0

http://stackoverflow.com/q/52123667
favorite count: 0
has answer: http://stackoverflow.com/a/52123857
type: UnansweredQuestion
tagged with: python
upvote count: 1
has comment: http://stackoverflow.com/comment/91198910
has body: I am trying to use VSCode with Python 3.6 on an Ubuntu 18.04 system. I wrote a "hello world" program. msg = "Hello World" print(msg) If I highlight it and press shift+enter it runs without problem, but, if I right-click and select to execute the file in a terminal I get this error message. &gt;&gt;&gt; /usr/bin/python3.6 /home/nuria/hello/hello.py File "&lt;stdin&gt;", line 1 /usr/bin/python3.6 /home/nuria/hello/hello.py ^ SyntaxError: invalid syntax &gt;&gt;&gt; I really don't know how to fix it. Please help!
downvote count: 1
type: Question
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/91198934
score: 0
answer count: 1
has title: VSCode on Ubuntu 18.04 cannot run a Python program

http://stackoverflow.com/a/52226158
downvote count: 0
has comment: http://stackoverflow.com/comment/91402578
type: Answer
has body: You were close, just missing a few brackets. For a matrix you need to give np.array a list of lists. In [4]: import numpy as np ...: ...: A = np.array([[1,2,3,1],[3,1,5,1]]) ...: B = np.array([[1,6,8,9],[9,2,7,1]]) ...: E = np.array([[A, B],[B, A]], dtype=int) ...: In [5]: E Out[5]: array([[[[1, 2, 3, 1], [3, 1, 5, 1]], [[1, 6, 8, 9], [9, 2, 7, 1]]], [[[1, 6, 8, 9], [9, 2, 7, 1]], [[1, 2, 3, 1], [3, 1, 5, 1]]]])
has comment: http://stackoverflow.com/comment/91402668
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52226079

http://stackoverflow.com/comment/91415442
type: Comment
type: QuestionComment
has text: That the number 10 exists in the array. I want all the rows that have a specific number the array.
comment on: http://stackoverflow.com/q/52233115
score: 0

http://stackoverflow.com/comment/91487832
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52251228
has text: @Meekao You can edit your original post to include the beginning of snippet 10 in the question (see the grey "edit" link below the text).
score: 0

http://stackoverflow.com/q/52134226
tagged with: text-mining
favorite count: 0
has comment: http://stackoverflow.com/comment/91226994
type: Question
tagged with: python
tagged with: nlp
has comment: http://stackoverflow.com/comment/91279623
score: 0
upvote count: 1
downvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/34784004
has comment: http://stackoverflow.com/comment/91218687
has answer: http://stackoverflow.com/a/52165363
type: UnansweredQuestion
has body: I am new to the text mining. I have a CSV file. I need to go through each line and extract some information then write them into another CSV file. I am looking for specific information which I have in a dictionary. Consider below sentence: "the application version is 1.8.2 and the variable skt.len passes the required information. file ReadMe.txt has the specifications." My dictionary is: ["application version", "variable", "file"] I need to extract: application version: 1.8.2 variable: skt.len file: ReadMe.txt What is the best way to extract such information from text? I am playing with NLTK and StanfordCoreNLP features. But, I could not extract the information yet. I am thinking to use regex to extract the application version. Any idea? PS: I know that this may make the task more complicated. But, sentences in each line of the CSV file may have different structures. For example: "application version" in one line, may be "app version" in another line. Or "file" in one line may be "filename" in another line.
has comment: http://stackoverflow.com/comment/91218742
tagged with: information-extraction
tagged with: nltk
has comment: http://stackoverflow.com/comment/91227122
has title: Extracting information from text in python

http://stackoverflow.com/comment/91456780
comment on: http://stackoverflow.com/q/52252580
type: Comment
type: QuestionComment
score: 0
has text: Would the solution not simply be `print ('ExternalImageId:' + match['Face']['ExternalImageId'])` inside the `for match` loop?

jinja2
tags question: http://stackoverflow.com/q/52149263
tags question: http://stackoverflow.com/q/52122949
tags question: http://stackoverflow.com/q/52174695
tags question: http://stackoverflow.com/q/52167300
tags question: http://stackoverflow.com/q/52225930
tags question: http://stackoverflow.com/q/52123103
tags question: http://stackoverflow.com/q/52256428
type: Tag
tags question: http://stackoverflow.com/q/52226293
tags question: http://stackoverflow.com/q/52240065
tags question: http://stackoverflow.com/q/52230088
tags question: http://stackoverflow.com/q/52229486
tags question: http://stackoverflow.com/q/52250516
tags question: http://stackoverflow.com/q/52261183
tags question: http://stackoverflow.com/q/52178795
tag name: jinja2
tags question: http://stackoverflow.com/q/52235577

http://stackoverflow.com/comment/91381499
type: Comment
comment on: http://stackoverflow.com/a/52212640
has text: Maybe an older library on my part, but make sure foo does what it is intended for. Writing a good, focused question is hard - a good check for it is looking from outsider lens, and also allowing other people to replicate the problem by running code. Please,accept the answer if it suits.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91408388
has text: Well I will add two new tables. Pseudo schemas: tblname - skilltracker, id and userid as foreign key of the users id, time the form submitted in time.time, then we decide the time to multiply by as in level 6 upgrade is 120 seconds multiplied by 6 = 720 seconds so we set that in a column, and also add it to the previous time for comparison and conversion in antoher column, last we have active or inactive boolean column. we have two processes, one which handles time comparisons. the other cleans the "pending" table and moves them to the history table.
comment on: http://stackoverflow.com/a/52216293
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52179821
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91312153
tagged with: python
has body: My code currently consists of loading the image, which is successful and I don't believe has any connection to the problem. Then I go on to transform the color image into a np.array named rgb # convert image into array rgb = np.array(img) red = rgb[:,:,0] green = rgb[:,:,1] blue = rgb[:,:,2] To double check my understanding of this array, in case that may be the root of the issue, it is an array such that rgb[x-coordinate, y-coordinate, color band] which holds the value between 0-255 of either red, green or blue. Then, my idea was to make a nested for loop to traverse all pixels of my image (620px,400px) and sort them based on the ratio of green to blue and red in an attempt to single out the greener pixels and set all others to black or 0. for i in range(xsize): for j in range(ysize): color = rgb[i,j] &lt;-- Index error occurs here if(color[0] &gt; 128): if(color[1] &lt; 128): if(color[2] &gt; 128): rgb[i,j] = [0,0,0] The error I am receiving when trying to run this is as follows: IndexError: index 400 is out of bounds for axis 0 with size 400 I thought it may have something to do with the bounds I was giving i and j so I tried only sorting through a small inner portion of the image but still got the same error. At this point I am lost as to what is even the root of the error let alone even the solution.
has comment: http://stackoverflow.com/comment/91310019
type: Question
has comment: http://stackoverflow.com/comment/91314810
tagged with: arrays
has title: Python 3: I am trying to find find all green pixels in an image by traversing all pixels using an np.array, but can't get around index error
score: 4
tagged with: rgb
tagged with: image
has answer: http://stackoverflow.com/a/52183666
upvote count: 4
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91312307

http://stackoverflow.com/q/52225520
accepted answer: http://stackoverflow.com/a/52225720
answer count: 3
has comment: http://stackoverflow.com/comment/91400343
has answer: http://stackoverflow.com/a/52225847
has comment: http://stackoverflow.com/comment/91400363
possible better answer: http://stackoverflow.com/a/52225768
favorite count: 0
has answer: http://stackoverflow.com/a/52225768
tagged with: python-3.x
has title: Get all of the possible products from a list of numbers
tagged with: python
has answer: http://stackoverflow.com/a/52225720
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91400406
downvote count: 3
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91400313
score: -2
has body: The problem is indexing. I've tried this code snippet: for i in range(2,len(the_list_im_getting_values_from)): for j in range(0,i+1): index[j] = j for k in range(0,len(index)): the_output_list.append(the_list_im_getting_values_from[index[k]]*the_list_im_getting_values_from[index[k+1]]) k += 1 , but it totally didn't work. How to solve this problem? Example input: array of 3, 4 and 7 Example output: [12,21,28,84] Processing stages: 3*4=12 3*7=21 4*7=28 3*4*7=84 [12,21,28,84]

http://stackoverflow.com/q/52144109
tagged with: pycharm
tagged with: pytorch
has comment: http://stackoverflow.com/comment/91237924
accepted answer: http://stackoverflow.com/a/52144227
type: Question
has body: I'm trying to install pytorch, but when I'm trying to import, my pycharm doesn't recognize this package although I'm sure I've installed this package on the same interpreter. What I am missing?! Thanks for your help.
tagged with: intellij-idea
has comment: http://stackoverflow.com/comment/91238262
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52144227
tagged with: python
type: AnsweredQuestion
has title: Installing packages but still python interpreter doesn't recognize using pycharm

http://stackoverflow.com/comment/91505714
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52268312
type: Comment
has text: What are you trying to parse? I don't think `str(record)` will give you anything useful - is your input data in a field in the record?

http://stackoverflow.com/q/52170785
has comment: http://stackoverflow.com/comment/91292224
has title: How can I generate random numbers and store them in a random amount of re-callable variables?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91292242
linked to: http://stackoverflow.com/q/51887012
has comment: http://stackoverflow.com/comment/91292217
tagged with: random
duplicate of: http://stackoverflow.com/q/51887012
has comment: http://stackoverflow.com/comment/91292387
type: Question
tagged with: minimum
has comment: http://stackoverflow.com/comment/91292284
tagged with: python
tagged with: numbers
has comment: http://stackoverflow.com/comment/91292385
score: 0
has body: So, I am trying to write a program that outputs (prints) a random number between (x = 1-1000) a random amount of times between (n = 1-10) and stores those numbers in the same random number (n) of re-callable variables. That way I can output(print) the smallest number (min) of the (x) random numbers. Here's my code so far: from random import randint for x in range (10): x = randint (1,1000) for n in range (10): n = randint (1,10) while n &gt; 0: print(x) num(n) = x for x in range (10): x = randint (1,1000) n = n - 1 def num_low(): min[num(n)] print('lowest number is', num_low()) As you can see, I am trying to put them into a variable by the name num(n) where (n) is the randomly generated (1-10) number so that you end up with num 1, num 2, num 3,.....num (n) etc. That way you have all the required variables and as the while loop continues it should change the name of the variable to a different name automatically. Then once they are all stored I can recall them for a min check and output the minimum variable.
answer count: 1
has answer: http://stackoverflow.com/a/52170898
has comment: http://stackoverflow.com/comment/91292256

http://stackoverflow.com/q/52147060
has comment: http://stackoverflow.com/comment/91243922
upvote count: 4
tagged with: cell
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91244885
tagged with: textbox
favorite count: 0
has comment: http://stackoverflow.com/comment/91245435
has comment: http://stackoverflow.com/comment/91244646
tagged with: python
has answer: http://stackoverflow.com/a/55831711
has comment: http://stackoverflow.com/comment/91244692
type: UnansweredQuestion
tagged with: styles
has comment: http://stackoverflow.com/comment/91245132
type: Question
has comment: http://stackoverflow.com/comment/91245480
has title: Dataframe styling through Python
has answer: http://stackoverflow.com/a/67631697
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91244072
has comment: http://stackoverflow.com/comment/91244107
has comment: http://stackoverflow.com/comment/91245157
score: 4
has body: I am trying to send outlook mail via python. I import some data from excel files using dataframe and after some filtering I send them where the body of the mail is: body = '&lt;html&gt;&lt;body&gt;'+df.to_html()+'&lt;/body&gt;&lt;/html&gt;' I get a table but the cells are not aligned.I can not use justify='left/write' as I want the cells to be center aligned,not just the column headers. I have used styles but it did not work either: df.style.set_properties(subset=df.columns,**{'width':'10em', 'text-align':'center'})\ I tried this too and it did not work. p=HTML(df.to_html(classes= 'table text-align:center')) After surfing through similar problems I found another solution: s = df.style.set_properties(**{'text-align': 'center'}) s.render() However it makes the border of the table disappear.So I modified it: s = df.style.set_properties(**{'text-align': 'center','border-color':'Black','border-width':'thin','border-style':'dotted'}) This gives border to the cells. But it looks like each cell is inside individual textbox,not like a table. How do I get this done? The final result looks like this:

http://stackoverflow.com/q/52145649
tagged with: python
has title: how to restore a splitted word by removing the hyphen "-" because of hyphenation in a paragraph using python
score: 2
has comment: http://stackoverflow.com/comment/91241069
has answer: http://stackoverflow.com/a/52146189
type: Question
has comment: http://stackoverflow.com/comment/91241860
has comment: http://stackoverflow.com/comment/91241400
has comment: http://stackoverflow.com/comment/91241012
has comment: http://stackoverflow.com/comment/91247678
linked to: http://stackoverflow.com/q/3788870
has body: simple example: func-tional --> functional The story is that I got a Microsoft Word document, which is converted from PDF format, and some words remain hyphenated (such as func-tional, broken because of line break in PDF). I want to recover those broken words while normal ones(i.e., "-" is not for word-break) are kept. In order to make it more clear, one long example (source text) is added: After the symposium, the Foundation and the FCF steering team continued their work and created the Func-tional Check Flight Compendium. This compendium contains information that can be used to reduce the risk of functional check flights. The information contained in the guidance document is generic, and may need to be adjusted to apply to your specific aircraft. If there are questions on any of the information in the compendi-um, contact your manufacturer for further guidance. Could someone give me some suggestions on this problem?
answer count: 1
has comment: http://stackoverflow.com/comment/91247995
downvote count: 0
has comment: http://stackoverflow.com/comment/91242601
tagged with: word-processor
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91241077
has comment: http://stackoverflow.com/comment/91242771
has comment: http://stackoverflow.com/comment/91242504

http://stackoverflow.com/q/52216446
score: 2
downvote count: 0
type: UnansweredQuestion
tagged with: scrapy
has body: In scrapyrt's POST documentation we can pass a JSON request like this, but how do you access the meta data like category and item in start_requests? { "request": { "meta": { "category": "some category", "item": { "discovery_item_id": "999" } }, , "start_requests": true }, "spider_name": "target.com_products" } Reference: https://scrapyrt.readthedocs.io/en/latest/api.html#id1
type: Question
has comment: http://stackoverflow.com/comment/92933557
has title: How to get scrapyrt's POST meta data?
tagged with: web-crawler
upvote count: 2
answer count: 2
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/76404017
has answer: http://stackoverflow.com/a/53023173

http://stackoverflow.com/a/52148664
answers question: http://stackoverflow.com/q/52148632
has body: Use: m1 = data['CityID'] == 1 m2 = data['CityID'].isin([2, 3, 4, 21]) m3 = data['CityID'].isin([33, 34]) data['CityID'] = np.select([m1, m2, m3], [1,2,4], default=3)
downvote count: 0
type: Answer
upvote count: 4
score: 4

http://stackoverflow.com/comment/91278150
type: QuestionComment
comment on: http://stackoverflow.com/q/52162711
has text: I wounder if @un33k can give a clarification for this :)
score: 0
type: Comment

http://stackoverflow.com/a/52195091
type: Answer
downvote count: 1
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/52194927
has body: This code prints what you requested :) list = [4,8,15] for i in range(len(list)): for j in range (len(list)): for k in range (len(list)): print ("("+str(list[i]) +","+str(list[j])+","+str(list[k])+")\n")

http://stackoverflow.com/comment/91320682
comment on: http://stackoverflow.com/a/52183777
score: 0
type: AnswerComment
has text: Hey. It worked. but I need the data in same Excel file in different sheet. How can I do that ??
type: Comment

http://stackoverflow.com/comment/91450361
comment on: http://stackoverflow.com/q/52250960
score: 0
type: Comment
type: QuestionComment
has text: @Onyambu. sure he did: https://stackoverflow.com/questions/52250960/turning-a-recursive-function-into-an-iterative-function#comment91449674_52250960

http://stackoverflow.com/q/52267712
has body: I have a series of strings in the follow pattern: string = 'ABCD 1NAME 123456'. I need to extract the last digits in order to make an ID. I tried to use the isdigit method, but the problem is that it also returns the digit before the Name. Caveats: Sometimes the name doesn't come with the digit. len from last digits ranges from 5 to 9. Could anyone suggest to me an alternative? I think that I need to test if the the previous position or next position are digits in order to extract the id, but I cant figure out how to implement this test.
has answer: http://stackoverflow.com/a/52267779
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52267781
has answer: http://stackoverflow.com/a/52267727
has title: Python - How extract specific numbers from strings?
has answer: http://stackoverflow.com/a/52267776
type: Question
has answer: http://stackoverflow.com/a/52267934
answer count: 6
has answer: http://stackoverflow.com/a/52268005
score: 0

http://stackoverflow.com/comment/91208046
has text: what's the use of `[0]` at the end of `extract`?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52128773

http://stackoverflow.com/a/52140159
downvote count: 0
answers question: http://stackoverflow.com/q/52139796
type: Answer
has body: how can I send some data on some external event occurs? The easiest way is to spawn the coroutine in connection_made and leave it to handle the event in the "background": def connection_made(self, transport): self.transport = transport loop = asyncio.get_event_loop() self._interesting_events = asyncio.Queue() self.monitor = loop.create_task(self._monitor_impl()) def connection_lost(self, exc): self.exit_future.set_result(True) self.monitor.cancel() async def _monitor_impl(self): while True: # this can also await asyncio.sleep() or whatever is needed event = await self._interesting_events.get() self.transport.write(...) Note that in the long run it might be worth it to replace create_connection with open_connection and use the streams API from the ground up. That way you can use coroutines all the way without worrying about the callback/coroutine impedance mismatch. On an unrelated note, try followed by except: pass is an anti-pattern - consider catching a specific exception instead, or at least logging the exception.
upvote count: 1
score: 1

http://stackoverflow.com/q/52195727
type: UnansweredQuestion
tagged with: python
tagged with: voice-recognition
has answer: http://stackoverflow.com/a/52196659
upvote count: 1
has comment: http://stackoverflow.com/comment/91342279
type: Question
tagged with: cmusphinx
has title: Voice recognition program works sporadically
downvote count: 0
answer count: 1
tagged with: voice
score: 1
has body: I am not sure why but it only finds, converts and transcribes all of the mp3 files in the directory occasionally but never 100 percent of the time. I am not sure why. I hope I am asking in the right place. My goal is to find all m4a files and then convert to wav files and then find all wav files and transcribe them. The program does this some of the time but not all of the time. #!/usr/bin/env python3 import speech_recognition as sr import time import subprocess import os from os import path from os import listdir # find and convert mp3 files to wav files # find all files with an extension, convert to wav files, transcribe to text file then transfer all wav files and mp3 files to finished directory and email transcribed files. # find files with mp3 extension def list_files1(directory, extension): ext = [] for root, dirs, files in os.walk(directory): for file in files: if file.endswith(extension): ext.append(file) print(ext) return ext # get directory path originalDir = os.getcwd() # call function to find files with mp3 extension mp3files = list_files1(originalDir, "m4a") # os.chdir("/Users/williamjohnson/Dropbox/goodscrapers/publimaison2/") # convert all mp3 files to wav files for x in mp3files: print(x) timestr = time.strftime("%Y%m%d-%H%M%S") command = "ffmpeg -i " + x + ' ' + timestr + ".wav" print(command) subprocess.call(command, shell=True) # find all converted wav files wavfiles = list_files1(originalDir, "wav") for y in wavfiles: print(y) # obtain path to "english.wav" in the same folder as this script AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), y) # AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "french.aiff") # AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "chinese.flac") # use the audio file as the audio source r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: audio = r.record(source) # read the entire audio file # recognize speech using Sphinx try: print("Sphinx thinks you said " + r.recognize_s…
favorite count: 0

http://stackoverflow.com/comment/91287252
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52168241
has text: @nottinhill , what do you mean by *"more elegant way"*? What you expect to be a good answer to your question?

http://stackoverflow.com/comment/134918882
comment on: http://stackoverflow.com/a/52164534
has text: `.env.dev` should be in the config directory
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91212892
has text: if you put in your update url instead of pk slug:slug i think that it work
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52131063
type: Comment

django-views
tags question: http://stackoverflow.com/q/52244997
tags question: http://stackoverflow.com/q/52175622
tags question: http://stackoverflow.com/q/52239128
tags question: http://stackoverflow.com/q/52154017
tags question: http://stackoverflow.com/q/52245448
tags question: http://stackoverflow.com/q/52167295
tags question: http://stackoverflow.com/q/52207464
tags question: http://stackoverflow.com/q/52136318
tags question: http://stackoverflow.com/q/52208582
tags question: http://stackoverflow.com/q/52266377
tags question: http://stackoverflow.com/q/52227531
tag name: django-views
tags question: http://stackoverflow.com/q/52245386
tags question: http://stackoverflow.com/q/52117935
type: Tag
tags question: http://stackoverflow.com/q/52183975
tags question: http://stackoverflow.com/q/52155601
tags question: http://stackoverflow.com/q/52218791
tags question: http://stackoverflow.com/q/52159365
tags question: http://stackoverflow.com/q/52144546
tags question: http://stackoverflow.com/q/52157649
tags question: http://stackoverflow.com/q/52243362
tags question: http://stackoverflow.com/q/52259027
tags question: http://stackoverflow.com/q/52187046
tags question: http://stackoverflow.com/q/52147061
tags question: http://stackoverflow.com/q/52268930
tags question: http://stackoverflow.com/q/52210917
tags question: http://stackoverflow.com/q/52203764
tags question: http://stackoverflow.com/q/52249056
tags question: http://stackoverflow.com/q/52166054

http://stackoverflow.com/comment/91471310
comment on: http://stackoverflow.com/q/52261828
has text: There are tons of code for prime number generation, you only need to search a bit.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52258284
tagged with: pyside2
upvote count: 1
type: Question
tagged with: qml
has title: Cannot use ApplicationWindow (QML) on PySide2
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52259904
favorite count: 0
has body: I'm trying to run a simple Qt application using QML and more specifically ApplicationWindow. My Python code is a simple QML caller: import sys from PySide2.QtWidgets import QApplication from PySide2.QtQuick import QQuickView from PySide2.QtCore import QUrl if __name__ == '__main__': app = QApplication(sys.argv) view = QQuickView() url = QUrl('view.qml') view.setSource(url) view.show() sys.exit(app.exec_()) and my QML file is a simple ApplicationWindow with Title, width and height: import QtQuick 2.0 ApplicationWindow { title: "Qt Quick Controls Gallery" width: 640 height: 480 } Running the code results in a blank screen, with default title ("gui.py", instead of the title given on QML), and with default width and height (not the specified on the QML file): I can run other components, like rectangles, buttons and canvas without problems. My problem is specifically with the ApplicationWindow component, that I would like to use since it's the standard for QML apps. I'm trying to stick with PySide2 as it's becoming the supported for Python Qt, but I'm accepting PyQt solutions as well, of course.
accepted answer: http://stackoverflow.com/a/52259904
has answer: http://stackoverflow.com/a/52259886
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52259886
score: 1

http://stackoverflow.com/q/52266049
has comment: http://stackoverflow.com/comment/91480213
answer count: 3
tagged with: convex-optimization
tagged with: python
possible better answer: http://stackoverflow.com/a/52267106
has body: I am creating a basic Newton-method algorithm for an unconstrained optimization problem, and my results from the algorithm are not what I expected. It is a simple objective function so it is clear that the algorithm should converge on (1,1). This is confirmed by a gradient descent algorithm I created previously, here: def grad_descent(x, t, count, magnitude): xvalues.append(x) gradvalues.append(np.array([dfx1(x), dfx2(x)])) fvalues.append(f(x)) temp=x-t*dfx(x) x = temp magnitude = mag(dfx(x)) count+=1 return xvalues, gradvalues, fvalues, count My attempt at creating an algorithm for Newtons-Method is here: def newton(x, t, count, magnitude): xvalues=[] gradvalues=[] fvalues=[] temp=x-f(x)/dfx(x) while count &lt; 10: xvalues.append(x) gradvalues.append(dfx(x)) fvalues.append(f(x)) temp=x-t*f(x)/dfx(x) x = temp magnitude = mag(dfx(x)) count+=1 if count &gt; 100: break return xvalues, gradvalues, fvalues, count Here is the objective function and gradient function: f = lambda x: 100*np.square(x[1]-np.square(x[0])) + np.square((1-x[0])) dfx = lambda x: np.array([-400*x[0]*x[1]+400*np.power(x[0],3)+2*x[0]-2, 200*(x[1]-np.square(x[0]))]) Here are the initial conditions. Note that alpha and beta are not used in the newton method. x0, t0, alpha, beta, count = np.array([-1.1, 1.1]), 1, .15, .7, 1 magnitude = mag(np.array([dfx1(x0), dfx2(x0)])) To call the function: xvalues, gradvalues, fvalues, iterations = newton(x0, t0, count, magnitude) This produce very strange results. Here are the first 10 iterations of the xvalues, gradient values, and function solution for its respective x input: [array([-1.1, 1.1]), array([-0.99315589, 1.35545455]), array([-1.11651296, 1.11709035]), array([-1.01732476, 1.35478987]), array([-1.13070578, 1.13125051]), array([-1.03603697, 1.35903467]), array([-1.14368874, 1.14364506]), array([-1.05188162, 1.36561528]), array([-1.15600558, 1.15480705]), array([-1.06599492, 1.37360245])] [array([-52.6, -22. ]), array([142.64160215, 73.81918332]), array([-…
has answer: http://stackoverflow.com/a/52267106
accepted answer: http://stackoverflow.com/a/52351046
tagged with: newtons-method
type: AnsweredQuestion
downvote count: 0
has title: How to tell if Newtons-Method Fails
has comment: http://stackoverflow.com/comment/91480532
has comment: http://stackoverflow.com/comment/91480284
has answer: http://stackoverflow.com/a/52351046
type: Question
has comment: http://stackoverflow.com/comment/91480337
tagged with: algorithm
score: 1
has comment: http://stackoverflow.com/comment/91500457
has answer: http://stackoverflow.com/a/52298790
has comment: http://stackoverflow.com/comment/91499015
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/91257163
has text: What system (OS, distro, etc.) is this? Can you post the full log of `virtualenv --python=python3.5 newtestenv; source newtestenv/bin/activate; python --version; which python`?
score: 0
comment on: http://stackoverflow.com/q/52153469
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52180305
has comment: http://stackoverflow.com/comment/91311118
answers question: http://stackoverflow.com/q/52179275
has comment: http://stackoverflow.com/comment/91310476
score: 1
has body: TL;DR For Pandas / NumPy efficiency, don't use mixed types (object dtype) within a column. There are methods available to convert series to numeric and then manipulate them efficiently. You can use pd.DataFrame.select_dtypes to determine numeric columns. Assuming these are the only ones where you wish to update values, you can then feed these to pd.DataFrame.loc. It quickly iterates through the underlying array, but the new dataframe has all 'object' dtypes. Given you are left with object dtype series, it seems your definition of ix_to_change includes non-numeric series. In this case, you should convert all numeric columns to numeric dtype. For example, using pd.to_numeric: df[ix_to_change] = df[ix_to_change].apply(pd.to_numeric, errors='coerce') Pandas / NumPy will not help with object dtype series in terms of performance, if this is what you are after. These series are represented internally as a sequence of pointers, much like list. Here's an example to demonstrate what you can do: import pandas as pd, numpy as np df = pd.DataFrame({'key': [0, 2, 0, 4, 0], 'A': [0.5, 1.5, 2.5, 3.5, 4.5], 'B': [2134, 5634, 134, 63, 1234], 'C': ['fsaf', 'sdafas',' dsaf', 'sdgf', 'fdsg'], 'D': [np.nan, pd.to_datetime('today'), np.nan, np.nan, np.nan], 'E': [True, False, True, True, False]}) numeric_cols = df.select_dtypes(include=[np.number]).columns df.loc[df['key'] == 0, numeric_cols] = 0 Result: A B C D E key 0 0.0 0 fsaf NaT True 0 1 1.5 5634 sdafas 2018-09-05 False 2 2 0.0 0 dsaf NaT True 0 3 3.5 63 sdgf NaT True 4 4 0.0 0 fdsg NaT False 0 No conversion to object dtype series for numeric columns, as expected: print(df.dtypes) A float64 B int64 C object D datetime64[ns] E bool key int64 dtype: object
has comment: http://stackoverflow.com/comment/91312585
upvote count: 1
has comment: http://stackoverflow.com/comment/91310583
has comment: http://stackoverflow.com/comment/91310656
has comment: http://stackoverflow.com/comment/91312506
has comment: http://stackoverflow.com/comment/91311138
type: Answer
has comment: http://stackoverflow.com/comment/91310677
has comment: http://stackoverflow.com/comment/91310539
downvote count: 0

http://stackoverflow.com/comment/91872061
type: Comment
comment on: http://stackoverflow.com/a/52354854
type: AnswerComment
has text: ok cool ! I also remember I had to share my spreadsheet with the email Id crated by Google console
score: 0

http://stackoverflow.com/comment/91296998
has text: The loss is the average, not the sum of the individual losses.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52172859
score: 4

http://stackoverflow.com/comment/91862935
type: Comment
type: QuestionComment
score: 0
has text: @QusaiAlothman It worked! Could you post the advice as the answer so I can mark it as solved?
comment on: http://stackoverflow.com/q/52146685

http://stackoverflow.com/comment/91192591
score: 0
has text: I believe the first answer in this question is relevant: [link](https://stackoverflow.com/questions/39132742/groupby-value-counts-on-the-dataframe-pandas). Use `.size().unstack(fill_value=0)` on your groupby object. This will get you the occurrences of 'U' for each ID-item, then you can divide by the total number of occurrences.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52120601

http://stackoverflow.com/q/52150008
has body: I am trying to implement a Neural Network using tensorflow. I want my model to initialize itself using default parameters or any weight size list passed by users. But the compute graph generated by my code seems incorrect. How can I initialize a NN by user-defined parameters in tensorflow? def setUp(self): self.hidden_layer_ = len(self.hidden_layer_sizes) self.weights = [] self.biases = [] size_list = [self.input_size] size_list.extend(list(self.hidden_layer_sizes)) i = 0 while i + 1 &lt; len(size_list): prev_size = size_list[i] size = size_list[i+1] w = tf.Variable(tf.truncated_normal([prev_size, size], stddev=0.1)) b = tf.Variable(tf.zeros([size])) self.weights.append(w) self.biases.append(b) i += 1 self.w_out = tf.Variable(tf.truncated_normal([size_list[-1], self.output_size], stddev=0.1)) self.b_out = tf.Variable(tf.zeros([self.output_size])) self.input_x = tf.placeholder(tf.float32, [None, self.input_size], name='input') self.input_y = tf.placeholder(tf.float32, [None, self.output_size], name='label') self.keep_prob_plh = tf.placeholder(tf.float32) self.layers = [self.input_x] for w, b in zip(self.weights, self.biases): hidden = ACT_FUN_DICT[self.activation](tf.matmul(self.layers[-1], w) + b) hidden_drop = tf.nn.dropout(hidden, self.keep_prob_plh) self.layers.append(hidden_drop) with tf.variable_scope('output'): self.output_layer = tf.nn.sigmoid(tf.matmul(self.layers[-1], self.w_out) + self.b_out) self.cost_func = tf.reduce_mean(tf.reduce_sum(tf.pow((self.input_y - self.output_layer), 2))) self.cost_summary = tf.summary.scalar('Cost', self.cost_func) self.optimizer = SOLVER_DICT[self.solver](self.learning_rate).minimize(self.cost_func) root_logdir = './tf_logs' now = datetime.utcnow().strftime('%Y%m%d%H%M%S') log_dir = "{}/run-{}/".format(root_logdir, now) self.file_writer = tf.summary.FileWriter(log_dir, tf.get_default_graph()) self.sess.run(tf.global_variables_initializer()) I implement the NN using a class, the size of weights are stored in the member self.h…
has comment: http://stackoverflow.com/comment/91250895
has title: How to initialize a neural network by user defined parameters in tensorflow
type: Question
tagged with: machine-learning
tagged with: python
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/91253282
downvote count: 1
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/91253346
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91251819
favorite count: 0

http://stackoverflow.com/comment/91237933
has text: [Please don't post your code or exception as an image](//meta.stackoverflow.com/q/285551). It's [hard to read](http://idownvotedbecau.se/imageofanexception/), prevents text-based searching, and lowers the overall presentation of the post.
score: 4
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52144105

http://stackoverflow.com/comment/109161880
type: AnswerComment
comment on: http://stackoverflow.com/a/52191801
score: 0
type: Comment
has text: Great the image is compressed a lot. Though is there a way to retain the orignal image height to width ratio?

http://stackoverflow.com/comment/91277039
has text: Try: `ldd example.so` Anyway, *ctypes* doesn't have anything to do with linking, it's dynamically loading. But, again without a *mcve* ([\[SO\]: How to create a Minimal, Complete, and Verifiable example (mcve)](https://stackoverflow.com/help/mcve)) it's hard to tell
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52139846
score: 0

http://stackoverflow.com/q/52206550
has comment: http://stackoverflow.com/comment/91362349
has answer: http://stackoverflow.com/a/52206768
downvote count: 0
has answer: http://stackoverflow.com/a/75654662
favorite count: 0
answer count: 5
has answer: http://stackoverflow.com/a/52206832
tagged with: python
has answer: http://stackoverflow.com/a/52206779
tagged with: readlines
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52206928
has title: How to split elements in a list and get date and time from a list
has body: Since the beginning of time I have been struggling with importing files in Python and reading lines in a optimal way. For example, a file I have is as follows: 2015 02 25 09:00:00 A second line One more line Now I want to extract the date and time from the first line; for this we want it in this format I think, to make it work in the datetime module (2015,02,25,09,00,00) This is what I have with open('file.txt', newline='') as inputfile: data = inputfile.readlines() print(data[0]) Out: ['2015 02 25 09:00:00'] This gives us the first element of the list. Now I want to make a comma separated list out of this. Now when I try this for example: In: datetime = [i.split(':') for i in file[0]] Out: [['2015 02 25 09', '00', '00']] I get a list of lists, which does not make things easier in any way. And we haven't even split the whitespaces yet. What is the best way to get the date and time out of this? And more in general, do you know any good tutorials to practice list/string splitting, iterate over text files/lists etc.
score: 2
tagged with: list
type: Question
tagged with: split

http://stackoverflow.com/comment/139940631
has text: or simply `path_ntb = Path(__vsc_ipynb_file__)` , but this would work only in vscode...
type: AnswerComment
comment on: http://stackoverflow.com/a/79058859
score: 0
type: Comment

http://stackoverflow.com/q/52162909
tagged with: python
accepted answer: http://stackoverflow.com/a/52163125
type: AnsweredQuestion
upvote count: 5
tagged with: dataframe
type: Question
answer count: 2
score: 5
has body: So I used a group by on a pandas dataframe which looks like this df.groupby(['year','month'])['AMT'].agg('sum') And I get something like this year month 2003 1 114.00 2 9195.00 3 300.00 5 200.00 6 450.00 7 68.00 8 750.00 9 3521.00 10 250.00 11 799.00 12 1000.00 2004 1 8551.00 2 9998.00 3 17334.00 4 2525.00 5 16014.00 6 9132.00 7 10623.00 8 7538.00 9 3650.00 10 7733.00 11 10128.00 12 4741.00 2005 1 6965.00 2 3208.00 3 8630.00 4 7776.00 5 11950.00 6 11717.00 7 1510.00 ... 2015 7 1431441.00 8 966974.00 9 1121650.00 10 1200104.00 11 1312191.90 12 482535.00 2016 1 1337343.00 2 1465068.00 3 1170113.00 4 1121691.00 5 1302936.00 6 1518047.00 7 1251844.00 8 825215.00 9 1491626.00 10 1243877.00 11 1632252.00 12 750995.50 2017 1 905974.00 2 1330182.00 3 1382628.52 4 1146789.00 5 1201425.00 6 1278701.00 7 1172596.00 8 1517116.50 9 1108609.00 10 1360841.00 11 1340386.00 12 860686.00 What I want is to just select the max out of the third summed column so that the final data frame has only the max from each year, something like: year month 2003 2 9195.00 2004 3 17334.00 2005 5 11950.00 ... and so on What do I have to add to my group by aggregation to do this?
downvote count: 0
possible better answer: http://stackoverflow.com/a/52163152
has answer: http://stackoverflow.com/a/52163125
has answer: http://stackoverflow.com/a/52163152
tagged with: pandas-groupby
tagged with: pandas
has title: How to get the max out of a group by on two columns and sum on third in a pandas dataframe?
favorite count: 0

arrays
tags question: http://stackoverflow.com/q/52253378
tags question: http://stackoverflow.com/q/52120200
tags question: http://stackoverflow.com/q/52218251
tags question: http://stackoverflow.com/q/52131822
tags question: http://stackoverflow.com/q/52114666
type: Tag
tags question: http://stackoverflow.com/q/52212118
tags question: http://stackoverflow.com/q/52240535
tags question: http://stackoverflow.com/q/52240846
tags question: http://stackoverflow.com/q/52164047
tags question: http://stackoverflow.com/q/52141920
tags question: http://stackoverflow.com/q/52239768
tags question: http://stackoverflow.com/q/52138737
tags question: http://stackoverflow.com/q/52153594
tags question: http://stackoverflow.com/q/52127529
tags question: http://stackoverflow.com/q/52116978
tags question: http://stackoverflow.com/q/52166639
tags question: http://stackoverflow.com/q/52231121
tags question: http://stackoverflow.com/q/52266658
tags question: http://stackoverflow.com/q/52226079
tags question: http://stackoverflow.com/q/52241820
tags question: http://stackoverflow.com/q/52194717
tags question: http://stackoverflow.com/q/52229579
tags question: http://stackoverflow.com/q/52230938
tags question: http://stackoverflow.com/q/52139518
tags question: http://stackoverflow.com/q/52179821
tags question: http://stackoverflow.com/q/52239956
tags question: http://stackoverflow.com/q/52248471
tags question: http://stackoverflow.com/q/52185740
tags question: http://stackoverflow.com/q/52183013
tags question: http://stackoverflow.com/q/52173120
tags question: http://stackoverflow.com/q/52146977
tags question: http://stackoverflow.com/q/52171180
tags question: http://stackoverflow.com/q/52176245
tags question: http://stackoverflow.com/q/52155603
tags question: http://stackoverflow.com/q/52186120
tags question: http://stackoverflow.com/q/52190024
tags question: http://stackoverflow.com/q/52142021
tags question: http://stackoverflow.com/q/52153991
tags question: http://stackoverflow.com/q/52133947
tags question: http://stackoverflow.com/q/52130441
tag name: arrays
tags question: http://stackoverflow.com/q/52256932
tags question: http://stackoverflow.com/q/52200102
tags question: http://stackoverflow.com/q/52233115
tags question: http://stackoverflow.com/q/52126238
tags question: http://stackoverflow.com/q/52135161
tags question: http://stackoverflow.com/q/52123272
tags question: http://stackoverflow.com/q/52247440
tags question: http://stackoverflow.com/q/52167339
tags question: http://stackoverflow.com/q/52171610
tags question: http://stackoverflow.com/q/52113360
tags question: http://stackoverflow.com/q/52190617
tags question: http://stackoverflow.com/q/52118783
tags question: http://stackoverflow.com/q/52136625
tags question: http://stackoverflow.com/q/52189425
tags question: http://stackoverflow.com/q/52153287
tags question: http://stackoverflow.com/q/52244225
tags question: http://stackoverflow.com/q/52189433
tags question: http://stackoverflow.com/q/52257265
tags question: http://stackoverflow.com/q/52130755
tags question: http://stackoverflow.com/q/52135392
tags question: http://stackoverflow.com/q/52245657
tags question: http://stackoverflow.com/q/52137832
tags question: http://stackoverflow.com/q/52138924
tags question: http://stackoverflow.com/q/52124961
tags question: http://stackoverflow.com/q/52244443
tags question: http://stackoverflow.com/q/52132331
tags question: http://stackoverflow.com/q/52123476
tags question: http://stackoverflow.com/q/52134327
tags question: http://stackoverflow.com/q/52130913
tags question: http://stackoverflow.com/q/52161604
tags question: http://stackoverflow.com/q/52180440
tags question: http://stackoverflow.com/q/52116918
tags question: http://stackoverflow.com/q/52238303
tags question: http://stackoverflow.com/q/52137200
tags question: http://stackoverflow.com/q/52243734
tags question: http://stackoverflow.com/q/52118745
tags question: http://stackoverflow.com/q/52223059
tags question: http://stackoverflow.com/q/52153855

http://stackoverflow.com/q/52263110
has comment: http://stackoverflow.com/comment/91473987
type: Question
has body: I am creating an enter/exit block for a module level construct. I have the following example to test how to access the module level variable from within the class: _variableScope = '' class VariableScope(object): def __init__(self, scope): self._scope = scope def __enter__(self): global _variableScope _variableScope += self._scope x = VariableScope('mytest') x.__enter__() print(_variableScope) This gets me the expected value of 'mytest', but ... Is the use of global inside the __enter__() method correct and good practice?
has title: Is `global` the correct way for a class to access a module level variable?
has comment: http://stackoverflow.com/comment/91474664
score: 0
has comment: http://stackoverflow.com/comment/91474593
accepted answer: http://stackoverflow.com/a/52263302
answer count: 1
has comment: http://stackoverflow.com/comment/91474219
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52263302

http://stackoverflow.com/q/52220242
type: Question
has body: I made a simple network to find broken lines and I had a very strange training run. The loss, keras.losses.binary_crossentropy, was decreasing steadily for around 1500 epochs then suddenly, it shot up and plateaued. What are some reasons this happens? Optimizers, loss function, network structure? I checked the weights, and none of the weights have a NaN value. The input data is 250,000+ 32x32 images with lines on them, and the same stack of images where the lines have a few pixels removed from so they're "broken". Here is the model creation code: input_shape = (1, 32, 32) kernel_shape = (16, 16) keras.backend.set_image_data_format("channels_first") n_filters = 64 input_layer = engine.Input(input_shape) active_1 = layers.Activation("relu")(input_layer) conv_1 = layers.Conv2D(n_filters, kernel_shape)(active_1) conv_2 = layers.Conv2D(2*n_filters, kernel_shape)(conv_1) pool_1 = layers.MaxPooling2D()(conv_2) s = tupleFromShape(pool_1.shape) p = 1 for d in s: p *= d shaped_1 = layers.Reshape((p,))(pool_1) dense_1 = layers.Dense(2)(shaped_1) out = layers.Activation("softmax")(dense_1) model = engine.Model(input_layer, out) model.save("broken-lines-start.h5") And the training code: full = #numpy array (c, slices, 32, 32) broken = #numpy array(c, slices, 32, 32) full = full[0] broken = broken[0] n = len(full) - 1024 n2 = len(broken) - 1024 random.shuffle(full) random.shuffle(broken) optimizer = keras.optimizers.Adam(0.00001) loss_function = keras.losses.binary_crossentropy model.compile( model, optimizer, loss_function=loss_function) batch_size = 256 steps = n//batch_size + n2//batch_size model.fit_generator(generator=getDataGenerator(full[:n], broken[:n2], batch_size), steps_per_epoch=steps, epochs=4680, validation_data=getDataGenerator(full[n:], broken[n2:], batch_size), validation_steps=2048//batch_size, callbacks=[saves_last_epoch_and_best_epoch] ) model.save("broken-lines-trained.h5") The generator code: def getDataGenerator(solid, broken, batch_size=128): zed = [([chun…
score: 4
upvote count: 4
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91426544
tagged with: keras
has comment: http://stackoverflow.com/comment/91426733
favorite count: 0
has comment: http://stackoverflow.com/comment/91426357
has answer: http://stackoverflow.com/a/52228330
has comment: http://stackoverflow.com/comment/91415854
tagged with: python
type: UnansweredQuestion
has title: Why does the loss of a CNN decrease for a long time and then suddenly increase?
tagged with: tensorflow

http://stackoverflow.com/a/52205722
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52191695
type: Answer
answers question: http://stackoverflow.com/q/52191695
has body: The following code achieves what I originally wanted, except I am looking for a way to translate the top-right figure to be closer to the scatter plot in the bottom-left. This is a smaller problem though, so I may post it as a new question. from matplotlib.transforms import Affine2D import mpl_toolkits.axisartist.floating_axes as floating_axes import matplotlib.pyplot as plt def setup_axes(fig, rect, rotation, axisScale, axisLimits, doShift): tr_rot = Affine2D().scale(axisScale[0], axisScale[1]).rotate_deg(rotation) # This seems to do nothing if doShift: tr_trn = Affine2D().translate(-90,-5) else: tr_trn = Affine2D().translate(0,0) tr = tr_rot + tr_trn grid_helper = floating_axes.GridHelperCurveLinear(tr, extremes=axisLimits) ax = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper) fig.add_subplot(ax) aux_ax = ax.get_aux_axes(tr) return ax, aux_ax fig = plt.figure(1, figsize=(8, 8)) axes = [] axisOrientation = [0, 0, 270, -45] axisScale = [[1,1],[6,1],[6,1],[6,1]] axisPosition = [223,221,224,222] axisLimits = [(-0.5, 4.5, -0.5, 4.5), (-0.5, 4.5, 0, 12), (-0.5, 4.5, 0, 12), (-3.5, 3.5, 0, 12)] doShift = [False, False, False, True] label_axes = [] for i in range(0, len(axisOrientation)): ax, aux_ax = setup_axes(fig, axisPosition[i], axisOrientation[i], axisScale[i], axisLimits[i], doShift[i]) axes.append(aux_ax) label_axes.append(ax) numPoints = 100 x = [] y = [] for i in range(0,numPoints): x.append(np.random.rand() + i/100.0) y.append(np.random.rand() + i/100.0 + np.mod(i,2)*2) axes[0].plot(x,y,ls='none',marker='x') label_axes[0].axis["bottom"].label.set_text('Variable 1') label_axes[0].axis["left"].label.set_text('Variable 2') b = np.linspace(-0.5,4.5,50) axes[1].hist(x, bins = b) axes[2].hist(y, bins = b) b = np.linspace(-3.5,3.5,50) axes[3].hist(np.array(x)-np.array(y), bins=b) for i in range(1,len(label_axes)): for axisLoc in ['top','left','right']: label_axes[i].axis[axisLoc].set_visible(False) label_axes[i].axis['bottom'].toggle(ticklabels=False)…
score: 3
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91290835
type: AnswerComment
has text: This is great! Thanks! While my script was running for hours already, this piece of code fixed it in a few minutes.
type: Comment
comment on: http://stackoverflow.com/a/52164296
score: 1

http://stackoverflow.com/a/52262225
answers question: http://stackoverflow.com/q/52261828
score: 0
type: Answer
has body: In your function is_prime() you are using a very brute force method to exhaustively check every possible number to see if it is a divisor of x. As mentioned in the comments you can instead only check up to sqrt(x) as the other half of the multiplication would have already been checked. Additionally it is very common to cut the number of calculations in half by checking if x is divisible by 2 only once and then only iterating over odd numbers. With these two modifications alone you can gain a lot of speed. import math def is_prime(x): if x == 2: #2 is prime return True if x % 2 == 0: #divisible by 2 return False for i in range(3,int(math.sqrt(x)),2): #only odd numbers up to sqrt(x) starting from 3 if x % i == 0: #divisible by i return False return True #we made it through the loop without finding a divisor An example of generating all primes up to x using a prime sieve and numpy might look something like this: import numpy as np sieve = np.ones(x,bool) sieve[:2] = False #0 and 1 are not prime for i in range(2,int(x**.5)): if sieve[i]: #`i` is prime therefore mark all multiples of i as not prime sieve[i*2::i] = False primes = np.where(sieve)[0] #extract primes as indices of `primes` that are true

http://stackoverflow.com/q/52148690
downvote count: 0
has comment: http://stackoverflow.com/comment/91256772
has comment: http://stackoverflow.com/comment/91271624
has title: How to make a tree from the output of a dependency parser?
favorite count: 0
possible better answer: http://stackoverflow.com/a/52161069
has comment: http://stackoverflow.com/comment/91291124
has body: I am trying to make a tree (nested dictionary) from the output of dependency parser. The sentence is "I shot an elephant in my sleep". I am able to get the output as described on the link: How do I do dependency parsing in NLTK? nsubj(shot-2, I-1) det(elephant-4, an-3) dobj(shot-2, elephant-4) prep(shot-2, in-5) poss(sleep-7, my-6) pobj(in-5, sleep-7) To convert this list of tuples into nested dictionary, I used the following link: How to convert python list of tuples into tree? def build_tree(list_of_tuples): all_nodes = {n[2]:((n[0], n[1]),{}) for n in list_of_tuples} root = {} print all_nodes for item in list_of_tuples: rel, gov,dep = item if gov is not 'ROOT': all_nodes[gov][1][dep] = all_nodes[dep] else: root[dep] = all_nodes[dep] return root This gives the output as follows: {'shot': (('ROOT', 'ROOT'), {'I': (('nsubj', 'shot'), {}), 'elephant': (('dobj', 'shot'), {'an': (('det', 'elephant'), {})}), 'sleep': (('nmod', 'shot'), {'in': (('case', 'sleep'), {}), 'my': (('nmod:poss', 'sleep'), {})})})} To find the root to leaf path, I used the following link: Return root to specific leaf from a nested dictionary tree [Making the tree and finding the path are two separate things]The second objective is to find the root to leaf node path like done Return root to specific leaf from a nested dictionary tree. But I want to get the root-to-leaf (dependency relationship path) So, for instance, when I will call recurse_category(categories, 'an') where categories is the nested tree structure and 'an' is the word in the tree, I should get ROOT-nsubj-dobj (dependency relationship till root) as output.
has answer: http://stackoverflow.com/a/52161069
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52231026
tagged with: nlp
linked to: http://stackoverflow.com/q/7443330
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/34395127
linked to: http://stackoverflow.com/q/47302382
has comment: http://stackoverflow.com/comment/91293352
linked to: http://stackoverflow.com/q/13883277
has comment: http://stackoverflow.com/comment/91265935
has comment: http://stackoverflow.com/comment/91297181
type: Question
has comment: http://stackoverflow.com/comment/91300147
tagged with: stanford-nlp
tagged with: nltk
upvote count: 5
accepted answer: http://stackoverflow.com/a/52231026
linked to: http://stackoverflow.com/q/39495924
answer count: 2
score: 5

http://stackoverflow.com/comment/91438357
type: Comment
type: QuestionComment
has text: driver.fiind_elements_by_xpath(//@title); This will return all the elements on page with title attribute, store in list and iterate over it to get its value using get_attribute method...
comment on: http://stackoverflow.com/q/52244588
score: 0

http://stackoverflow.com/a/52204008
has comment: http://stackoverflow.com/comment/91357998
has comment: http://stackoverflow.com/comment/91357530
score: 0
answers question: http://stackoverflow.com/q/52202459
has comment: http://stackoverflow.com/comment/91360229
has comment: http://stackoverflow.com/comment/91357181
type: Answer
has comment: http://stackoverflow.com/comment/91357107
has comment: http://stackoverflow.com/comment/91357714
has body: You can write a different method for fetching data. def getDataWithRetry(self, url, data, timeoutValue): responsedata = None retry = None try: responsedata = requests.get(url, timeout=timeoutValue, data=data, headers=self.hed, verify=False) retry = False except (requests.Timeout): retry = True return (retry, responsedata) Call this method from getdata in loop till retry is False. You can also limit the retries by keeping a loop counter. For printing name of thread. import threading print(threading.current_thread().getName()) Reply after comment - Modify requests.get call as - responsedata = requests.get(url, timeout=120, data=data, headers=self.hed, verify=False) and except statement as - except (requests.exceptions.RequestException, requests.Timeout, ConnectionResetError) as e:

http://stackoverflow.com/q/52228140
has answer: http://stackoverflow.com/a/52365924
accepted answer: http://stackoverflow.com/a/52365924
type: Question
has body: How can I (hermetically) include python as an (executable) input to my genrule? Conceptually, I'm aware of the following approaches: include a python interpreter in the source repo at third_party/python have Bazel fetch python ala rules-go There also seem to be a couple methods for doing so: py_runtime py_toolchain (doesn't seem to be available yet) py_distribution_package (doesn't seem to be available yet) genrules.tools genrules.toolchains Example: I have a python library: myproject - setup.py - mylibrary - __init__.py - myfunction.py I'd like to produce a pip install-able distribution with Bazel so that I can do: pip install &lt;path/to/distribution&gt; python &gt;&gt;&gt; from mylibrary.myfunction import helloworld &gt;&gt;&gt; helloworld() I added a (empty) WORKSPACE file at myproject/WORKSPACE and followed the example in this medium article: # myproject/BUILD genrule( name = "mylibrary_sdist", srcs = glob(["**/*.py"]), outs = ["mylibrary.tar.gz"], cmd = "python setup.py sdist &amp;&amp; mv dist/mylibrary*.tar.gz $(location mylibrary.tar.gz)" ) This works (ie. produces bazel-genfiles/mylibrary.tar.gz), but I'm shelling out to python. How can I (hermetically) include python as an (executable) input to my genrule?
answer count: 1
favorite count: 0
tagged with: bazel
upvote count: 10
tagged with: python
has title: How to (hermetically) include Python interpreter in Bazel to build Python library (sdist)
downvote count: 0
type: AnsweredQuestion
score: 10

http://stackoverflow.com/comment/91238223
score: 1
has text: show us a code example, the error stack and example data.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52144245

http://stackoverflow.com/comment/91362591
has text: It depends. You could use a 1billion-dimensional data point and for all routes that are shorter simply repeat the end point up to have that number of dimensions. Sure, you are going to lose information by splitting the routes, however I have no idea what you are trying to do. might or might not be important depending on what exactly you want to achieve. Splitting sequences is a common practice, for example using LSTMs you have to choose a certain number of time steps and divide longer sequences according to that. If you do it well you lose very little information.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52206267

http://stackoverflow.com/a/52146351
score: 0
answers question: http://stackoverflow.com/q/52141883
type: Answer
has body: I think this is because jpeg is a loss compression, it differs every time you save the image. If you want the decode result be the same every time you read it, you can use other format, such as png, bmp, etc.

http://stackoverflow.com/comment/91422169
score: 0
has text: thank you @Blorgbeard, but I typed the example that is on the webpage and it works fine, my code is the one with problems
type: QuestionComment
comment on: http://stackoverflow.com/q/52236768
type: Comment

http://stackoverflow.com/q/52129253
tagged with: selenium
has comment: http://stackoverflow.com/comment/91209421
type: Question
score: 3
has title: Fatal Python error while executing application created in python
has comment: http://stackoverflow.com/comment/91209375
has comment: http://stackoverflow.com/comment/91209097
has comment: http://stackoverflow.com/comment/91208995
has comment: http://stackoverflow.com/comment/91209074
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91209514
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: pyinstaller
tagged with: python
has body: short.py from selenium import webdriver from selenium.webdriver.common.keys import Keys from time import sleep from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait import time print("Opening...") driver = webdriver.Chrome('chromedriver.exe') driver.get('https://google.com') Converting the above script file to executable file: pyinstaller short.py While executing the short.exe Gave me error: Fatal Python error: initfsencoding: unable to load the file system codec zipimport.ZipImportError: can't find module 'encodings' My Python version is 3.7, can anybody please suggest the most appropriate corrective action to take?
tagged with: exe
upvote count: 3
has answer: http://stackoverflow.com/a/52129286

http://stackoverflow.com/comment/91449626
score: 0
type: AnswerComment
has text: in this case, you need to open the terminal inside your windows. That's your OS where Hadoop is installed.
type: Comment
comment on: http://stackoverflow.com/a/52250094

http://stackoverflow.com/q/52260568
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/91492285
has answer: http://stackoverflow.com/a/52272761
score: 0
has comment: http://stackoverflow.com/comment/91470015
answer count: 1
tagged with: apache-spark-sql
has body: I have the following DataFrame df in PySpark. import pyspark.sql.functions as func df = spark\ .read \ .format("org.elasticsearch.spark.sql") \ .load("my_index/my_mapping") \ .groupBy(["id", "type"]) \ .agg( func.count(func.lit(1)).alias("number_occurrences"), func.countDistinct("host_id").alias("number_hosts") ) ds = df.collect() I use collect because the amount of data after grouping and aggregating is always small and fits into memory. Also, I need to use collect because I pass ds as a parameter of udf function. The function collect returns an array. How can I make the following queries to this array: for the given id and type, return number_occurrences and number_hosts. For example, let's imagine that df contains the following rows: id type number_occurrences number_hosts 1 xxx 11 3 2 yyy 10 4 After doing df.collect(), how can I retrieve number_occurences and number_hosts for id equal to 1 and type equal to xxx. The expected result is: number_occurrences = 11 number_hosts = 3 Update: Maybe there is the more elegant solution? id = 1 type = "xxx" number_occurrences = 0 number_hosts = 0 for row in ds: if (row["id"] == id) &amp; (row["type"] == type): number_occurrences = row["number_occurrences"] number_hosts = row["number_hosts"]
tagged with: pyspark
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91472964
tagged with: apache-spark
has title: How to retrieve particular values from df.collect() result in PySpark?
has comment: http://stackoverflow.com/comment/91469433

http://stackoverflow.com/comment/91244344
comment on: http://stackoverflow.com/q/52147276
type: QuestionComment
has text: No, that is a local variable.
score: 1
type: Comment

http://stackoverflow.com/q/52244867
type: Question
tagged with: time-series
has body: I have a file with several data from wifi access. The database is divided in multiple columns : user_id, start (when the device connect to the router), end (when the device disconnect from the router). Exemple : user_id start end 1 15/05/16 13:51 15/05/16 14:06 1 15/05/16 14:06 15/05/16 14:32 1 15/05/16 14:32 15/05/16 14:34 2 15/05/16 11:14 15/05/16 11:25 2 15/05/16 11:25 15/05/16 12:09 2 15/05/16 12:14 15/05/16 12:42 2 15/05/16 17:33 15/05/16 17:41 2 15/05/16 17:41 15/05/16 18:27 The problem is, sometime the devices disconnect and reconnect. I would like to group the data in event like that: user_id start end 1 15/05/16 13:51 15/05/16 14:34 2 15/05/16 11:14 15/05/16 12:42 2 15/05/16 17:33 15/05/16 18:27 Is there an efficient way to do it with pandas ?
tagged with: database
has title: Pandas merge rows with same start and end time
score: 0
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/52245521
tagged with: data-science
tagged with: python
has answer: http://stackoverflow.com/a/52245518
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52245071
accepted answer: http://stackoverflow.com/a/52245521
has answer: http://stackoverflow.com/a/52245071

http://stackoverflow.com/comment/91304582
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52177162
score: 0
has text: you can give a case under which you got wrong answer.

http://stackoverflow.com/q/52254747
has comment: http://stackoverflow.com/comment/91457360
upvote count: 3
tagged with: django
accepted answer: http://stackoverflow.com/a/52257411
type: Question
has comment: http://stackoverflow.com/comment/91456996
score: 3
has comment: http://stackoverflow.com/comment/91458707
has comment: http://stackoverflow.com/comment/91459132
has body: I'm struggling with a DoesNotExist error on my application. The point is that I don't really understand why this error is thrown as I already handle it: import socket from django.core.exceptions import ObjectDoesNotExist from django.db import Models class MyClass(models.Model): name = models.CharField(max_length=250, default=socket.gethostname(), unique=True) @staticmethod def update_some_list(some_list): for some_item in some_list: try: MyClass.objects.get(name=some_item) except ObjectDoesNotExist: # I also tried with MyClass.DoesNotExist MyClass.objects.create(name=some_item) The point here is that, when I run into this code, I have some "module-level" DoesNotExist that is thrown away, as if this try/except block is never hit: Traceback (most recent call last): File "/app/backend/shared/models.py", line 201, in update_some_list MyClass.objects.get(name=some_item) File "/usr/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/lib/python3.6/site-packages/django/db/models/query.py", line 399, in get self.model._meta.object_name shared.models.DoesNotExist: MyClass matching query does not exist.
has comment: http://stackoverflow.com/comment/91456977
has comment: http://stackoverflow.com/comment/91456980
has title: Django try/except on DoesNotExist still throws it
answer count: 1
has comment: http://stackoverflow.com/comment/91457170
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52257411
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91458589

http://stackoverflow.com/a/52165363
answers question: http://stackoverflow.com/q/52134226
type: Answer
has body: I use R and below is one of the way (not the best one but just to show how it works) to extract value of variable: &gt;&gt; str_extract(text, '(?&lt;=variable\\s)(\\w+)(.)?(\\w+)?') here text is the entire string which you have shared. This gives me an output &gt;&gt; skt.len I am sure there are similar functions in Python to get this done and get the output in desired format.
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91296062

http://stackoverflow.com/comment/91452085
comment on: http://stackoverflow.com/q/52252354
type: Comment
type: QuestionComment
score: 3
has text: This is _default_ value and it means it can be changed by passing another number for `tax_rate` but in second approach `tax_rate` is `0.04` always.

http://stackoverflow.com/comment/91286592
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52168241
has text: why not define a function?

http://stackoverflow.com/comment/91327201
comment on: http://stackoverflow.com/a/52175689
type: Comment
type: AnswerComment
has text: @DavidAnderson: Like I said, merely defining a class makes a reference cycle (the class itself is self-referencing). The fact that `gc.collect()` resolves the problem actually proves cyclic references were the problem; CPython is reference counted, so aside from references that are part of a reference cycle, all objects are cleaned immediately when the last reference to them disappears; if `gc.collect` cleans it, then it was part of, or referenced from, a referenced cycle, always.
score: 0

http://stackoverflow.com/comment/91317505
score: 0
has text: You can take a look at the following questions about moving a item around a canvas: https://stackoverflow.com/questions/41067129/trying-to-make-an-object-move-in-a-grid-with-tkinter-through-player-inputs/41078251#41078251, https://stackoverflow.com/questions/41603194/how-do-i-move-an-object-on-the-screen-using-the-mousex-and-mousey-coordinates-in/41609864#41609864.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52183500

http://stackoverflow.com/a/70574012
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52169173
has body: You can custumize a serializer field and use it as the default ModelSerializer field mapping for ImageField. Note: The following code snippet should be loaded before you serializer class. from rest_framework import serializers from django.db import models class MyImageField(serializers.ImageField): def __init__(self, *args, **kwargs): self.null_as_blank = kwargs.pop('null_as_blank', True) if self.null_as_blank: kwargs['allow_blank'] = True super().__init__(*args, **kwargs) def to_internal_value(self, data): value = super().to_internal_value(data) # Handle deserializer, change blank value back to null. if self.null_as_blank and value == '': value = None return value def to_representation(self, value): value = super().to_internal_value(value) if self.null_as_blank and value is None: value = '' return value serializers.ModelSerializer.serializer_field_mapping[models.ImageField] = MyImageField
downvote count: 0

http://stackoverflow.com/q/52197359
has answer: http://stackoverflow.com/a/52462430
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91343999
favorite count: 0
has answer: http://stackoverflow.com/a/55029630
type: Question
score: 3
tagged with: grpc-python
tagged with: python
has title: Sending back a file stream from GRPC Python Server
possible better answer: http://stackoverflow.com/a/55029630
accepted answer: http://stackoverflow.com/a/52462430
has body: I have a service that needs to return a filestream to the calling client so I have created this proto file. service Sample { rpc getSomething(Request) returns (stream Response){} } message Request { } message Response { bytes data = 1; } When the server receives this, it needs to read some source.txt file and then write it back to the client as a byte stream. Just would like to ask is this the proper way to do this in a Python GRPC server? fileName = "source.txt" with open(file_name, 'r') as content_file: content = content_file.read() response.data = content.encode() yield response I cannot find any examples related to this.
has comment: http://stackoverflow.com/comment/91343967
upvote count: 3
answer count: 2
tagged with: grpc

http://stackoverflow.com/q/52190548
upvote count: 1
type: Question
has body: I receive some packets from serial port. Packet example: last 2 bytes /\ [ data length ] [ data ] [packet crc] I get crc, for example, b'w\x06'. Value is 125 (sum(b'w\x06') = 125). I calculate crc of packet: sum(data). And I get 1655. I know that 1655 is the same as b'w\06', but I do not know, how to translate it simply to 125 and compare with right checksum. What I need to convert 1655 to the same value as received packet bytes (125 or b'w\x06')? binascii/struct/something else? Thanks
has comment: http://stackoverflow.com/comment/91331352
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52190621
favorite count: 0
tagged with: crc
tagged with: python
has comment: http://stackoverflow.com/comment/91335838
type: AnsweredQuestion
has title: Best way to check checksum of bytes in python
score: 1
accepted answer: http://stackoverflow.com/a/52190621

http://stackoverflow.com/comment/91224479
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52137420
score: 7
has text: `"-8.8373347749999997e-08"[12]` is `'9'`

http://stackoverflow.com/comment/91263902
type: Comment
score: 0
has text: It's also not guaranteed that there's an older version installed.
comment on: http://stackoverflow.com/a/52156681
type: AnswerComment

http://stackoverflow.com/comment/91415520
score: 0
comment on: http://stackoverflow.com/q/52232592
type: QuestionComment
has text: @shahidammer : It worked fine without code script to do file operations. I placed the file in c:\users\akjain and it is writing it to file. Thanks
type: Comment

http://stackoverflow.com/comment/91331729
has text: It works.Thanks for the link mentioned.It is very helpful for me.
comment on: http://stackoverflow.com/a/52190856
type: AnswerComment
type: Comment
score: 2

http://stackoverflow.com/comment/91345293
comment on: http://stackoverflow.com/a/52191659
has text: Well, it would be nice if I could create more cubes on the screen, but I guess this works as well, if you have the time to write another comment / answer that shows me how to do that, please post it, if you're just too busy I don't mind this will do as well.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52222109
has comment: http://stackoverflow.com/comment/91557952
type: UnansweredQuestion
tagged with: python
has body: I am trying to deploy a Flask App + React to Azure. I already created a Web-App on Azure but I am struggling to deploy my code. Before, let me tell you things I cannot do: Using Docker Using Git After this restrictions all the tutorials I found including the official MS documentation doesnt help me too much. What I did so far is upload the code as zip as described here: https://learn.microsoft.com/en-us/azure/app-service/app-service-deploy-zip Anyway could somebody tell me the best practice and link me to some tutorials?
score: -1
type: Question
has answer: http://stackoverflow.com/a/52291993
answer count: 1
downvote count: 1
tagged with: flask
favorite count: 0
tagged with: azure
has title: Deploy Flask service to Azure
upvote count: 0
has comment: http://stackoverflow.com/comment/91776172

http://stackoverflow.com/q/52174832
tagged with: printing
has answer: http://stackoverflow.com/a/52176934
answer count: 1
downvote count: 0
has body: I try to write the code for the web automation, which is: open a tab, login, hit button, and print the page. Everything is running perfect except the last step, which my script cannot click the blue "Print" button shown below. Thanks for the help! from selenium import webdriver import time import logging def chrome_script(): driver = webdriver.Chrome('C:\\Users\\Eric\\chromedriver') driver.get("https://shop.spira.com/Admin/Orders/Default.aspx") driver.implicitly_wait(2) driver.find_element_by_id("ctl00_MainContent_LoginDialog1_UserName") driver.find_element_by_id("ctl00_MainContent_LoginDialog1_Password") driver.find_element_by_id("LoginButton") driver.find_element_by_name("ctl00$MainContent$BatchButton").click() time.sleep(2) driver.find_element_by_name("ctl00$MainContent$Print").click() driver.forward() driver.find_element_by_xpath('.//button[text()="Print"]').click() time.sleep(5) return chrome_script()
favorite count: 0
tagged with: driver
accepted answer: http://stackoverflow.com/a/52176934
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: google-chrome
type: Question
has title: Python - cannot use Selenium to hit the final print button

http://stackoverflow.com/comment/91371803
score: 0
type: QuestionComment
type: Comment
has text: I think the implementation is just really slow for large N; on my computer it looks like it'll finish, but in about twenty minutes. You should think about whether or not you really want [Fisher](https://stats.stackexchange.com/questions/14226/given-the-power-of-computers-these-days-is-there-ever-a-reason-to-do-a-chi-squa), of course.
comment on: http://stackoverflow.com/q/52210788

http://stackoverflow.com/a/52194832
downvote count: 0
has body: Going off your conversation with @ShadowRanger below, how about this? import re commit_msg = """ &lt;rdar://problem/19391231&gt; This is the subject line1 &lt;rdar://problem/11121314&gt; This is the subject line2 [Problem] The Problem description [Solution] This is the Solutions section [Recommended Tests] This is the Recommended Tests &lt;rdar://problem/12345678&gt; Text Change-Id: Ibbafa780adb2502d470f12d0280ddb0049c727c4 Reviewed-on: https://tech-gerrit.sd.company.com/17954 Tested-by: Username1 &lt;username1@company.com&gt; Build-watchOS: service account &lt;serviceaccount@company.com&gt; Reviewed-by: username2 &lt;username2@company.com&gt; """ m = re.findall("(?!.*(?:Revert|revert))[\S]*(?:rdar:\/\/problem\/)(\d{8,8})", commit_msg.split('[')[0]) print m
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52194605
type: Answer
answers question: http://stackoverflow.com/q/52194605
score: 2

http://stackoverflow.com/a/52280081
score: 0
has comment: http://stackoverflow.com/comment/91516210
has comment: http://stackoverflow.com/comment/91515175
has body: Ok so there is a lot that needs work here. I imagine the missing bits are part of your main code but without them testing your code is just not possible. I work with what I could and set up your class's to inherit from the tkinter objects they needed to be. Judging by your button command in your BlastAPI class I am assuming this class should be a Toplevel() window. I have made some changes to your code and without having Bio.Blast I have changed some things to what I think you might need to do. import subprocess import tkinter as tk # import tkinter as tk is good for compatibility and maintainability. Don't use * from tkinter.filedialog import * import tkinter.messagebox from Bio.Blast import NCBIWWW from Bio.Blast import NCBIXML class AutoPrimer(tk.Tk): # Class names should normally use the CapWords convention. def __init__(self): #initialization tk.Tk.__init__(self) self.title("Complete Genomics Inc.") self.input = "" self.output = "" self.param = "" self.inputbool = False self.outputbool = False self.parambool = False self.p3filestring = '-p3_settings_file=' self.entry_input = tk.Entry(self) self.entry_output = tk.Entry(self) self.entry_parameters = tk.Entry(self) self.entry_input.grid(row=1, column=1, padx=1, pady=1, sticky="w") self.entry_output.grid(row=2, column=1, padx=1, pady=1, sticky="w") self.entry_parameters.grid(row=3, column=1, padx=1, pady=1, sticky="w") self.label1 = tk.Label(self, text="AUTOPRIMER").grid(row=0, columnspan=4) tk.Button(self, text="Input Filepath: ", command=lambda: self.button1).grid(row=1, padx=1, pady=1, sticky="e") tk.Button(self, text="Output Filepath: ", command=lambda: self.button2).grid(row=2, padx=1, pady=1, sticky="e") tk.Button(self, text="Parameters Filepath: ", command=lambda: self.button3).grid(row=3, padx=1, pady=1, sticky="e") tk.Button(self, text="Get Primers",).grid(row=4) tk.Button(self, text="Parse Primers",).grid(row=4, column=1, sticky="w") tk.Button(self, text="Pool Primers",).grid(row=4, column=2, sticky="w") …
has comment: http://stackoverflow.com/comment/91509895
accepted answer of: http://stackoverflow.com/q/52266674
has comment: http://stackoverflow.com/comment/91549727
has comment: http://stackoverflow.com/comment/91513022
type: Answer
has comment: http://stackoverflow.com/comment/91513059
has comment: http://stackoverflow.com/comment/91509977
answers question: http://stackoverflow.com/q/52266674
has comment: http://stackoverflow.com/comment/91548287
has comment: http://stackoverflow.com/comment/91510074
has comment: http://stackoverflow.com/comment/91521093
has comment: http://stackoverflow.com/comment/91513077
has comment: http://stackoverflow.com/comment/91516252
has comment: http://stackoverflow.com/comment/91515291
has comment: http://stackoverflow.com/comment/91509815
type: AcceptedAnswer

http://stackoverflow.com/q/52230621
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52230629
type: Question
score: 0
answer count: 1
has title: Error because object attribute does not exist, except it does
has body: I am trying to send an email using the SendGrid python API. In order to do so I use this function: def send_contact_us_email(sender=None, name=None, subject=None, message=None): status_code = None if sender and name and subject and message: to = "test@test.com" email = Email.objects.create(to=to, sender=sender, subject=subject, content=message) status_code = email.send() return status_code So I use an Email model to store emails for later potential reference and so that the code for sending an email can be put in the model. Here is the Email model: from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import * sg = SendGridAPIClient(apikey=getattr(settings, 'SENDGRID_API_KEY')) class Email(models.Model): to = models.EmailField(max_length=100) sender = models.EmailField(max_length=100) subject = models.CharField(max_length=100) content = models.TextField() def __str__(self): return 'to: {to} from: {sender}'.format(to=self.to, sender=self.sender) def send(self): if self.to and self.sender and self.subject and self.content: to_email = Email(self.to) from_email = Email(self.sender) content = Content("text/html", self.content) mail = Mail(from_email, self.subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) return response.status_code return 600 # incomplete information, cannot send email. When I run this code I expect it to work fine; I create an email model object with all required data to send an email and then use the sendgrid helper classes to construct a JSON request body for the SendGrid API to handle. However, I get the following error: AttributeError at /contact-us/ 'Email' object has no attribute 'get' Request Method: POST Request URL: http://127.0.0.1:8000/contact-us/ Django Version: 1.11.13 Exception Type: AttributeError Exception Value: 'Email' object has no attribute 'get' Exception Location: /Users/tomfinet/Desktop/royaleaccounts/env/lib/python2.7/site-packages/sendgrid/helpers/mail/personalization.py in add_…
tagged with: python
tagged with: sendgrid-api-v3
has answer: http://stackoverflow.com/a/52230629
tagged with: django

http://stackoverflow.com/comment/91424003
has text: Is there any other python library through which we can do this. I stuck on getting the summation of salary based on the value of months_worked?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52235704
type: AnswerComment

http://stackoverflow.com/a/52149029
has body: Well done for getting this far. You have managed to implement the logic, but have got stuck with a specific behaviour of defaultdict. There are 2 main points to note: If a key is not initialized with defaultdict, it won't be added to the dictionary. You can do this simply by adding 0 to a non-initialized key. For the specific formatting you require, you can use enumerate in a loop after sorting. Putting these together, amend your loop as below: for game in data_dicts: if game['left_score'] == game['right_score']: team_scores[game['left']] += 1 team_scores[game['right']] += 1 elif game ['left_score'] &gt; game['right_score']: team_scores[game['left']] += 3 team_scores[game['right']] += 0 else: team_scores[game['left']] += 0 team_scores[game['right']] += 3 Then use enumerate in a loop. You can use operator.itemgetter and f-strings (the latter in Python 3.6+) to make your logic cleaner: from operator import itemgetter teams_sorted = sorted(team_scores.items(), key=itemgetter(1), reverse=True) for idx, (team, score) in enumerate(teams_sorted, 1): print(f'{idx}. {team} {score} pts') 1. Tarantulas 6 pts 2. Lions 5 pts 3. Snakes 1 pts 4. FC Awesome 1 pts 5. Grouches 0 pts
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52148667
answers question: http://stackoverflow.com/q/52148667
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/52221034
accepted answer of: http://stackoverflow.com/q/52219857
type: Answer
has body: I think you have simply wrote the equation down incorrectly. The following parts std = x.std() mu = x.mean() are not in-line with the original paper. It seems that you require the std = x[: n - lag].std() mu = x[: n - lag].mean() fixing this gives In [221]: custom_autocorrelation(a, 12) Out[221]: 0.9569497673729846 I have also taken some ideas from a previous answer of mine to greatly speed up the calculation def modified_acorr(ts, lag): """An autocorrelation estimation as per http://itfeature.com/time-series-analysis-and-forecasting/autocorrelation-time-series-data Args: ts (np.ndarray): series lag (int): the lag Returns: float: The autocorrelation """ return ( (ts[:ts.size - lag] - ts[:ts.size - lag].mean()) * (ts[lag:] - ts[lag:].mean()) ).ravel().mean() / (ts[lag:].std() * ts[:ts.size - lag].std()) Comparing a regular autocorrelation function we get similar answers In [197]: modified_acorr(a, 12) Out[197]: 0.9569497673729849 In [218]: acorr(a, a.mean(), 12) / acorr(a, a.mean(), 0) # normalisation Out[218]: 0.9201920561073853
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91390837
upvote count: 2
has comment: http://stackoverflow.com/comment/91390794
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52219857
has comment: http://stackoverflow.com/comment/91397088

http://stackoverflow.com/comment/91413189
type: QuestionComment
has text: No. That would be a freak event if there was.
score: 0
comment on: http://stackoverflow.com/q/52231908
type: Comment

http://stackoverflow.com/comment/91322590
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52186361
has text: Next, you execute `x +=1` in the `if` statement, and *on the next line* set `x` back to `1`, so it'll never actually be anything other than `1` at the top of the loop.
type: QuestionComment

http://stackoverflow.com/comment/98720584
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52234206
score: 3
has text: What if we get exception in `session.commit()` when we are not re-raising the exception?

http://stackoverflow.com/comment/91311151
type: Comment
has text: do you want the attempt to be stored even when program is closed as you previously wrote?
score: 0
comment on: http://stackoverflow.com/q/52177889
type: QuestionComment

http://stackoverflow.com/a/77278003
type: Answer
has comment: http://stackoverflow.com/comment/136262720
score: 0
has body: You can add following line ax.set_ylim(y.min(), y.max()) in your animation function. Then the similar code can be written as import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation x = np.linspace(0, 2*np.pi, 100) y = np.cos(x) t = 0 fig, ax = plt.subplots() line, = ax.plot(x, y) def animate(i): y = i*np.sin(i*x) line.set_ydata(y) ax.set_ylim(y.min()*1.1, y.max()*1.1) return line, ani = animation.FuncAnimation(fig=fig, func=animate, frames=range(20), interval=250) plt.close() ani
answers question: http://stackoverflow.com/q/52193852

http://stackoverflow.com/comment/91441087
comment on: http://stackoverflow.com/q/52240403
score: 0
type: Comment
type: QuestionComment
has text: Hasn't worked unfortunately.

http://stackoverflow.com/comment/91329149
has text: @desertnaut, thank you for the suggestion, new to here.
comment on: http://stackoverflow.com/q/52189626
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/91303833
comment on: http://stackoverflow.com/q/52176573
score: 0
type: QuestionComment
type: Comment
has text: I mean slicing df1 by df2. My poor English...

http://stackoverflow.com/comment/91233075
has text: Okay I tried and I didnt get a picture, but I didnt get an error, here is what it did:%run "c:\users\my_user~1\appdata\local\temp\tmpgyzrfx.py"
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52141592
score: 0

http://stackoverflow.com/q/52219393
upvote count: 5
has comment: http://stackoverflow.com/comment/91389186
type: Question
score: 5
linked to: http://stackoverflow.com/q/6796492
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91387541
favorite count: 0
has comment: http://stackoverflow.com/comment/91387756
has title: How do I capture stderr in Python?
has answer: http://stackoverflow.com/a/52249766
tagged with: python
has comment: http://stackoverflow.com/comment/91388936
has comment: http://stackoverflow.com/comment/91387487
accepted answer: http://stackoverflow.com/a/52249766
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91388037
has body: I would like to capture error messages which are generated from a python module A. A is written in C++ and SWIG, and so I cannot capture Python's sys.stderr. &gt;&gt;&gt; import A &gt;&gt;&gt; A.func() # this prints an error message by C++ std::cerr. this is an error message from module A What I want to do are to suppress the error message and to change my script behavior according to the error type. But A.func() does not return error numbers. Assuming that my use of contextlib below is correct, it did not help. &gt;&gt;&gt; import io &gt;&gt;&gt; f = io.StringIO() &gt;&gt;&gt; import contextlib &gt;&gt;&gt; with contextlib.redirect_stderr(f): ... no_return = A.func() ERROR MESSAGE HERE &gt;&gt;&gt; f.getvalue() &gt;&gt;&gt;
linked to: http://stackoverflow.com/q/977840

http://stackoverflow.com/comment/91277483
type: AnswerComment
comment on: http://stackoverflow.com/a/52163034
score: 0
type: Comment
has text: @EranMoshe Fixed, we should use queue if we want to get processed data from workers

http://stackoverflow.com/q/52270853
has title: How to get rid of theano.gof.compilelock?
answer count: 0
type: UnansweredQuestion
upvote count: 7
tagged with: theano
score: 7
type: Question
tagged with: locking
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/34035632
has body: I am using the joblib library to run multiple NN on my multiple CPU at once. the idea is that I want to make a final prediction as the average of all the different NN predictions. I use keras and theano on the backend. My code works if I set n_job=1 but fails for anything >1. Here is the error message: [Parallel(n_jobs=3)]: Using backend ThreadingBackend with 3 concurrent workers. Using Theano backend. WARNING (theano.gof.compilelock): Overriding existing lock by dead process '6088' (I am process '6032') WARNING (theano.gof.compilelock): Overriding existing lock by dead process '6088' (I am process '6032') The code I use is rather simple (it works for n_job=1) from joblib import Parallel, delayed result = Parallel(n_jobs=1,verbose=1, backend="threading")(delayed(myNNfunction)(arguments,i,X_train,Y_train,X_test,Y_test) for i in range(network)) For information (I don't know if this is relevant), this is my parameters for keras: os.environ['KERAS_BACKEND'] = 'theano' os.environ["MKL_THREADING_LAYER"] = "GNU" os.environ['MKL_NUM_THREADS'] = '3' os.environ['GOTO_NUM_THREADS'] = '3' os.environ['OMP_NUM_THREADS'] = '3' I have tried to use the technique proposed here but it didn't change a thing. To be precise I have created a file in C:\Users\myname.theanorc with this in it: [global] base_compiledir=/tmp/%(user)s/theano.NOBACKUP I've read somewhere (I can't find the link sorry) that on windows machines I shouldn't call the file .theanorc.txt but only .theanorc ; in any case it doesn't work. Would you know what I am missing?

http://stackoverflow.com/a/52213432
answers question: http://stackoverflow.com/q/52213377
has comment: http://stackoverflow.com/comment/91376802
score: 0
has comment: http://stackoverflow.com/comment/91383919
type: Answer
has body: Because when you write btn.clicked.connect(self.close_application()), self.close_application() is executed immediately (and the result of the function would be sent to btn.clicked.connect, but at that time the application is already closed). When you write btn.clicked.connect(self.close_application) it is not - because you did not call it. Instead, this code sends the reference to bound method self.close_application, to btn.clicked.connect, to be executed when the button is clicked. To compare it with another example: def f(): print('ffff') calling f() prints ffff, but just using reference to f does not print anything: a = f() # prints ffff b = f # does not print anything b() # prints ffff

http://stackoverflow.com/a/52188968
answers question: http://stackoverflow.com/q/52185979
upvote count: 5
score: 4
has comment: http://stackoverflow.com/comment/91328095
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91327861
has comment: http://stackoverflow.com/comment/91328212
has comment: http://stackoverflow.com/comment/91327965
type: Answer
has body: An interface deviating from the parent signature is a questionable design in regular classes too. You don't need the extra complexity of metaclasses to get into this kind of mess - you can cause the same new/init jumble by subclassing a datetime or whatever. I want to have a metaclass and an easy way to create instances of that metaclass. The usual pattern in Python is to write a factory using a from_something classmethod. To take the example of creating datetime instances from a different init signature, there is for example datetime.fromtimestamp, but you have many other examples too (dict.fromkeys, int.from_bytes, bytes.fromhex...) There is nothing specific to metaclasses here, so use the same pattern: class MyMeta(type): @classmethod def from_no_args(cls, name=None): if name is None: name = cls.__name__ + 'Instance' return cls(name, (), {}) Usage: &gt;&gt;&gt; class A(metaclass=MyMeta): ... pass ... &gt;&gt;&gt; B = MyMeta.from_no_args() &gt;&gt;&gt; C = MyMeta.from_no_args(name='C') &gt;&gt;&gt; A.__name__ 'A' &gt;&gt;&gt; B.__name__ 'MyMetaInstance' &gt;&gt;&gt; C.__name__ 'C'
accepted answer of: http://stackoverflow.com/q/52185979
downvote count: 1
has comment: http://stackoverflow.com/comment/91327812

http://stackoverflow.com/comment/135667657
type: Comment
score: 2
comment on: http://stackoverflow.com/q/52119454
has text: The highest voted answers say you cannot reliably do so, but in many cases, you actually can: https://stackoverflow.com/questions/12544056/how-do-i-get-the-current-ipython-jupyter-notebook-name/.
type: QuestionComment

http://stackoverflow.com/a/52257323
has comment: http://stackoverflow.com/comment/91462180
answers question: http://stackoverflow.com/q/52256983
has comment: http://stackoverflow.com/comment/91462313
score: 0
has body: Your question is incomplete - you didn't post a MCVE, we don't know the effective values for "repeatble" and "num" that leads to this behaviour, and we don't even know if it's using Python 2.x or Python 3.x - so we can just try and guess. Now since you mention that you "parse an XML file into a list of instances", I stronly suspect you are running Python 2.x and passing those values as strings instead of (resp.) boolean and int. In Python 2, "-1" (string) compares greater than 0 (int) - it raises a TypeError in Python 3.x -, and in both cases a non-empty string evals to True in a boolean context (bool('False') == True). Since there's no obvious logical error in your method implementation, that's the only explanation I can think of. BTW, expressions have a boolean values and return exits the function, so you can simplify your code: @property def DCheck(self): if self.repeatable: return True return self.num &gt; 0
type: Answer

http://stackoverflow.com/a/52258404
accepted answer of: http://stackoverflow.com/q/52256085
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52256085
has body: You could try with pandas import pandas as pd df = pd.read_csv(filepath) df['id']=df.index df.to_csv(filepath) If the ID column does not appear in the desired position in the dataframe, you may have to reorder the columns in the dataframe before saving to csv.
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/91403130
comment on: http://stackoverflow.com/a/52207333
type: Comment
score: 1
has text: You can pass an argument to `read` to limit the number of bytes read. Read and process chunks until the file is done and sum the lengths like in your original.
type: AnswerComment

http://stackoverflow.com/comment/91479501
type: Comment
type: QuestionComment
has text: Okay so if I am understanding correctly then each time that I create an `__init__` method and declare as `__init__(self):` I am also creating an instance of the variable `self`. Do these instances of `self` remain independent of one another?
comment on: http://stackoverflow.com/q/52265615
score: 1

http://stackoverflow.com/a/52180953
answers question: http://stackoverflow.com/q/52180610
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: If it only changes in the admin, you can override the save_model on the admin and check the form's changed_data list: class OrderAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): if 'status_of_execution' in form.changed_data: if form.cleaned_data['status_of_execution'] == 'Done': # do stuff return super().save_model(request, obj, form, change)
type: Answer
accepted answer of: http://stackoverflow.com/q/52180610
score: 2

f-string
tags question: http://stackoverflow.com/q/52270145
tag name: f-string
type: Tag
tags question: http://stackoverflow.com/q/52248776

http://stackoverflow.com/q/52184407
has body: When I create a virtualenv for a Python project, it get's "polluted" by packages that I install for my convenience (like iPython or other packages that my editor "VS Code" depends on, like "pylint"). But these packages are not relevant for my project. So if I do pip freeze &gt; requirements.txt, I see that only a few packages are relevant for my project. What is the best way to clean up? Install those packages in a global context so that I can use them in every project I begin? or Do a pip freeze &gt; requirements.txt, then edit the requirements file and remove not needed packages?
has comment: http://stackoverflow.com/comment/91319085
upvote count: 3
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52184684
possible better answer: http://stackoverflow.com/a/52201137
type: Question
has answer: http://stackoverflow.com/a/52201137
answer count: 2
downvote count: 0
has title: Python: Packages that are not relevant for project
favorite count: 0
accepted answer: http://stackoverflow.com/a/52184684
tagged with: python

http://stackoverflow.com/comment/91497300
comment on: http://stackoverflow.com/q/52237376
has text: @Raman My question is not related to filename conventions, hence it is not duplicate.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52247021
has answer: http://stackoverflow.com/a/54377739
accepted answer: http://stackoverflow.com/a/54377739
tagged with: conda
answer count: 1
tagged with: jupyter-notebook
favorite count: 0
score: 8
has title: Jupyter Notebook Not Recognizing "import torch"
tagged with: pip
tagged with: python
type: AnsweredQuestion
has body: To install PyTorch on Ubuntu, as instructed by the official website, I did pip3 install torch torchvision, and I am able to run PyTorch using the python3.5 command. However, when I run Jupyter Notebook (I'm just running Jupyter Notebook in the terminal and using Chrome to access my notebooks), it doesn't recognize the package, throwing ModuleNotFoundError: No module named 'torch' at me. The other odd thing is that PyTorch seems to have only been installed on Python 3.5 and not on Python 3.6 because: ➜ ~ python3.5 -c "import torch; print(torch.__version__)" 0.4.1 ➜ ~ python3.6 -c "import torch; print(torch.__version__)" Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'torch' ➜ ~ Therefore I'm guessing that Jupyter Notebook is not using Python 3.5. This is the result when I type python in my terminal and press TAB: ➜ ~ python python python2.7 python3.5 python3.5m python3.6 python3.6m python3-config python3m-config python2 python3 python3.5-config python3.5m-config python3.6-config python3.6m-config python3m Also, when I run which python, I get /home/mhy/anaconda3/bin/python since I installed Anaconda recently. I then activated my env and installed PyTorch using the following commands: source activate my_env conda install torch torchvision But I wasnt able to run PyTorch on Anaconda either.
tagged with: anaconda
has comment: http://stackoverflow.com/comment/91442417
downvote count: 0
has comment: http://stackoverflow.com/comment/91452254
upvote count: 8
type: Question

http://stackoverflow.com/comment/91482921
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52267457
has text: is that the correct indentation level for `calc_average` or did it just get messed up when copied onto SO or ?
score: 0

http://stackoverflow.com/comment/91331655
type: Comment
comment on: http://stackoverflow.com/a/52190756
has text: Edited my post again
score: 0
type: AnswerComment

http://stackoverflow.com/a/52141634
answers question: http://stackoverflow.com/q/52141529
score: 0
type: Answer
has body: I agree with @JBallin , but instead of for i in range (0, len(word)): you can use for index,ch in enumerate(word): where index is from 0 to length of the word, and ch is the character itself

http://stackoverflow.com/comment/91357694
type: Comment
has text: So when I add print command it return [0,0] which means it doesn't actually make a vector.
type: AnswerComment
comment on: http://stackoverflow.com/a/52203093
score: 0

http://stackoverflow.com/comment/91315188
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52180942
score: 0
has text: "replace all values that are smaller than the top three different values".. aren't the largest three different values `9`, `8` and `7`? So you'd have to replace `4` and leave `7` in, or am I missing something?

http://stackoverflow.com/comment/95434508
comment on: http://stackoverflow.com/q/52149750
has text: [PDF was based on (or at least inspired by) PostScript](http://www.planetpdf.com/planetpdf/pdfs/warnock_camelot.pdf), so it is not surprising they look somewhat similar.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52248385
upvote count: 0
has body: So I have list that looks like this mylist = ['storeitem_1','storeitem_2','storeitem_3'] How would I go about getting only numbers from those strings? I tried following but it came out totally wrong. for items in mylist: print(items.split("storeitem_")) Any help is appreciated
has answer: http://stackoverflow.com/a/52248415
duplicate of: http://stackoverflow.com/q/4289331
type: UnansweredQuestion
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/52248418
score: -2
has answer: http://stackoverflow.com/a/52248404
tagged with: python-3.x
has title: Get only numbers from strings that are in the list
downvote count: 2
answer count: 3
tagged with: python
linked to: http://stackoverflow.com/q/4289331

http://stackoverflow.com/comment/91228166
has text: @Alan Maybe I am misinterpreting, but if your initial string is `Activity-Location-UserCode`, then `.str.rsplit('-', expand=True)[1]` would give you `Location` instead of `UserCode`.
type: Comment
comment on: http://stackoverflow.com/a/52139043
type: AnswerComment
score: 0

http://stackoverflow.com/q/52190644
favorite count: 0
has comment: http://stackoverflow.com/comment/91331455
type: Question
has body: address='''No-33-6,BEML Layout,Basaveshwaranagara 8th Main,Kamala Nagar,Near Academy Of Science and Knowledge,Bengaluru,Karnataka 560079''' I tried using below pattern.But .* matches all characters re.findall('[n][o].*',adress) Match based on first term that is No and last term 6 digits pincode/zipcode output:No-33-6,BEML Layout,Basaveshwaranagara 8th Main,Kamala Nagar,Near Academy Of Science and Knowledge,Bengaluru,Karnataka 560079
has comment: http://stackoverflow.com/comment/91331104
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/52190856
score: 0
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/52190810
has answer: http://stackoverflow.com/a/52190954
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91331273
has title: Regex pattern to split based on first and last words
tagged with: regex
tagged with: nlp

http://stackoverflow.com/comment/91342496
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/52196503
has text: That's good. Works in most cases - when values are addable for example. One exception is when default_values contains values for indices that are not in df. Then you get unwanted `NaN`s!

http://stackoverflow.com/a/52210292
accepted answer of: http://stackoverflow.com/q/52196276
answers question: http://stackoverflow.com/q/52196276
type: Answer
has body: I was able to solve my problem with: http://alexanderhoughton.co.uk/blog/lighttpd-changing-default-user-raspberry-pi/
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91276838
type: Comment
comment on: http://stackoverflow.com/a/52161167
has text: Thanks my friend. Solved. I was using student.detailinfo_set.all().filter(fourth_column="204X1001") but i removed the all() and now it is working as student.detailinfo_set.filter(fourth_column="204X1001")
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91335893
type: QuestionComment
has text: My advice is to work with a symbolic computation package to work out the log likelihood and formulas for uncertainty of estimates (via Hessian of likelihood function or something like that). Typically you can tell such packages to print a formula in a form which is easily parsed as a snippet of some other language (typically C or Fortran or some other ordinary language), so you can paste your derivations into another program. I work with Maxima (http://maxima.sourceforge.net) a lot, but you can also try Sympy (http://sympy.org), Sage, Axiom, or other systems.
comment on: http://stackoverflow.com/q/52187260
score: 0
type: Comment

http://stackoverflow.com/q/52192148
has title: Divide image to single objects (coins) for machine learning
has comment: http://stackoverflow.com/comment/91334176
has body: I want to automatically divide an image of multiple coins to the single coins, so that afterwards the single coins can be put into a model that classifies the coins (with Tensorflow/Keras). The input images look something like this And they should look like this (Sorry that I cannot integrate the images directly as I'm new to StackOverflow). I want to divide the input images, put the single coins into a classification model, so that I know the single value of the single coins and thereby can identify the value of the first input image. I already tried an object detection model, but it didn't detect coins (https://towardsdatascience.com/object-detection-with-10-lines-of-code-d6cb4d86f606). As I already know that all objects on the image are coins, I thought that there is maybe an easier way to divide the image? Thank you in advance.
tagged with: tensorflow
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/19385264
has comment: http://stackoverflow.com/comment/91337984
tagged with: keras
score: 0
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/62095083
has answer: http://stackoverflow.com/a/52193172
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/25789278
tagged with: machine-learning
tagged with: python
tagged with: computer-vision

http://stackoverflow.com/comment/91220724
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52135046
has text: Thank you, Now I think '-created' in order_by is redundant
type: AnswerComment

http://stackoverflow.com/comment/91458781
comment on: http://stackoverflow.com/a/52250350
score: 0
type: Comment
has text: Thanks you both, I fix my issue and now I understand the module <3
type: AnswerComment

http://stackoverflow.com/a/52334661
type: Answer
answers question: http://stackoverflow.com/q/52183357
score: 0
has body: I solved my problem, here is the solution : Build an url from an user input. Sorry for making it so confusing ! from flask import Flask, jsonify, render_template, request app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/generate', methods=['GET']) def generate(): prefix = request.args.get('prefix') urls = [] for number in range(1, 7): urls.append('https://example.com/{p}-{n}.jpg'.format(p=prefix, n=number)) return jsonify(result=urls) Html file : Image Grabber v1.0 Image Grabber v1.0 Download

http://stackoverflow.com/a/52197484
score: 2
has body: is checks if they are the same object(same place in memory) == checks if they are of equal value, low values are pre stored an thus point to the same memory space. for example, it would be stupid to write a new 1 and 0 every time it was needed just because it's for a new use, since those two numbers are being used so often so they just point to a prewritten datatable containing 1 and 0, among with low numbers and other often used values.
downvote count: 0
answers question: http://stackoverflow.com/q/52197459
type: Answer
upvote count: 2

http://stackoverflow.com/comment/91263782
type: AnswerComment
comment on: http://stackoverflow.com/a/52156681
score: 0
type: Comment
has text: Don't do searches for files unless necessary. Use `where.exe` to figure out what is on `PATH` to be found on Windows (`which` on Linux).

http://stackoverflow.com/q/52218288
answer count: 0
tagged with: ffmpeg
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91385124
tagged with: python
score: 2
has body: In Python I installed the library av (which is a Python API for ffmpeg) into my conda environment with conda install -c conda-forge av=0.4.0, but I when I import av into my python script, I get the error message ImportError: libx264.so.138: cannot open shared object file: No such file or directory on my Linux Kubuntu 14.4 machine. How can I resolve this issue? Wild guess: My Kubuntu repositories are a little old, so I cannot update ffmepg further and I guess this is why libx264 is missing, but am not sure.
has comment: http://stackoverflow.com/comment/91385156
downvote count: 0
type: Question
upvote count: 2
has title: Install dependencies for Python ffmpeg library "av" (ImportError: libx264.so missing)
has comment: http://stackoverflow.com/comment/91385242
has comment: http://stackoverflow.com/comment/91385822
has comment: http://stackoverflow.com/comment/91385414
tagged with: dependencies
favorite count: 0
has comment: http://stackoverflow.com/comment/91386118

http://stackoverflow.com/comment/91212256
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52130748
type: Comment
has text: Thanks, makes sense now

http://stackoverflow.com/q/52219988
has answer: http://stackoverflow.com/a/52400595
favorite count: 0
has comment: http://stackoverflow.com/comment/91388815
tagged with: python
has comment: http://stackoverflow.com/comment/91388617
has answer: http://stackoverflow.com/a/52331515
accepted answer: http://stackoverflow.com/a/52328603
type: AnsweredQuestion
has title: Python: how to replace NaN with conditions in a dataframe?
has comment: http://stackoverflow.com/comment/91388563
has answer: http://stackoverflow.com/a/52329287
possible better answer: http://stackoverflow.com/a/52220120
score: 7
has answer: http://stackoverflow.com/a/52220120
has body: I have a dataframe df1 that corresponds to the egelist of nodes in a network and value of the nodes themself like the following: df node_i node_j value_i value_j 0 3 4 89 33 1 3 2 89 NaN 2 3 5 89 69 3 0 2 45 NaN 4 0 3 45 89 5 1 2 109 NaN 6 1 8 109 NaN I want to add a column w that correspond to the value_j if there is the value. If value_j is NaN I would like to set w as the average of the values of the adjacent nodes of i. In the case that node_i has only adjacent nodes with NaN values set w=1. so the final dataframe should be like the foolowing: df node_i node_j value_i value_j w 0 3 4 89 33 33 1 3 2 89 NaN 51 # average of adjacent nodes 2 3 5 89 69 69 3 0 2 45 NaN 89 # average of adjacent nodes 4 0 3 45 89 89 5 1 2 109 NaN 1 # 1 6 1 8 109 NaN 1 # 1 I am doing a loop like the following but I would like to use apply: nodes = pd.unique(df['node_i']) df['w'] = 0 for i in nodes: tmp = df[df['node_i'] == i] avg_w = np.mean(tmp['value_j']) if np.isnan(avg_w): df['w'][idx] = 1 else: tmp.ix[tmp.value_j.isnull(), 'value_j'] = avg_w ## replace NaN with values df['w'][idx] = tmp['value_j'][idx]
tagged with: apply
upvote count: 7
type: Question
has comment: http://stackoverflow.com/comment/91388737
downvote count: 0
answer count: 6
tagged with: pandas
has answer: http://stackoverflow.com/a/52328603
has answer: http://stackoverflow.com/a/52328673

http://stackoverflow.com/comment/91386529
type: Comment
has text: the socket_receiver doesn't go over async with websockets.connect instruction, so only pipe works even if I removthe readline
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52200377

http://stackoverflow.com/q/52210121
has body: Input: import pandas as pd data = [['abc1',55,98,100],['abc2',56,97,101],['abc3',13,18,55],['abc4',56,79,100]] df = pd.DataFrame(data,columns=['Bus','Existing_Fare','Petrol_Price','Salary_Hike']) I need to apply this formula. IF Petrol_Price>80: Petrol_Price=80 else: Petrol_Price given in dataframe New Price = Existing_Fare+Petrol_Price+2*Salary_Hike 2.Ranking Correct Order. If two scores have same value then give them same rank Output Bus New_Price Rank_Order Rank_duplicates 0 abc1 335 1 2 1 abc2 338 2 1 2 abc3 141 3 3 3 abc4 335 4 2
accepted answer: http://stackoverflow.com/a/52210350
score: 0
has comment: http://stackoverflow.com/comment/91370320
answer count: 1
has comment: http://stackoverflow.com/comment/91370028
favorite count: 0
tagged with: pandas
tagged with: python
has title: How to apply formulas on condition to generate a new column and apply two types of ranking?
has comment: http://stackoverflow.com/comment/91369948
has comment: http://stackoverflow.com/comment/91369998
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52210350
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91370393

http://stackoverflow.com/q/52270808
type: Question
tagged with: dataframe
upvote count: 4
linked to: http://stackoverflow.com/q/23435270
downvote count: 0
score: 4
has title: create sub-index of groups with pandas and groupby
favorite count: 0
has comment: http://stackoverflow.com/comment/91488915
has comment: http://stackoverflow.com/comment/91489134
tagged with: pandas
has body: I have a dataframe that has an ID column and I would like to add a column to the dataframe is an index for each unique ID. I was able to do this using 2 for-loops with the example below by making a list from the ID count, converting it to an array, and adding it to the dataframe. However, I was hoping to simplify this using pandas groupby() instead and avoid using these 2 for-loops it's not too efficient. I tried playing around with groupby() and set_index() but I couldn't get anything to work. Does anybody know how I can simplify all these steps using pandas groupby()? df = pd.DataFrame({'ID': (4,4,4,5,6,7,7,7,7), 'Record': (1,4,5,1,1,1,5,7,8), 'color': ('b','r','r','r','r','b','b','b','b')}) ID Record color 4 1 b 4 4 r 4 5 r 5 1 r 6 1 r 7 1 b 7 5 b 7 7 b 7 8 b ############################################## ### Steps I did to add the make sub index ID to df def convert_to_sub_index_array(count_list): sub_ID_list = [] for c in count_list: for i in range(c): sub_ID_list.append(i+1) return np.asarray(sub_ID_list) ID_group=df.groupby(['ID']).count() ID_count = ID_group['Record'].values.tolist() sub_ID_index = convert_to_sub_index_array(ID_count) df['ID_index'] = sub_ID_index ################################################# ID Record color ID_index 4 1 b 1 4 4 r 2 4 5 r 3 5 1 r 1 6 1 r 1 7 1 b 1 7 5 b 2 7 7 b 3 7 8 b 4
has comment: http://stackoverflow.com/comment/91489222
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: data-cleaning
duplicate of: http://stackoverflow.com/q/23435270

http://stackoverflow.com/q/52117935
tagged with: django-views
tagged with: django-models
has answer: http://stackoverflow.com/a/52118030
accepted answer: http://stackoverflow.com/a/52118030
score: 0
answer count: 1
tagged with: python
has body: I'm getting started with Django and I'm having some trouble with query_sets and for loops. I have created a model and populated my DB with a few entries. In my views.py I have sent a count of these entries to my template and can see the result in HTML. However when I send a query_set list of these entries I cannot seem to access them and I am unsure as to why. Here is the view.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from website.models import Member # Create your views here. def index(request): """ View for the homepage of the site """ num_mem = Member.objects.count() mem_list = list(Member.objects.all()) context = { 'mem_list': mem_list, 'num_mem' : num_mem, } #render the HTML template index.html with the data return render(request, 'index.html', context=context) In index.html I attempt to access these as such. {% extends "base_generic.html" %} {% block content %} {{ num_mem }} {% for member in mem_list %} There are Members! {% empty %} Sorry can't find the members =/ {% endfor %} {% endblock %} The result returned is as shown. "6 Sorry can't find the members =/" So I can see the num_mem value and can see that there are currently 6 values there. The intention would be to loop through the members list and do something with each value e.g &lt;a href='{{member.m_name.contact_email}}'&gt; Contact {{member.m_name}} here...&lt;/a&gt; edit:I have changed the mem_list as advised however this has not resolved the issues sadly. Updated code. mem_list = Member.objects.all() I am using Django 1.11 and Python 2.7.5, thanks in advance for any help!
type: AnsweredQuestion
tagged with: django-templates
tagged with: django
has title: For 'model_object' in 'query_set_list' is showing empty. Django 1.11
type: Question

http://stackoverflow.com/comment/91209793
has text: It will spin up 1024 (=64*16) threads instead of just a single thread. But (if you made no other changes) each thread will execute **the exact same code** which is not what you want. You want each thread to execute the same code but with different parameters, such as different values of `i`, and that requires changes to the kernel code itself, to remove the for-loop(s) in `i`, and to replace it with a cuda thread index.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52123275

http://stackoverflow.com/a/63314215
has body: As an addition to rafaelc's answer, here are the according times (from quickest to slowest) for the following setup import numpy as np import pandas as pd s = pd.Series([x &gt; 0.5 for x in np.random.random(size=1000)]) Using np.where &gt;&gt;&gt; timeit np.where(s)[0] 12.7 µs ± 77.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) Using np.flatnonzero &gt;&gt;&gt; timeit np.flatnonzero(s) 18 µs ± 508 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) Using pd.Series.index The time difference to boolean indexing was really surprising to me, since the boolean indexing is usually more used. &gt;&gt;&gt; timeit s.index[s] 82.2 µs ± 38.9 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) Using boolean indexing &gt;&gt;&gt; timeit s[s].index 1.75 ms ± 2.16 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) If you need a np.array object, get the .values &gt;&gt;&gt; timeit s[s].index.values 1.76 ms ± 3.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) If you need a slightly easier to read version &lt;-- not in original answer &gt;&gt;&gt; timeit s[s==True].index 1.89 ms ± 3.52 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) Using pd.Series.where &lt;-- not in original answer &gt;&gt;&gt; timeit s.where(s).dropna().index 2.22 ms ± 3.32 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) &gt;&gt;&gt; timeit s.where(s == True).dropna().index 2.37 ms ± 2.19 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) Using pd.Series.mask &lt;-- not in original answer &gt;&gt;&gt; timeit s.mask(s).dropna().index 2.29 ms ± 1.43 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) &gt;&gt;&gt; timeit s.mask(s == True).dropna().index 2.44 ms ± 5.82 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) Using list comprehension &gt;&gt;&gt; timeit [i for i in s.index if s[i]] 13.7 ms ± 40.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) Using Python's built-in filter &gt;&gt;&gt; timeit [*filter(s.get, s.index…
answers question: http://stackoverflow.com/q/52173161
upvote count: 33
type: Answer
downvote count: 0
score: 33

http://stackoverflow.com/q/52195903
has comment: http://stackoverflow.com/comment/91341836
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/52195976
possible better answer: http://stackoverflow.com/a/52196227
has answer: http://stackoverflow.com/a/52196227
has comment: http://stackoverflow.com/comment/91341856
tagged with: python
has body: I'm very new to Python or any programming language in general. For reference: Assignment My Code Question 1.) The assignment for my class is this: read from text file 'word.txt' and write into a new text file the words from the first text file that fit the criteria. For example, if the function is getListEnd('s', 'word.txt', 'word1.txt') and the criteria is that the words in the ofile must all end with the character 's' then my ifile word.txt=[apples, carrots, cheese, mustard, problems] would be sorted into an ofile word1.txt=[apples, carrots, problems] 2.) Here is my code: mf1 = open("/Users/XXXX/word.txt", "r") mf2 = open("/Users/XXXX/word2.txt", "w+") mylist1=[] #list for storing word.txt strings mylist2=[] #list for storing sorted strings def sort(c): #function for sorting mylist1 for for i in mylist1: criteria into my list2 if c==i[-1]: mylist2.append(i) def getListEnd(c, ifile, ofile): for s in mf1: #loop for appending word.txt to list 1 mylist1.append(s) print(len(mylist1)) #check if mylist1 contains word.txt sort(c) #append sorted words to list2 with open('word2.txt', 'w+') as mf2: #write into word1.txt list2 for listitem in mylist2: mf2.write('%s\n' % listitem) getListEnd('s', 'word.txt', 'word2.txt') 3.) So the question is: why is it that whenever I try to append into mylist2 the sorted words nothing happens? That is, when I check the length of mylist2 it says 0 even though there are many words in the word.txt file that end in s? I know that there is an error in checking myList1 for characters that end with the last letter 's' but I don't know what and I can't get it to append to mylist2.
has title: Cannot append conditional result to new list
tagged with: append
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52196280
tagged with: file
has answer: http://stackoverflow.com/a/52195976
type: Question

http://stackoverflow.com/comment/91370344
has text: how many questions have you got here? I have counted at least 6 of them.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52210355

http://stackoverflow.com/comment/91227060
type: QuestionComment
has text: Yes, that seems to answer it. So all I can do is work on a workaround for that then it seems
comment on: http://stackoverflow.com/q/52138630
score: 0
type: Comment

http://stackoverflow.com/q/52144763
tagged with: video
has answer: http://stackoverflow.com/a/52166232
tagged with: tensorflow
type: Question
tagged with: image
score: 0
answer count: 1
has title: how to make a flash effect of a image?
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
has body: In tensorflow, there is a adjust_brightness API that is quite convenient to augment training data by changing the brightness. My question is how does adjusting to higher brightness different from a real flash? I read a paper that has this augmentation method that adds artificial flash effect to a frame by converting to LUV color space and increasing the intensity by 70%. I am not sure how does this relate to the adjust brightness function? Thanks!

http://stackoverflow.com/q/52195635
tagged with: python-3.x
type: UnansweredQuestion
has title: Python: Searching Values in a list
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/52195835
tagged with: list
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/45180899
has comment: http://stackoverflow.com/comment/91340920
type: Question
has comment: http://stackoverflow.com/comment/91340890
has body: I have the following set-up: stuff = ['apple', 'I like apples today', 'orange', 'oranges and apples guys'] What I want to do: I want to search each value in a list to see if the word "orange" is contained anywhere within that lists index value. In other words, my expected output is this: orange oranges and apples guys What I am currently getting back is nothing. Here is what I am currently doing: for x in range(0, len(stuff), 1): if 'orange' in stuff[x] == True: print('testing to see if this works') I am not successful with this, any suggestions? Edit #1: I tried searching for the contains syntax to use with the re module, but did not return anything useful. Edit #2: What about for cases like this: stuff = ['crabapple'] 'apple' in stuff False The word "apple" does exist, it's just part of another word. In this case, I'd like to return that as well.
has answer: http://stackoverflow.com/a/52195787
has answer: http://stackoverflow.com/a/52195791
has comment: http://stackoverflow.com/comment/91342448
has comment: http://stackoverflow.com/comment/91341122
downvote count: 0
has comment: http://stackoverflow.com/comment/91341278
has answer: http://stackoverflow.com/a/52195737
has comment: http://stackoverflow.com/comment/91340903
favorite count: 0

http://stackoverflow.com/comment/91340511
has text: +Reblochon Masque : It works. Your solution is actually very similar to mine. Thanks.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52158526
type: AnswerComment

http://stackoverflow.com/q/52205558
accepted answer: http://stackoverflow.com/a/52205629
upvote count: 15
possible better answer: http://stackoverflow.com/a/71613215
has answer: http://stackoverflow.com/a/71613215
has title: jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got 'posted'
has answer: http://stackoverflow.com/a/78613673
tagged with: flask
favorite count: 0
answer count: 5
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: AnsweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/52205710
score: 13
has body: I'm new to programming and recently a friend of mine gave me a project to work on in order to get myself familiar with the programming environment and language (python in this particular example). https://www.youtube.com/watch?v=QnDWIZuWYW0 I used this video as a beginners tutorial to help me understand how i'm supposed to proceed with my personal project. the code i wrote is exactly how it is written in the video, and i get an error. from flask import Flask, render_template app = Flask(__name__) posts = [ { 'author': 'Alon Salzmann', 'title': 'First Post', 'content': 'First post content', 'date posted': 'September 5, 2018' }, { 'author': 'Alon Salzmann', 'title': 'Second Post', 'content': 'Second post content', 'date posted': 'September 6, 2018' } ] @app.route("/") def homepage(): return render_template('Home.html', posts=posts) @app.route("/about") def about(): return render_template('About.html') if __name__ == '__main__': app.run(debug=True) The code above is the python code I wrote, and the code below is the html code I wrote that involves python: {% for post in posts %} {{ post.title }} By {{ post.author }} on {{ post.date posted }} {{ post.content }} {% endfor %} after running the program on both cmd and powershell (not simultaneously of course), and going to my localhost address, i got the error that appears in the title: jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got 'posted' I would love to get a good explanation as to why this has been happeninig, and how to fix this. Please remember I am a beginner and maybe need to be explained a few basic concepts at first :). P.S. The guy's code in the video worked so I would love to understand where I went wrong.
has answer: http://stackoverflow.com/a/52205629
has answer: http://stackoverflow.com/a/76341835
type: Question

http://stackoverflow.com/comment/91298561
comment on: http://stackoverflow.com/q/52173203
score: 0
type: QuestionComment
type: Comment
has text: How did you end up with what is clearly a mix of 6 linear trends, while the vehicle under examination likely has a 5-speed transmission, judging by by your code example (it sets `k=5`)?

http://stackoverflow.com/q/52231539
answer count: 1
tagged with: maya
tagged with: mel
has answer: http://stackoverflow.com/a/52232646
has title: Pass instance name as argument from several UI controls to a single function in Python-Maya
tagged with: python
tagged with: pymel
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/52232646
type: Question
has body: I'm developing a UI in python for maya, and I'm trying to do a function that performs an action when a frameLayout expands, in this case I have several "frameLayout" objects and I would like to use a single function "fl_expand", instead of one for each object def fl_expand(*args): print args with frameLayout("layout1", collapsable=True, expandCommand=fl_expand): ... with frameLayout("layout2", collapsable=True, expandCommand=fl_expand): ... but I don't know how to pass the instance name as argument to the function, I tried: with frameLayout("layout1", collapsable=True, expandCommand=fl_expand("layout1")): ... But of course I get this error: # Error: TypeError: file /usr/autodesk/maya2018/lib/python2.7/site-packages/pymel/internal/pmcmds.py line 134: Invalid arguments for flag 'ec'. Expected string or function, got NoneType #

http://stackoverflow.com/comment/91286910
comment on: http://stackoverflow.com/q/52167706
has text: @JPG, You are right, but in my case i need to exclude = user , and include=user_id
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91281813
type: QuestionComment
comment on: http://stackoverflow.com/q/52165826
has text: I mean _after_ seeking back to rewind the file.
score: 0
type: Comment

http://stackoverflow.com/a/52125313
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52124441
type: Answer
has body: Your derived table has no name, or in other words the union expression is missing an alias in the FROM clause. Try: q3 = q1.union_all(q2).alias() which will add the required AS.
score: 0
answers question: http://stackoverflow.com/q/52124441

http://stackoverflow.com/q/52212719
type: Question
tagged with: byte
tagged with: struct.pack
tagged with: python
has comment: http://stackoverflow.com/comment/91375610
score: 0
has body: I want to "unpack" OR de-serialize the formatted data that is outputed from python's struct.pack() function. The data is sent over the network to another platform that uses Java only. The Python function that sends data over the network, uses this formater: def formatOutputMsg_Array(self, mac, arr): mac_bin = mac.encode("ascii"); mac_len = len(mac_bin); arr_bin = array.array('d', arr).tobytes(); arr_len = len(arr_bin); m = struct.pack('qqd%ss%ss' % (mac_len, arr_len), mac_len, arr_len, time.time(), mac_bin, arr_bin); return m Here are the docs for python's struct (refer to section 7.3.2.2. Format Characters): https://docs.python.org/2/library/struct.html 1) The issue is what does 'qqd%ss%ss' mean ??? Does it mean -> long,long,double,char,char,[],char[],char,char[],char[] 2) why is modulo "%" used here with a tuple 'qqd%ss%ss' % (mac_len, arr_len) ?
accepted answer: http://stackoverflow.com/a/52212753
answer count: 1
has title: unpacking pythons struct.pack in another language
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52212753

http://stackoverflow.com/comment/91218510
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52134151
has text: I do know KV, but i prefer pure python.
score: 0

http://stackoverflow.com/comment/91233504
score: 1
type: QuestionComment
type: Comment
has text: @WillCole Okay, good. Your interpreter has a weird font. Which is just one more reason that you should always post text here, as others have requested, not pictures.
comment on: http://stackoverflow.com/q/52141709

http://stackoverflow.com/comment/91273876
type: Comment
type: QuestionComment
has text: Make sure that the previous execution is completed before triggering the new run. If the previous instance of the program is still running ,then it might create this issue
score: 0
comment on: http://stackoverflow.com/q/52162046

http://stackoverflow.com/a/52266425
has comment: http://stackoverflow.com/comment/91480903
has comment: http://stackoverflow.com/comment/91481071
score: 0
answers question: http://stackoverflow.com/q/52265795
type: Answer
has comment: http://stackoverflow.com/comment/91481945
has comment: http://stackoverflow.com/comment/91480790
has body: There is no need for specifying the input_shape argument in the second recurrent layer. This parameter is expressly required when the recurrent layer is the first layer in the network, but not otherwise. If you wish to specify the input batch shape at each recurrent layer, remember to set the parameter stateful = True to render your LSTMs stateful(and only use this argument at the first layer of your network).
has comment: http://stackoverflow.com/comment/91481034
has comment: http://stackoverflow.com/comment/91480779
has comment: http://stackoverflow.com/comment/91480798
has comment: http://stackoverflow.com/comment/91480849

http://stackoverflow.com/q/52247428
has comment: http://stackoverflow.com/comment/91479556
has answer: http://stackoverflow.com/a/65208534
tagged with: twitter
has comment: http://stackoverflow.com/comment/91471259
score: 4
answer count: 2
has body: I was trying to do some data mining with twitter and ran into this problem. Python keeps converting the tweet's large numerical id's to scientific notation when I try to write it to a CSV file. For example, if the ID was 9381435503399854 python will convert it to 9.381435503399854E+17. I tried using format(int(tweet.id), ".0f") but it is giving me the same result. Format(int(tweet.id), "f") seems like it works but appends ".000000" to the end of the id. Any suggestions would be greatly appreciated. Here is some sample code: writeExtended(count, tweet.id, tweet.full_text.encode('utf8'), tweet.display_text_range, tweet.created_at) def writeExtended(id, idstr, full_text, display_text_range, created_at): #Write Extended tweet details to CSV file with open('Extended.csv', mode='a+') as employee_file: employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) employee_writer.writerow([id,idstr, full_text, display_text_range, created_at])
tagged with: variables
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91491295
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
upvote count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52273633
accepted answer: http://stackoverflow.com/a/52273633
downvote count: 0
has comment: http://stackoverflow.com/comment/91471443
has comment: http://stackoverflow.com/comment/91461466
has title: Python converting tweepy tweet and user IDs to scientific notation
type: Question
possible better answer: http://stackoverflow.com/a/65208534

http://stackoverflow.com/comment/91502070
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52256480
has text: thank @khelili miliana ___ Sorry I did not explain my question well I wanted to say (if self.date_transfer <= self.create_date ) was replaced by state 'done" ; I mean before all >>>> [https://stackoverflow.com/questions/52261821/update-fields-from-other-fields-after-date-odoo]

http://stackoverflow.com/comment/91388615
comment on: http://stackoverflow.com/q/52219956
type: Comment
type: QuestionComment
has text: How did you declare `log`?
score: 0

http://stackoverflow.com/comment/91425871
score: 0
comment on: http://stackoverflow.com/q/52238507
has text: @abarnert: I think `line` is kind of risky for lots of reasons, one of them being that I don't want to miss lambdas (I didn't think to include that in the question but I should have said I want to hook function creation). `opcode` seems to be what I want though :)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91411790
score: 0
has text: @MichaelButscher ok thank you for help, one last question: `res=req.json()` is not working `x=req.text` is working but giving ouput like this - how to extarct access token from there ` jqUb-QG7n3lZp494Gm8lRH9-9iz0xm2WxR_XHXQ4LFE. `
comment on: http://stackoverflow.com/q/52230875
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91454979
type: Comment
comment on: http://stackoverflow.com/a/52253716
has text: @Onyambu but why? :p
score: 1
type: AnswerComment

http://stackoverflow.com/comment/91260619
score: 0
type: AnswerComment
type: Comment
has text: Thanks @MattMessersmith see my edited answer for more information.
comment on: http://stackoverflow.com/a/52153801

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/52181799
tags question: http://stackoverflow.com/q/52263978
type: Tag

asynchronous-method-call
type: Tag
tags question: http://stackoverflow.com/q/52174867
tag name: asynchronous-method-call

communication
tag name: communication
tags question: http://stackoverflow.com/q/52173409
type: Tag

http://stackoverflow.com/comment/91402578
type: Comment
comment on: http://stackoverflow.com/a/52226158
score: 1
type: AnswerComment
has text: These are braces: `{}`. They are sometimes called curly brackets. These are brackets: `[]`, sometimes called square brackets when there could be confusion otherwise.

http://stackoverflow.com/comment/91303364
score: 0
type: Comment
type: AnswerComment
has text: That being said, I've posted an alternative solution.
comment on: http://stackoverflow.com/a/52176231

http://stackoverflow.com/comment/91449004
has text: Whta do you mean by "every time you run programe. you will get same sequence of three numbers" ?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52250538

http://stackoverflow.com/comment/91307816
score: 0
type: Comment
type: QuestionComment
has text: Can you provide more code for your problem? And why is "cast op not supported"? That seems very strange.
comment on: http://stackoverflow.com/q/52171143

http://stackoverflow.com/comment/91335706
type: Comment
has text: I agree, although I honestly don't know anything about `itertools` save for a few of the simple functions.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52187455

http://stackoverflow.com/a/52216629
score: 1
downvote count: 0
has body: As per the docs, the model.objects.raw() method is intended for running queries that return model instances. See this example from the docs: &gt;&gt;&gt; for p in Person.objects.raw('SELECT * FROM myapp_person'): ... print(p) John Smith Jane Jones Consequently, if the result of your stored procedure is to be converted into instances of some of your models, you probably should use raw(). Otherwise, you should work with cursor objects because raw() will do unnecessary work to convert the result into Django model instances. Speaking of your other concerns: readability: same as above, this depends on whether your procedure returns data to populate model instances; protection from attacks: no difference between the two options, as both of them allow for parameter interpolation, which is injection-safe.
type: Answer
answers question: http://stackoverflow.com/q/52215941
upvote count: 1

http://stackoverflow.com/a/52228619
has body: You can use re.split to split a string with a regex. import re def get_upper_sequences(s): return re.split(r'\s+[a-z][a-z\s]*', s) Example &gt;&gt;&gt; get_upper_sequences( "A B c de F G A") ['A B', 'F G A']
answers question: http://stackoverflow.com/q/52228525
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/91298932
comment on: http://stackoverflow.com/q/52172724
score: 0
type: Comment
type: QuestionComment
has text: Question edited to reflect changes requested

http://stackoverflow.com/q/52196219
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/127604232
has body: I am porting a python project (s3 + Athena) from using csv to parquet. I can make the parquet file, which can be viewed by Parquet View. I can upload the file to s3 bucket. I can create the Athena table pointing to the s3 bucket. However, when I query the table at Athena Web GUI, it runs for 10 mins (it seems that it will never stop) and there is no result shown. The whole project is complicated. I try to simplify the case. 1.Let say, we have the following csv file (test.csv) "col1","col2" "A","B" 2.Then, I use the following python (2.7) code to convert it to parquet file (test.parquet) import fastparquet import pandas as pd df = pd.read_csv(r"test.csv") fastparquet.write(r"test.parquet", df, compression="GZIP") 3.Upload the test.parquet to s3 bucket folder "abc_bucket/abc_folder" by the s3 Web GUI 4.Create the following table by Athena Web GUI CREATE EXTERNAL TABLE IF NOT EXISTS abc_folder ( `col1` string, `col2` string) STORED AS PARQUET LOCATION 's3://abc_bucket/abc_folder/' TBLPROPERTIES ( "parquet.compress"="GZIP" ); 5.Finally, run the following SQL at Athena. The SQL runs for 10 mins and seems forever. select * from abc_folder; My question is which step above is wrong so that I cannot query the table from Athena. It is highly appreciated for any help.
has comment: http://stackoverflow.com/comment/127580175
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/127564927
has comment: http://stackoverflow.com/comment/91344474
favorite count: 0
has answer: http://stackoverflow.com/a/67406161
tagged with: amazon-athena
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/127587843
has title: How can Athena read parquet file from S3 bucket
has comment: http://stackoverflow.com/comment/91342519
tagged with: parquet
downvote count: 0
has comment: http://stackoverflow.com/comment/127662849
score: 1
has answer: http://stackoverflow.com/a/53080663
type: Question
tagged with: fastparquet

http://stackoverflow.com/q/52151121
accepted answer: http://stackoverflow.com/a/52151354
favorite count: 0
has title: How to make python create N strings without defining all of them manually?
tagged with: python
has comment: http://stackoverflow.com/comment/91253564
type: AnsweredQuestion
has body: Now I want to run multiple test cases one by one and display the output together line by line. n=input() for i in range (0,int(n)): #takes input and runs the code #stores output in a string #prints output for all n cases one by one How can I make the program to store N outputs of N different test cases in N different strings without actually defining N strings myself??
linked to: http://stackoverflow.com/q/20109391
linked to: http://stackoverflow.com/q/5963269
downvote count: 2
has answer: http://stackoverflow.com/a/52151354
type: Question
score: -2
upvote count: 0
answer count: 1

http://stackoverflow.com/q/52225216
type: Question
tagged with: debugging
has title: Pretty print a pandas dataframe in VS Code
tagged with: visual-studio-code
has answer: http://stackoverflow.com/a/65883166
tagged with: dataframe
answer count: 6
has answer: http://stackoverflow.com/a/78127381
has answer: http://stackoverflow.com/a/71833515
upvote count: 43
possible better answer: http://stackoverflow.com/a/58848201
tagged with: pandas
has answer: http://stackoverflow.com/a/58848201
downvote count: 0
has answer: http://stackoverflow.com/a/54560389
favorite count: 0
has answer: http://stackoverflow.com/a/55416034
accepted answer: http://stackoverflow.com/a/65883166
tagged with: python
type: AnsweredQuestion
score: 43
has body: I'd like to know if it's possible to display a pandas dataframe in VS Code while debugging (first picture) as it is displayed in PyCharm (second picture) ? Thanks for any help. df print in vs code: df print in pycharm:

http://stackoverflow.com/a/52164352
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52163959
has comment: http://stackoverflow.com/comment/91278500
has body: You need to provide a parse_mode Parameter (parse_mode="Markdown"). Or else you will not see any markdown style. sendMessage(chat_id, "*this text is bold*", parse_mode= 'Markdown') See https://telepot.readthedocs.io/en/latest/reference.html#telepot.Bot.sendMessage
answers question: http://stackoverflow.com/q/52163959
score: 15
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91278444
type: Answer
upvote count: 15
has comment: http://stackoverflow.com/comment/91279167

http://stackoverflow.com/a/52237614
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52235475
score: 1
has body: Everything except the rows beyond the last value is trivial: it's simply df["inside"] = df.lf.interpolate("linear", limit_area="inside") To handle the extrapolation at the end, we can forward-fill the difference between the interpolated values and then take the cumulative sum to get back to the original values: delta = df.lf.interpolate("linear", limit_area="inside").diff().ffill() df["rebuilt"] = delta.fillna(df.lf).cumsum() which gives me lf seed inside rebuilt 2476 5680.89225 5680.892250 5680.892250 5680.892250 2477 NaN 5682.184530 5682.184530 5682.184530 2478 NaN 5683.476810 5683.476810 5683.476810 2479 NaN 5684.769090 5684.769090 5684.769090 2480 NaN 5686.061370 5686.061370 5686.061370 2481 5687.35365 5687.353650 5687.353650 5687.353650 2482 NaN 5686.913100 5686.913100 5686.913100 2483 NaN 5686.472550 5686.472550 5686.472550 2484 NaN 5686.032000 5686.032000 5686.032000 2485 NaN 5685.591450 5685.591450 5685.591450 2486 5685.15090 5685.150900 5685.150900 5685.150900 2487 NaN 5685.141110 5685.141110 5685.141110 2488 NaN 5685.131320 5685.131320 5685.131320 2489 NaN 5685.121530 5685.121530 5685.121530 2490 NaN 5685.111740 5685.111740 5685.111740 2491 5685.10195 5685.101950 5685.101950 5685.101950 2492 NaN 5681.444686 5681.444686 5681.444686 2493 NaN 5677.787421 5677.787421 5677.787421 2494 NaN 5674.130157 5674.130157 5674.130157 2495 NaN 5670.472893 5670.472893 5670.472893 2496 NaN 5666.815629 5666.815629 5666.815629 2497 NaN 5663.158364 5663.158364 5663.158364 2498 5659.50110 5659.501100 5659.501100 5659.501100 2499 NaN 5658.118262 5658.118263 5658.118263 2500 NaN 5656.735425 5656.735425 5656.735425 2501 NaN 5655.352587 5655.352588 5655.352588 2502 5653.96975 5653.969750 5653.969750 5653.969750 2503 NaN 5652.586912 NaN 5652.586912 2504 NaN 5651.204075 NaN 5651.204075 2505 NaN 5649.821237 NaN 5649.821237 and In [126]: np.allclose(df["rebuilt"], df["seed"]) Out[126]: True Note: I've assumed that there aren't any NaN values at the top of the series. We could handle th…
has comment: http://stackoverflow.com/comment/91426902
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91429420
has comment: http://stackoverflow.com/comment/91429235
has comment: http://stackoverflow.com/comment/91426962
accepted answer of: http://stackoverflow.com/q/52235475
has comment: http://stackoverflow.com/comment/91428085

http://stackoverflow.com/comment/91302821
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52176199
has text: Python 2 or Python 3?
score: 1

tcp
type: Tag
tags question: http://stackoverflow.com/q/52143232
tags question: http://stackoverflow.com/q/52206450
tag name: tcp

http://stackoverflow.com/q/52159977
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52160101
score: -1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52160101
upvote count: 0
linked to: http://stackoverflow.com/q/39038358
favorite count: 0
tagged with: functional-programming
possible better answer: http://stackoverflow.com/a/52160176
has body: My question is closely related to the question here: Function chaining in Python , which is the "A chain adding function" problem on CodeWars. There're many useful solutions in the link, but I just want to find out what's wrong with my own solution. The first thing that comes up to my mind is using Currying, for example def add(a): def add2(b): return b + a return add2 add(1)(2) will give me 3 as output. Now I want to add recursion so that add(1), add(1)(2)(3) and add(1)(2)(3)(4) etc. can also work as expected: def add(a): if not callable(a): return a else: def add2(b): return b + add(a) return add2 This time add(1) returns 1 as expected, but add(1)(2), add(1)(2)(3) etc. gives me error: TypeError: 'int' object is not callable Can anyone point out what's wrong here? Furthermore, how to resolve it? Thanks a lot for any help!
has title: Currying and Recursion
has comment: http://stackoverflow.com/comment/91269831
has answer: http://stackoverflow.com/a/52160176
tagged with: python
downvote count: 1

http://stackoverflow.com/comment/91475534
comment on: http://stackoverflow.com/q/52263399
has text: Where does the validation data come from? Another csv?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52201796
favorite count: 0
has title: Meaning of return HttpResponse("")
tagged with: python
has body: In python, what the meaning of the below code if written in a function return HttpResponse("")
has answer: http://stackoverflow.com/a/52202024
downvote count: 5
type: UnansweredQuestion
score: -4
tagged with: django
has comment: http://stackoverflow.com/comment/91356735
type: Question
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/91436751
comment on: http://stackoverflow.com/q/52244225
has text: Yes, it works for the sample cases.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52134584
score: 0
has title: How to compute actual spectrogram from decomposed spectogram of an audio file?
has comment: http://stackoverflow.com/comment/91219774
type: UnansweredQuestion
tagged with: python
tagged with: audio-analysis
has comment: http://stackoverflow.com/comment/91220644
type: Question
has answer: http://stackoverflow.com/a/52682989
linked to: http://stackoverflow.com/q/44787437
answer count: 1
has body: I decomposed the spectrogram from an audio file like this: import librosa y, sr = librosa.load('my audio file.wav') S = np.abs(librosa.stft(y)) W, H = librosa.decompose.decompose(S, n_components=32) Now how to recompose the decomposed spectrogram to actual spectogram. What i want is like this type of functionality: S=recompose(W,H)

http://stackoverflow.com/q/52270916
has answer: http://stackoverflow.com/a/78325746
tagged with: python
type: AnsweredQuestion
tagged with: qcombobox
tagged with: pyqt5
type: Question
accepted answer: http://stackoverflow.com/a/52271167
upvote count: 9
has body: In my program some comboboxes (QComboBox) were used to make several settings. Sometimes its necessary not only to know the item the user selected but also the item which was selected previously in the combobox. Well, transferring the new selection is quite easy: self.MyCombobox.activated[str].connect(self.ComboChange) But how do i manage to not only passing the newly selected but also the previous item to a function when the index changed? My compromise solution would be to manually set a variable for every combobox which stores the last selected value so that it can be accessed when the selction has changed. But considering that i have a lot of Comboboxes this would be quite prone to errors until some boxes could be updated on different ways. Thanks in advance for your help A minimal working example: import sys from PyQt5.QtWidgets import ( QApplication, QWidget, QGridLayout, QComboBox, QLabel) class BaseWidget(QWidget): def __init__(self): super(BaseWidget, self).__init__() self.setGeometry(300, 300, 300, 200) # 2 Labels to display the new and the old item after selection self.LabelOldItem = QLabel(self) self.LabelNewItem = QLabel(self) self.MyCombobox = QComboBox(self) self.MyCombobox.addItems(['Item 1', 'Item 2', 'Item 3', 'Item 4']) self.MyCombobox.activated[str].connect(self.ComboChange) grid = QGridLayout() grid.addWidget(self.MyCombobox, 0, 0, 1, 1) grid.addWidget(self.LabelOldItem, 1, 0, 1, 1) grid.addWidget(self.LabelNewItem, 2, 0, 1, 1) self.setLayout(grid) def ComboChange(self, newitem): self.LabelOldItem.setText('Previous Selection: ') # &lt;- crucial point # How can i transfer both, not only the new item but also the previous # item of the combobox when it gets activated? self.LabelNewItem.setText('New Selection: &lt;b&gt;' + newitem + '&lt;/b&gt;') if __name__ == '__main__': app = QApplication(sys.argv) pyqtComboExample = BaseWidget() pyqtComboExample.show() sys.exit(app.exec_())
score: 9
answer count: 2
tagged with: pyqt
downvote count: 0
has title: Get previous and newly selected item on activation in QComboBox
favorite count: 0
possible better answer: http://stackoverflow.com/a/78325746
has answer: http://stackoverflow.com/a/52271167

http://stackoverflow.com/q/52265195
has comment: http://stackoverflow.com/comment/91478596
has title: Update global variable inside a function inside a method
score: 2
has comment: http://stackoverflow.com/comment/91478479
has comment: http://stackoverflow.com/comment/91478637
upvote count: 3
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91478543
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52265289
has comment: http://stackoverflow.com/comment/91478419
possible better answer: http://stackoverflow.com/a/52265365
has answer: http://stackoverflow.com/a/52265365
has body: I have a function inside a method of a class like this: class A(): def run(self): exit=False def walk(): global exit #DoStuff - change exit variable walk() print(exit) Now, the function walk should change the exit variable. But this variable is outside of the function always False like set before. How can I change this variable using as a flag to access this outside the function if this function set this varibale to True? I am rather confused about the scope of this variable. I use python 3.6.
answer count: 2
favorite count: 0
accepted answer: http://stackoverflow.com/a/52265289
tagged with: scope
has comment: http://stackoverflow.com/comment/91478411
tagged with: python
has comment: http://stackoverflow.com/comment/91478488

http://stackoverflow.com/comment/91451935
score: 0
type: QuestionComment
has text: `lower()` is not an attribute of a `list`. Try converting it to a `numpy` array. Then `.lower()` should work.
type: Comment
comment on: http://stackoverflow.com/q/52252107

http://stackoverflow.com/comment/91512115
type: Comment
comment on: http://stackoverflow.com/a/52275334
has text: This is helpful, i tried the prefix-suffix way , but the customer is bent on adding headers.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52141631
type: UnansweredQuestion
tagged with: excel
type: Question
score: 0
has title: Typeerror with filename
has body: I'm getting the following error with line 18 - "TypeError: Open() got an unexpected keyword argument 'filename2'". Can someone help me figure out what I am doing wrong?Thanks in advance import os import win32com.client path = r'XXX' pathmaster = r'XXX\MyFile.xlsx' filename=pathmaster xl = win32com.client.DispatchEx('Excel.Application') xl.Visible = False wbmaster = xl.Workbooks.Open(filename) sheets = os.listdir(path) for sheet in sheets: print(sheet) wb1=xl.Workbooks.Open(filename2 = os.path.join(path,sheet)) ws1 = wb1.Worksheets("Val") ws1.Name=sheet[:4] ws1.Copy(Before=wbmaster.Worksheets(1)) wb1.Close(True) wbmaster.Close(SaveChanges=True)
has comment: http://stackoverflow.com/comment/91233065
tagged with: python
has comment: http://stackoverflow.com/comment/91233248
has comment: http://stackoverflow.com/comment/91233053
answer count: 0

http://stackoverflow.com/comment/115177200
score: 0
type: Comment
has text: Asked here, thanks - https://stackoverflow.com/questions/65148708/testing-a-cloud-function-from-trigerring-event-option
comment on: http://stackoverflow.com/a/52250030
type: AnswerComment

http://stackoverflow.com/q/52145568
has comment: http://stackoverflow.com/comment/91241087
has answer: http://stackoverflow.com/a/52145630
possible better answer: http://stackoverflow.com/a/52145778
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52146699
answer count: 3
has title: Slicing the substring from the string in each row of the column using Python
accepted answer: http://stackoverflow.com/a/52145630
score: 2
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question
tagged with: pandas
has answer: http://stackoverflow.com/a/52145778
has body: I am absolute beginner. I have a problem in slicing string in a Excel file using Python. My Excel file contains the following info: Column 1: ordercode PMC11-AA1L1FAVWJA PMC21-AA1A1CBVXJA PMP11-AA1L1FAWJJ PMP21-AA1A1FBWJJ PMP23-AA1A1FA3EJ+JA PTP31B-AA3D1HGBVXJ PTC31B-AA3D1CGBWBJA PTP33B-AA3D1HGB1JJ I want to slice the string in column "ordercode" based on whether it is "PMC11"/"PMC21"/"PMP21"/"PMP11"/"PMP23"/"PTP31B"/"PTP33B"/"PTC31B" at different position and save it in new column "pressurerange". In Excel I have used the below code and it worked fine: =IF(OR(ISNUMBER(SEARCH("PMC11",A2)),ISNUMBER(SEARCH("PMC21",A2)),ISNUMBER(SEARCH("PMP11",A2)),ISNUMBER(SEARCH("PMP21",A2)),ISNUMBER(SEARCH("PMP23",A2))),MID(A2,11,2),MID(A2,12,2)) but in Python I used the below coding, and it didn't work properly. Python Code: import pandas as pd #Assigning the worksheet to file file="Stratification_worksheet.xlsx" #Loading the spreadsheet data= pd.ExcelFile(file) #sheetname print(data.sheet_names) #loading the sheetname to df1 df=data.parse("Auftrag") print(df) #creating a new column preessurerange and slicing the pressure range from order code for index,row in df.iterrows(): if "PMC11" in df.loc[index,"ordercode"]: df["pressurerange"]=df["ordercode"].str.slice(10,12) elif "PMC21" in df.loc[index,"ordercode"]: df["pressurerange"]=df["ordercode"].str.slice(10,12) elif "PMP11" in df.loc[index,"ordercode"]: df["pressurerange"]=df["ordercode"].str.slice(10,12) elif "PMP21" in df.loc[index,"ordercode"]: df["pressurerange"]=df["ordercode"].str.slice(10,12) elif "PMP23" in df.loc[index,"ordercode"]: df["pressurerange"]=df["ordercode"].str.slice(10,12) elif "PTP31B" in df.loc[index,"ordercode"]: df["pressurerange"]=df["ordercode"].str.slice(11,13) elif "PTP33B" in df.loc[index,"ordercode"]: df["pressurerange"]=df["ordercode"].str.slice(11,13) elif "PTC31B" in df.loc[index,"ordercode"]: df["pressurerange"]=df["ordercode"].str.slice(11,13) else: df["pressurerange"]="NONE" print(df.loc[:,["pre…

http://stackoverflow.com/q/52196302
has title: pip install django-import-export read timed out
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I am trying to using django-import-export to populate my models with excel files. However, when I do pip install django-import-export, I get this following error C:\Users\Billy Somers\webapps&gt;pip install django-import-export Collecting django-import-export Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/django-import-export/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/django-import-export/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/django-import-export/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/django-import-export/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/django-import-export/ Could not find a version that satisfies the requirement django-import-export (from versions: ) No matching distribution found for django-import-export How do I resolve this?
score: 0
type: Question
has answer: http://stackoverflow.com/a/52196330
has answer: http://stackoverflow.com/a/52196334
answer count: 2

http://stackoverflow.com/q/52249359
type: Question
accepted answer: http://stackoverflow.com/a/52249848
tagged with: class
score: 0
has title: append tf.ones and tf.zeros (tensorflow)
answer count: 1
has body: my dumb code: ones = [1 for i in range(len(positivePictures))] zeros = [0 for i in range(len(negativePictuers))] y = zeros + ones classes = np.array(y).reshape(1,len(y)) this works but it's taking too long (about 4k pictures). I was thinking about using tf.ones and tf.zeros instead. But I don't know how to append two tensors together. I know I can evaluate the result to get back a numpy array. But How to append them?
has answer: http://stackoverflow.com/a/52249848
tagged with: classification
tagged with: python
type: AnsweredQuestion
tagged with: tensorflow

http://stackoverflow.com/a/53080663
type: Answer
has body: Try to view your parquet data in S3 bucket itself with "Select From" option. If its fine, then use Athena to create table of your parquet file with proper table column headers. Later preview table to view the content.
score: 0
answers question: http://stackoverflow.com/q/52196219

http://stackoverflow.com/a/52207227
has comment: http://stackoverflow.com/comment/91369551
type: Answer
has body: If you're running flask run in a bash script, adding &amp; to the end (flask run &amp;) will run the task in the background, allowing the bash script to continue. I think this will let your job finish and Jenkins can scan stdout for the message indicating success. Edit: Apparently overriding the build number export BUILD_ID=&lt;whatever&gt; is enough to stop Jenkins from killing the background process. I'd be wary of what you choose as &lt;whatever&gt;, if you choose an existing BUILD_ID, there could be side-effects.
has comment: http://stackoverflow.com/comment/91364540
accepted answer of: http://stackoverflow.com/q/52207146
answers question: http://stackoverflow.com/q/52207146
score: 4
has comment: http://stackoverflow.com/comment/91369209
upvote count: 4
has comment: http://stackoverflow.com/comment/107730385
has comment: http://stackoverflow.com/comment/91368221
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52246288
favorite count: 0
has title: keras scalar multiplication using inputs
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/52246512
tagged with: tensorflow
type: Question
answer count: 1
has body: I just want to do scalar multiplication using inputs int_input = Input(shape=(1,), name='depth') int_sigmoid = (Activation('sigmoid')(depthInput)) imageInput = Input(shape=(100, 100, 1), name='image') imageInputNormalized = BatchNormalization()(imageInput) con1 = Conv2D(64, (2, 2), padding='same', name='con1')(Activation('relu')(imageInputNormalized)) mp1 = MaxPooling2D(pool_size=2)(con1) con2 = Conv2D(128, (2, 2), padding='same', name='con2')(Activation('relu')(mp1)) l1 = Lambda(lambda x: x ** depthSigmoid)(con2) i get error tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes: [20,50,50,128] vs. [20,1]
tagged with: keras
score: 0

http://stackoverflow.com/q/52143318
answer count: 6
has title: Which default variable stores the substring while searching for string in python using IF condition?
favorite count: 0
downvote count: 3
has answer: http://stackoverflow.com/a/52143773
has comment: http://stackoverflow.com/comment/91236625
tagged with: python
has answer: http://stackoverflow.com/a/52143676
has answer: http://stackoverflow.com/a/52143702
upvote count: 0
has body: if "a" or "b" or "c" in x: print (x) print ("a" or "b" or "c") Here I want to print the substring a or b or c which present in the string and want to do some manipulation on it. So which variable stores the substring?
has comment: http://stackoverflow.com/comment/91237413
has answer: http://stackoverflow.com/a/52143713
type: UnansweredQuestion
score: -3
has answer: http://stackoverflow.com/a/52143765
has comment: http://stackoverflow.com/comment/91236656
has comment: http://stackoverflow.com/comment/91236658
has answer: http://stackoverflow.com/a/52143732
type: Question

http://stackoverflow.com/comment/91466646
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52259498
has text: Paste errors and anything else that might be helpful.

http://stackoverflow.com/comment/91207288
score: 0
type: Comment
type: QuestionComment
has text: @chepner I also think that this could be the error, but I just can't find it.
comment on: http://stackoverflow.com/q/52128294

http://stackoverflow.com/a/52249682
answers question: http://stackoverflow.com/q/52249652
type: Answer
has body: Your line-processing logic should be indented inside the for loop instead, and instead of appending sequence to fasta[seq_name] as a list, you should concatenate sequence to it as a string if you want it to be one value: import sys sequence = '' fasta = {} def seqs_from_file(filename): with open(filename) as f: for line in f: line = line.rstrip("\n") if not line: continue if line.startswith("&gt;"): seq_name = line[1:] if seq_name in fasta: fasta[seq_name].append('') else: fasta[seq_name] = [''] continue sequence = line fasta[seq_name][-1] += sequence print(fasta)
accepted answer of: http://stackoverflow.com/q/52249652
has comment: http://stackoverflow.com/comment/91447551
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91265802
has text: Connecting to a remote MongoDB server. @JoeA
score: 0
comment on: http://stackoverflow.com/q/52157671
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52184303
has comment: http://stackoverflow.com/comment/91322966
score: 1
has comment: http://stackoverflow.com/comment/91318740
downvote count: 1
has comment: http://stackoverflow.com/comment/91323102
has comment: http://stackoverflow.com/comment/91320284
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91321483
has body: To obtain reproducable results in keras follow the following instructions: https://keras.io/getting-started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development. It might be that multi-threading is causing problems. Edit: Every time you run a method, that returns a random number, this number depends on your initial seed. So while your script always returns the same values, e.g. same mean and std for your training/val/test set evaluation it will not use the same random number in each iteration of the for loop. What you can try is to loop around the entire script and set the random set at the beginning of the for loop. Maybe then you will get the same results. There is all kind of randomness in generating and training a DL model. From the initialization of the weights to the order of your training set, which by default is random. This initialization will not be the same if you do not reset the random seed. Same for the order of the dataset. In each epoch your training data is shuffled and this will be different in every for loop run. There are also layers which use stochastic elements like dropout, which need the same seed to guarantee the same performance.
accepted answer of: http://stackoverflow.com/q/52184053
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52184053
has comment: http://stackoverflow.com/comment/91324810
has comment: http://stackoverflow.com/comment/91320619
has comment: http://stackoverflow.com/comment/91324680

http://stackoverflow.com/a/52247227
score: 2
has comment: http://stackoverflow.com/comment/91457066
upvote count: 4
has body: l = [[5,3,7,1,2],[3,2,9,4,7],[8,9,4,2,3]] [q+l[w+1][t+1] for w,i in enumerate(l[:-1]) for t,q in enumerate(i[:-1])] then you can avoid using numpy :) and the output is [7,12,11,8,12,6,11,7]
has comment: http://stackoverflow.com/comment/91474999
answers question: http://stackoverflow.com/q/52246983
downvote count: 2
type: Answer

http://stackoverflow.com/q/52122949
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52123068
tagged with: jinja2
downvote count: 1
has title: Why is my Flask site not displaying the correct information from the database?
type: Question
upvote count: 0
score: -1
tagged with: flask
accepted answer: http://stackoverflow.com/a/52123068
has body: Here is my repository: ​ https://github.com/normandantzig1/artshow.git ​ ​I am not getting the expected results when I run my Flask site ​ I am trying to build for a small project. I am in Bash with a virtualenv. ​ When I go to my my Artshow route for the site, I see "This is the array: submissions" and "says:". Says is repeated 11 times. First, I expect to see a string showing the contents of my submission query where "submissions" is. Second, I expect to see the username of the submitter, "says": and body of the submission repeated 5 times (because there are 5 rows in the submission table). ​ ​Example: The site should show: Tom says Here is a cat picture ​ I am new to flask and sqlalchemy. Did I pass the submissions right in the routes?
tagged with: http://stackoverflow.com/tag/html
answer count: 1

http://stackoverflow.com/comment/91343460
score: 0
type: Comment
type: QuestionComment
has text: read this documentation page [https://python-graph-gallery.com/122-multiple-lines-chart/](https://python-graph-gallery.com/122-multiple-lines-chart/)
comment on: http://stackoverflow.com/q/52196937

http://stackoverflow.com/comment/91396142
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52192168
has text: In "await bot.send_message(message.channel,"Hello")" what do you have to replace message.channel with?
type: AnswerComment

http://stackoverflow.com/comment/91371845
comment on: http://stackoverflow.com/a/52208990
score: 0
type: Comment
has text: I don't know. It would be less work to try it and see than to try to build a mathematical model to estimate. And way more reliable: an ounce of experiment is worth a pound of theory. If you don't have the fully populated tables, I'd suggest creating dummy data, write a short program or query to just fill a table with "a", "b", "c", etc, or whatever is appropriate for the data types.
type: AnswerComment

http://stackoverflow.com/comment/91475006
comment on: http://stackoverflow.com/a/52263212
type: Comment
score: 0
type: AnswerComment
has text: Okay, I'll try your last suggestion when I get home tonight (at work now) and use session if I need to. Thanks for all your help and patience.

http://stackoverflow.com/comment/91447205
comment on: http://stackoverflow.com/q/52249421
score: 0
has text: Mixing up `grid` and `place` within the same parent widget is not supported, and can do all kinds of weird things. Why are you not just gridding everything that you want on the left into column 0? What happens if you try?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91428471
score: 0
has text: This works only for unsigned data (which includes chars) but for signed data, also non-zero elements can sum to zero.
type: Comment
comment on: http://stackoverflow.com/a/52239463
type: AnswerComment

http://stackoverflow.com/comment/119661301
type: Comment
score: 0
has text: Thanks for pointing it out, edited the solution. withColumn takes two positional arguments first is the name of the column and another expression for new column
type: AnswerComment
comment on: http://stackoverflow.com/a/52210702

flask-restplus
tag name: flask-restplus
tags question: http://stackoverflow.com/q/52241556
tags question: http://stackoverflow.com/q/52248567
type: Tag

http://stackoverflow.com/a/52157626
accepted answer of: http://stackoverflow.com/q/52157537
has body: It is very resource intensive to keep opening and closing a socket, I am going to take those out of the while loop. Also, I can't remember if recv is a blocking function or not. But this should help you break out of the while loop properly and solve your first problem. Receiver: def frame_reception_function (): data = [] PORT = 123 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind(('0.0.0.0',PORT)) s.listen(1) conn,address=s.accept() # accept an incoming connection using accept() method which will block until a new client connects while True: datachunk=conn.recv(1024) # reads data chunk from the socket in batches of 4086 bytes using method recv() until it returns an empty string if not datachunk: break # no more data coming in, so break out of the while loop data.append(datachunk) # add chunk to your already collected data conn.close() print(data) return frame_reception_function() Sender: import os,sys import socket import time MyNeighborSet_ip= [&ltTHE IP ADDRESS OF YOUR RECEIVER&gt] Data_transfer_listt = [['192.168.1.1', '192.168.1.2'], ['192.168.1.2', '192.168.1.3'], ['192.168.1.2', '192.168.1.4'], ['192.168.1.4', '192.168.1.5'], ['192.168.1.4', '192.168.1.6']] def sending_Neighobr_ip_list(): #nn1=n1 message='Neighbor_list_sending' #print (len(Data_transfer_listt)) PORT = 123 for k in range (len(MyNeighborSet_ip)): s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((MyNeighborSet_ip[k],PORT)) s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) for i in range(len(Data_transfer_listt)): receiver_ip=Data_transfer_listt[i][0] receiver_node_list=Data_transfer_listt[i][1] T_message= message + ";" + receiver_ip + ";" + receiver_node_list T_message_bytes= bytes(T_message) print("sending message") s.sendall (T_message_bytes) s.close() sending_Neighobr_ip_list() For THE IP ADDRESS OF YOUR RECEIVER, I used my local IP address (192.168.x.x). This is the output on the receiver side: ['Neighbor_list_sen…
has comment: http://stackoverflow.com/comment/91334968
has comment: http://stackoverflow.com/comment/91266431
answers question: http://stackoverflow.com/q/52157537
has comment: http://stackoverflow.com/comment/91279988
has comment: http://stackoverflow.com/comment/91314784
has comment: http://stackoverflow.com/comment/91266069
has comment: http://stackoverflow.com/comment/91266206
has comment: http://stackoverflow.com/comment/91266114
has comment: http://stackoverflow.com/comment/91266319
has comment: http://stackoverflow.com/comment/91308382
has comment: http://stackoverflow.com/comment/91309454
has comment: http://stackoverflow.com/comment/91302127
score: 0
has comment: http://stackoverflow.com/comment/91266792
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91265929
has comment: http://stackoverflow.com/comment/91283686
has comment: http://stackoverflow.com/comment/91280684
has comment: http://stackoverflow.com/comment/91314654
has comment: http://stackoverflow.com/comment/91265589
type: Answer
has comment: http://stackoverflow.com/comment/91339605

http://stackoverflow.com/comment/91429379
has text: PyQt4 is different from PyQt5, getSaveFileName(...) returns a tuple of 2 elements, the first is the name of the file and the second is the filter used, so those lines must throw you an error, can you provide a [mcve] ?
score: 1
comment on: http://stackoverflow.com/q/52240205
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52240319
has title: NOT NULL constraint failed error in django despite having null set to true and blank set to true
answer count: 1
tagged with: model
has body: Here's the code: class community(models.Model): communityName = models.CharField(max_length=280) communityID = models.BigIntegerField(null=True,blank=True) icon = models.CharField(max_length=400) def __str__(self): return self.communityName class team(models.Model): date = models.DateField() startTime = models.TimeField() teamName = models.CharField(max_length=280) community = models.ForeignKey(community, on_delete=models.CASCADE, default=None) I've done a lot of reading on this and it makes sense that I'm supposed to set null and blank to true to prevent this error however when I attempt to migrate the models I still get the following error thrown: django.db.utils.IntegrityError: NOT NULL constraint failed: scheduler_team.community_id I don't know anything about database management and this is the first project I've attempted to do that has a database involved so an ELI5 would be very much appreciated thank you!
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52240351
type: AnsweredQuestion
type: Question
tagged with: database
accepted answer: http://stackoverflow.com/a/52240351
score: 0

http://stackoverflow.com/q/52257555
favorite count: 0
has body: I'm working through the book "Django 2 by example". The second excercise creates a bookmarklet launcher, which loads some javascript from the local Django folder. Testing with a/the recent Firefox version (I'm using arch linux by the way), means that a HTTPS connection is required and I'm having trouble with setting this up. For this I set up stunnel, however it doesn't seem to work fully: The bookmarklet loads correctly on the website that I'm developing, however on all other sites I'm getting Loading failed for the &lt;script&gt; with source “https://127.0.0.1:8443/static/js/bookmarklet.js?r=797695449745”. message in the FF web dev console. The book recommends ngrok, however I don't feel comfortable relying on a third party for these simple tests nor do I feel comfortable necessarily exposing my laptop to the whole web. Hence my efforts with stunnel. While I'm on the webpage I'm developing (https://127.0.0.1:8443/account/#), FF complains about the connection not being secure when checking where usually the green lock is, though the site loads. # dev_https pid= cert = stunnel/stunnel.pem key = stunnel/stunnel.key options=NO_SSLv3 foreground = yes output = stunnel.log debug = 7 output = stunnel.log [https] accept=127.0.0.1:8443 connect=127.0.0.1:8001 TIMEOUTclose=1 and started with stunnel dev_https. The Django development server is started with HTTPS=1 python manage.py runserver 8001 What changes can I make so that the bookmarklet will load the code on any site?
has comment: http://stackoverflow.com/comment/91463169
tagged with: python
tagged with: web
score: 1
answer count: 0
has title: HTTPS for localhost for Django development with stunnel
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: https
tagged with: stunnel
type: Question
has comment: http://stackoverflow.com/comment/91463500
downvote count: 0
has comment: http://stackoverflow.com/comment/91463115

http://stackoverflow.com/a/52235777
upvote count: 2
has comment: http://stackoverflow.com/comment/91432625
has comment: http://stackoverflow.com/comment/91432408
has comment: http://stackoverflow.com/comment/91432363
accepted answer of: http://stackoverflow.com/q/52235389
answers question: http://stackoverflow.com/q/52235389
type: AcceptedAnswer
downvote count: 0
has body: You could use the "date" column as index before concatenating. df1 = pd.DataFrame({'value': [1,2,3,4,5], 'date': [20,40,60,80,100]}) df2 = pd.DataFrame({'value': [11,21,31,41,51], 'date': [20,40,60,80,100]}) df3 = pd.concat([df1.set_index("date"), df2.set_index("date")], keys=['df1','df2'], axis=1) df3.plot() This creates a dataframe with only the two "value" columns and the date as index. When plotting the index is used as x values and for each column a line is drawn. You could also ignore the ignore the column index and later set new column names df3 = pd.concat([df1.set_index("date"), df2.set_index("date")], axis=1, ignore_index =True) df3.columns=['df1','df2'] Or you drop the level of the index that is common to both columns after concatenation. df3 = pd.concat([df1.set_index("date"), df2.set_index("date")], keys=['df1','df2'], axis=1) df3.columns = df3.columns.droplevel(level=1)
type: Answer
score: 2

http://stackoverflow.com/comment/91479784
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52265615
has text: Working through an introductory tutorial on writing classes will help answer many of these questions.

http://stackoverflow.com/comment/91453945
comment on: http://stackoverflow.com/q/52253160
type: Comment
type: QuestionComment
has text: Why and? Just one input value should be entered and not all three of them
score: 0

http://stackoverflow.com/q/52219340
tagged with: append
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/11205254
has comment: http://stackoverflow.com/comment/91387106
has body: I get: 'NoneType' object has no attribute 'append' I want to start with an empty list: Edate = [] But Q1) how do I define this to be a list that will take in dates? Im not sure, so I input a timstamp to get me started: Edate = [Timestamp('2018-01-01 00:00:00')] which is now a 1 element list Now, I want to append dates: dates= 1 2018-01-29 2 2017-10-11 3 2017-03-28 4 2016-10-25 5 2016-03-02 6 2015-11-04 7 2015-10-22 8 2014-01-24 9 2014-01-03 10 2013-10-09 But in trying to do so, I encounter the aforementioned error, which I don't understand. Thanks PS- I would also like to do the same for numbers: entrynumbers = [] data= 0 NaN 1 -31.336 2 -36.012 3 -21.282 4 -41.859 5 -31.381 6 -30.789 7 -27.509 entrynumbers = entrynumbers.append(data)
type: Question
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52219376
has title: Error when appending to an empty list in python
has answer: http://stackoverflow.com/a/52219376
tagged with: python

http://stackoverflow.com/comment/91374878
comment on: http://stackoverflow.com/a/52193521
score: 0
type: AnswerComment
has text: Try using pylint on your code and open a new question if you know where your bottleneck is. Alternatively seek a package that does what you want.
type: Comment

http://stackoverflow.com/comment/91342448
has text: I'm on a bit of a time crunch, so I'll have to check that out later. I did edit my post though, edit #2, if you have a second?
comment on: http://stackoverflow.com/q/52195635
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52138510
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52138883
has body: I have 'inherited' a larger software project using python/flask in the backend and HTML/Javascript in the frontend. I now want to implement some interactiveness on one of the websites. I successfully passed a dataframe to the webpage and can display its content. I have some filters as buttons to change in between various views. I can access those filter values within the webpage itself. How can I now pass these new values to the dataframe to filter it without having to re-render the whole page? Please note that I use template.render() instead of render_templates() as the project does not have a templates folder and it would require too much restructuring to change this. This is the relevant python part: @app.route('/tagging/OverviewPerDoc.html') def analysis(): x = <function which returns a pandas dataframe>() tempid = globalxmlid datatuple = [x, tempid] filetoopen = os.path.join(os.getcwd(), config.filepaths.overviewperdoc) with open(filetoopen) as fi: template = Template(fi.read()) return template.render(data = datatuple) This is the website part: (...) Show (...) {% block content %} (...) {{data[0][data[0]['identifier'] == data[1]]['Name'].iloc[0]}} (...) (...) Value {{data[0][data[0]['identifier'] == data[1]]['Value'].iloc[0]}} {{data[0][data[0]['identifier'] == data[1]]['currency'].iloc[0]}} 100% (...) When clicking on my test button, I can print its value to the console. As I said, all of this is working I now just want to change it to something like: data[0][data[0]['identifier'] == test]['Name'].iloc[0] How can I achieve this?
upvote count: 1
type: Question
has title: Filter pandas Dataframe on Javascript Website
accepted answer: http://stackoverflow.com/a/52138883
answer count: 1
downvote count: 0
tagged with: javascript
score: 1
tagged with: flask
favorite count: 0
tagged with: pandas

http://stackoverflow.com/q/52188421
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91379599
accepted answer: http://stackoverflow.com/a/52188695
has comment: http://stackoverflow.com/comment/91327138
type: Question
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/91328061
answer count: 1
has answer: http://stackoverflow.com/a/52188695
tagged with: python-2.7
score: 0
has body: This is my script, it takes screenshots after 5 seconds and stores it into a png file with timestamp as its name. I want this script to run between 9am to 5pm everyday so i could get screenshot f every activity done between 9 to 5 every day. import pyautogui import time for i in range(4): # Take screensot pic = pyautogui.screenshot() #Name the file with data and time ts = time.strftime("%Y%m%d-%H%M%S") filename = "screenshot" filename += str(ts) filename += ".png" # Save the image pic.save('C:\\Users\\DELL\\Desktop\\Frankiii\{}'.format(filename)) time.sleep(5)
has comment: http://stackoverflow.com/comment/91326614
tagged with: python
has comment: http://stackoverflow.com/comment/91326726
has title: How to make python script to run at specific time?
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91328745

http://stackoverflow.com/comment/91266531
type: QuestionComment
has text: Add a salt to your password generator. Else if one I'd is compromised, there is a high risk of compromising all the passwords.
score: 0
comment on: http://stackoverflow.com/q/52158102
type: Comment

http://stackoverflow.com/comment/91439652
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52244319
has text: No I don't think so. But I don't see how that's relevant to python? Is there some rc option like `text.texarguments`? Also as I mentioned it works if I don't use any latex environments
score: 0

http://stackoverflow.com/q/52231496
type: Question
has comment: http://stackoverflow.com/comment/91412669
answer count: 2
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/91412654
score: 0
has answer: http://stackoverflow.com/a/52231679
has comment: http://stackoverflow.com/comment/91412483
has comment: http://stackoverflow.com/comment/91412686
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52231679
possible better answer: http://stackoverflow.com/a/52231650
has title: Replace unwanted special characters from a string, retain special characters between two numerical
has answer: http://stackoverflow.com/a/52231650
tagged with: nlp
has body: Hi I am working on one NLP project, where I need to identify entities / organization names from the text. However, the words in string are concatenated with (_ : ,) characters as shown below: RING_LECO:108_.250X.436X.093V_772_520 I would want to clean the string as below: Ring Leco 108 .250X.436X.093V 772_520 We have removed special characters between two words (A-Z:A-Z,A-Z:0-9) but retained _ symbol between 772 and 520. Is there any way that I could do this?

http://stackoverflow.com/q/52234500
tagged with: scrapy
tagged with: emoji
has answer: http://stackoverflow.com/a/52234539
type: Question
accepted answer: http://stackoverflow.com/a/52235304
possible better answer: http://stackoverflow.com/a/52234539
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52235304
has body: I am currently using Scraper from https://scrapy.org/ under python 3.x and ubuntu environment , somehow i would like to get user comment in forum, and which contain text as well as emoji. Wondering how we save those emoji into an array so that i can see this in cvs or json ? Thanks
has comment: http://stackoverflow.com/comment/91417695
has title: Scraper - How to save and store emoji
tagged with: python
type: AnsweredQuestion
tagged with: web-scraping

http://stackoverflow.com/a/52122675
score: 14
has comment: http://stackoverflow.com/comment/91261759
downvote count: 0
has comment: http://stackoverflow.com/comment/91255703
has comment: http://stackoverflow.com/comment/91372939
type: Answer
answers question: http://stackoverflow.com/q/52122632
has comment: http://stackoverflow.com/comment/91372553
upvote count: 14
has comment: http://stackoverflow.com/comment/91372538
has body: What you are seeing is the representation of the function type: &gt;&gt;&gt; from types import FunctionType &gt;&gt;&gt; repr(FunctionType) "&lt;class 'function'&gt;" This is the "type" of a function defined with def or otherwise: &gt;&gt;&gt; def f(): ... pass ... &gt;&gt;&gt; type(f) is FunctionType True &gt;&gt;&gt; type(lambda: None) is FunctionType True The string you've seen in the representation is coming from __name__ attribute on each object: &gt;&gt;&gt; type(print).__name__ 'builtin_function_or_method' &gt;&gt;&gt; FunctionType.__name__ 'function' "function" is not syntax itself, because it's easier to type "def". A rhetorical question: if def was the name used to resolve to the function type, then what syntax would you use to actually define a function?

http://stackoverflow.com/a/52193794
accepted answer of: http://stackoverflow.com/q/52193263
answers question: http://stackoverflow.com/q/52193263
score: 0
has body: Answer confirmed from comments: Variable row is at a higher scope already, so writes to it are getting overwritten by writes to it by another thread. Changing the name of row to something else made the problem go away.
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/91342618
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52195737
type: Comment
has text: For the edit#2, it'll only search whether search string exists in list as it is.

http://stackoverflow.com/q/52242647
tagged with: android
tagged with: python
accepted answer: http://stackoverflow.com/a/52242697
score: 0
answer count: 1
tagged with: java
tagged with: mysql
has answer: http://stackoverflow.com/a/52242697
type: AnsweredQuestion
has title: Android POST request with JSON Constraint
has body: Error which i am facing The Error Tells me on class execution to create and inner class or create a new class But i am executing it inside a button which is in onCreate method so please if anybody can guide me how to proceed .... The Main Class private class SendDeviceDetails extends AsyncTask { @Override protected String doInBackground(String... params) { String data = ""; HttpURLConnection httpURLConnection = null; try { httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream()); wr.writeBytes("PostData=" + params[1]); wr.flush(); wr.close(); InputStream in = httpURLConnection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(in); int inputStreamData = inputStreamReader.read(); while (inputStreamData != -1) { char current = (char) inputStreamData; inputStreamData = inputStreamReader.read(); data += current; } } catch (Exception e) { e.printStackTrace(); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); } } return data; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Log.e("TAG", result); // this is expecting a response code to be sent from your server upon receiving the POST data } }
type: Question

http://stackoverflow.com/comment/91179208
score: 0
type: AnswerComment
type: Comment
has text: Is there a way to make a list from the second column to the last column?
comment on: http://stackoverflow.com/a/52114348

http://stackoverflow.com/a/52216668
downvote count: 0
score: 7
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52216526
upvote count: 7
type: Answer
has body: You can try sum along axis=0 and use argsort then reverse the array and use: a[:,np.argsort(a.sum(axis=0))[::-1]] array([[1., 0., 1.], [0., 0., 4.], [8., 8., 0.], [0., 0., 0.], [5., 0., 0.], [2., 2., 2.]])
accepted answer of: http://stackoverflow.com/q/52216526

http://stackoverflow.com/comment/91240781
score: 0
type: AnswerComment
has text: pandas 0.23 and python 3.6.5
type: Comment
comment on: http://stackoverflow.com/a/52145106

http://stackoverflow.com/comment/91242974
type: QuestionComment
comment on: http://stackoverflow.com/q/52146416
has text: yes, sudo pip install quadprog
score: 0
type: Comment

http://stackoverflow.com/comment/91484814
comment on: http://stackoverflow.com/a/52133610
has text: I tried your code. Got an error: NameError: name 'query_string' is not defined" Please try this with DOT = "529136" as an example. It is a valid number and should return a result. Again, I'm completely unfamiliar with aspx that's why I'd like a template code that I could use. Thank you.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/52122990
upvote count: 1
has body: With statsmodels.formula.api you can use vectorized functions from numpy. To apply a subtraction, you may use np.subtract(): import numpy as np import statsmodels.formula.api as smf import pandas as pd y = np.random.uniform(0, 20, size=100) x1 = np.random.uniform(0, 20, size=100) x2 = np.random.uniform(0, 20, size=100) x3 = np.random.uniform(0, 20, size=100) x = np.stack([y, x1, x2, x3], axis=1) df = pd.DataFrame(x) df.columns = ["y", "x1", "x2", "x3"] fit = smf.ols(formula="y~x1+np.subtract(x2, x3)", data=df).fit() print(fit.summary()) (The example data does obviously not make sense and leads to a regression with R squared almost zero, but it shows how it works.)
accepted answer of: http://stackoverflow.com/q/52120834
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52120834
type: Answer
score: 1

http://stackoverflow.com/q/52152857
upvote count: 1
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91256072
downvote count: 1
type: Question
has body: I'd like to close vscode with command: In [8]: cmd = "kill -9 $(pgrep Electron)" In [11]: subprocess.Popen(cmd, shell=True) Out[11]: &lt;subprocess.Popen at 0x10d1d0438&gt; It worked, but when I tried an alternative without shell=True In [13]: cmd = "kill -9 $(pgrep Electron)" In [14]: cmd = shlex.split(cmd) In [15]: cmd Out[15]: ['kill', '-9', '$(pgrep', 'Electron)'] In [16]: subprocess.Open(cmd) AttributeError: module 'subprocess' has no attribute 'Open' How could I enable working as intended?
score: 0
has comment: http://stackoverflow.com/comment/91262988
favorite count: 0
has title: shlex.split failed on "kill -9 $(pgrep Electron)"
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/91207554
type: QuestionComment
comment on: http://stackoverflow.com/q/52128526
has text: i want the text to be moved forward by the character
score: 0
type: Comment

http://stackoverflow.com/comment/91197620
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52123099
has text: @OlivierMelançon I isolated this code. This is all the code.

http://stackoverflow.com/a/77472922
type: Answer
answers question: http://stackoverflow.com/q/52254025
has body: Open the Command Palette (Ctrl+P) and type the name of the symbol you are looking for, prepended with the character # e.g. #MyClass
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/91188076
comment on: http://stackoverflow.com/q/52118321
score: 0
type: QuestionComment
has text: @roganjosh I cannot hardcode it because I have to know exactly the position of each element to compute it via operator. I want it to be computed automatically for any type of given values. If it could easely converted via dictionary of operators like x1 operator.add x2 operator.sub there were questions at all
type: Comment

http://stackoverflow.com/q/52225735
has comment: http://stackoverflow.com/comment/91571909
possible better answer: http://stackoverflow.com/a/52226332
answer count: 3
has comment: http://stackoverflow.com/comment/91401066
has answer: http://stackoverflow.com/a/52226332
has comment: http://stackoverflow.com/comment/91571982
downvote count: 0
has answer: http://stackoverflow.com/a/52316209
favorite count: 0
has comment: http://stackoverflow.com/comment/91573572
has comment: http://stackoverflow.com/comment/91532405
accepted answer: http://stackoverflow.com/a/52316209
tagged with: python
tagged with: regex
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91403421
score: 1
has body: I'm trying to use Python's findall to try and find all the hypenated and non-hypenated identifiers in a string (this is to plug into existing code, so using any constructs beyond findall won't work). If you imagine code like this: regex = ... body = "foo-bar foo-bar-stuff stuff foo-word-stuff" ids = re.compile(regex).findall(body) I would like the ids value to be ['foo', 'bar', 'word', 'foo-bar', 'foo-bar-stuff', and 'stuff'] (although not bar-stuff, because it's hypenated, but does not appear as a standalone space-separated identifier). Order of the array/set is not important. A simple regex which matches the non-hypenated identifiers is \w+ and one which matches the hypenated ones is [\w-]+. However, I cannot figure out one which does both simultaneously (I don't have total control over the code, so cannot concatenate the lists together - I would like to do this in one Regex if possible). I have tried \w|[\w-]+ but since the expression is greedy, this misses out bar for example, only matching -bar since foo has already been matched and it won't retry the pattern from the same starting position. I would like to find matches for (for example) both foo and foo-bar which begin (are anchored) at the same string position (which I think findall simply doesn't consider). I've been trying some tricks such as lookaheads/lookbehinds such as mentioned, but I can't find any way to make them applicable to my scenario. Any help would be appreciated.
upvote count: 1
has comment: http://stackoverflow.com/comment/91532229
type: Question
has answer: http://stackoverflow.com/a/52226455
has comment: http://stackoverflow.com/comment/91533560
has title: How can I define a regex that matches multiple patterns anchored at the same position in my search text?
has comment: http://stackoverflow.com/comment/91401362
has comment: http://stackoverflow.com/comment/91618726
has comment: http://stackoverflow.com/comment/91401165

http://stackoverflow.com/comment/91399960
comment on: http://stackoverflow.com/a/52220705
score: 0
has text: i'm not too sure, this is the message I get when I try to trigger the event. `Ignoring exception in on_message Traceback (most recent call last): File "C:\Program Files\Python35\lib\site-packages\discord\client.py", line 307, in _run_event yield from getattr(self, event)(*args, **kwargs) File "C:\Users\Jon\errorbot.py", line 20, in on_message await bot.send_message(message.channel, "I am a Teapot") NameError: name 'bot' is not defined` which is weird, since the bot.py file is not located in users folder. and im not sure about the client.py
type: Comment
type: AnswerComment

http://stackoverflow.com/q/52139976
downvote count: 1
tagged with: repr
has title: Best way to print a dict with \n or \t characters in keys or values in python?
has body: Essentially, I want to print a dictionary such that it uses str() instead of repr() to stringify its keys and values. This would be especially useful when saving a traceback string in some json. But this appears to be much more difficult than I would imagine: In [1]: import pprint, json In [2]: example = {'a\tb': '\nthis\tis\nsome\ttext\n'} In [3]: print(example) {'a\tb': '\nthis\tis\nsome\ttext\n'} In [4]: str(example) Out[4]: "{'a\\tb': '\\nthis\\tis\\nsome\\ttext\\n'}" In [5]: pprint.pprint(example) {'a\tb': '\nthis\tis\nsome\ttext\n'} In [6]: pprint.pformat(example) Out[6]: "{'a\\tb': '\\nthis\\tis\\nsome\\ttext\\n'}" In [7]: json.dumps(example, indent=2) Out[7]: '{\n "a\\tb": "\\nthis\\tis\\nsome\\ttext\\n"\n}' In [8]: print(json.dumps(example, indent=2)) { "a\tb": "\nthis\tis\nsome\ttext\n" } The behaviour I want (and expect) is this: &gt; print(d) {'a b': ' this is some text '} &gt; pprint.pprint(d) { 'a b': ' this is some text ' } or maybe, if pprint were really smart: &gt; pprint.pprint(d) { 'a b': ' this is some text ' } ...but I can't seem to built-in way to do this! I'd like to know what the standard/best way to do this is, and if there isn't one, why not? Is there a special reason that repr() is always called on strings instead of str() when printing dicts (and other containers)?
has comment: http://stackoverflow.com/comment/91231720
score: 1
has answer: http://stackoverflow.com/a/52140207
has answer: http://stackoverflow.com/a/52140388
type: Question
answer count: 2
tagged with: pprint
has comment: http://stackoverflow.com/comment/91229943
tagged with: string
has comment: http://stackoverflow.com/comment/91229868
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: dictionary

http://stackoverflow.com/a/52223033
has comment: http://stackoverflow.com/comment/91398305
answers question: http://stackoverflow.com/q/52222929
has comment: http://stackoverflow.com/comment/91398623
score: 0
has body: That is completely possible. Below is some of my own code that I have done this with. Combo1x is taking the heading "Name" in the sheet "Reference". Hope this helps! filelog=pd.read_excel(desktop,read_only=True, sheetname=None, na_filter=False) combo1= Combobox(frame3, state='readonly') combo1x=list(filelog['Reference']['Name']) EDIT: One way you could get all the numbers for just "Premium" would to be to take the max row and work backwards with a while statement. ash=logbook["Approvals"] rows = ash.max_row mylist=[] while rows != FinalHeader1 mylist.append() rows -= 1
has comment: http://stackoverflow.com/comment/91395150
type: Answer
has comment: http://stackoverflow.com/comment/91398042
has comment: http://stackoverflow.com/comment/91395185
has comment: http://stackoverflow.com/comment/91399491

http://stackoverflow.com/q/52231122
tagged with: python
linked to: http://stackoverflow.com/q/61881345
upvote count: 6
type: AnsweredQuestion
has body: I know it is possible to extract the road network of a city via the OSMNX python package. See details at https://geoffboeing.com/2016/11/osmnx-python-street-networks/ . paris_network = ox.gdf_from_place("Paris") But, let's say I do not want that level of high details, but rather only big freeways of a whole country. I'm looking for something like : france_big_expressway_network = ox.gdf_from_place("France", road_type = "freeway") I guess it might comes from the "infrastructure" argument but as a newbie I really do not get how to use it precisely.
accepted answer: http://stackoverflow.com/a/52412274
score: 6
type: Question
tagged with: openstreetmap
has title: python osmnx - extract only big freeways of a country
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52412274
tagged with: osmnx
favorite count: 0

tab-completion
tags question: http://stackoverflow.com/q/52212063
type: Tag
tag name: tab-completion

http://stackoverflow.com/a/52123884
answers question: http://stackoverflow.com/q/52123692
score: 0
type: Answer
has body: board = [] for x in range(0,5): board.append(["O"] * 5) print(board) def print_board(board): for i,row in enumerate(board): row[i]="X" print_board(board)

http://stackoverflow.com/comment/91456996
comment on: http://stackoverflow.com/q/52254747
score: 0
has text: Can you make a blanket exception, and print `print(type(e).__qualname__)`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91478171
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52261194
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/179769/discussion-between-d-kennetz-and-jasondl).

http://stackoverflow.com/q/52220065
type: UnansweredQuestion
tagged with: openpyxl
tagged with: python
has comment: http://stackoverflow.com/comment/91596997
type: Question
has comment: http://stackoverflow.com/comment/91458840
score: 0
has title: merged cells are broken after load/save
tagged with: python-3.x
has body: I am opening a .xlsm file using openpyxl abd updated some cells in it and then saved as .xlsm file.Now when I open the saved file I see that the cells which were merged in the original file are broken in new file. the code which i am using is- from openpyxl import Workbook from openpyxl import load_workbook wb = load_workbook('Excel.xlsm',read_only=False ,keep_vba=True) ws = wb['K0 Reg Patch Util'] ws.cell(row=42,column=3).value = 25 ws.cell(row=43,column=3).value = 30 ws.cell(row=44,column=3).value = 24 wb.save('Test.xlsm') how to modify the code so that the file remains in the same format in the new saved file too. Right now with this code the cells which were merged in the original file are broken. How to resolve that because i dont want to destroy the structure in the original file. I have tried saving the file with the same name then also the same problem is coming. Actually i have to save the file with the same structure but the updated values.Can you guys please help me with this??
answer count: 0

http://stackoverflow.com/q/52245272
downvote count: 1
score: -1
type: Question
upvote count: 0
answer count: 1
favorite count: 0
has body: Sorry if my headline wasn't explicit enough. I'm trying to develop a marketing tool that track every single page of my project. So I'm using InfluxDB along PostgreSQL. I am able to track pages (or clicks) but not the "views". Let me explain: If I have a 10 items in the listing. I want to track which item has been displayed on which page. Example: Item B was displayed on page 2; Item C was displayed on page 1. I was planing on looping through the list but I don't like this solution because I have to loop twice: one for tracking, one for display the item. So I'm looking for a cleaner solution but I'm out of ideas. What would you do? Thank you in advance. EDIT: Here are the ideas I found from most favorable to least favorable: create template_tag to track view per object loop through the list before looping again for display use javascript with specific class name to track object
tagged with: python
has answer: http://stackoverflow.com/a/52246550
type: UnansweredQuestion
has title: Count every time an object if displayed/accessed
tagged with: django

http://stackoverflow.com/comment/91186685
has text: if you want to generate a url for another page NO, that's not what it is meant for, it gives you the url for the endpoints in YOUR website that you have declared, but if http://yourserver/cgi-bin is declared (you can access http://yourserver/cgi-bin because there is some @app.route('cgi-bin') in your routes then you can use it, one thing I don't understand is why you are passing the python scripts as urls
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52116418

http://stackoverflow.com/q/52119585
possible better answer: http://stackoverflow.com/a/52119890
has comment: http://stackoverflow.com/comment/91273498
score: 6
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91190094
downvote count: 0
tagged with: dataframe
has answer: http://stackoverflow.com/a/52119661
accepted answer: http://stackoverflow.com/a/52119661
type: Question
upvote count: 6
has body: I have two dataframes, one with daily info starting in 1990 and one with daily info starting in 2000. Both dataframes contain information ending in 2016. df1: Date A B C 1990-01-01 3.0 40.0 70.0 1990-01-02 20.0 50.0 80.0 1990-01-03 30.0 60.0 90.0 1990-01-04 2.0 1.0 1.0 1990-01-05 1.0 8.0 3.0 df2: Date A B C 2000-01-01 NaN NaN NaN 2000-01-02 5.0 NaN NaN 2000-01-03 1.0 NaN 5.0 2000-01-04 2.0 4.0 8.0 2000-01-05 1.0 3.0 4.0 I need to compare columns in df1 and df2 which have the same name, which wouldn't usually be too complicated, but I need to compare them from the point at which there is data available in both dataframes for a given column (e.g from df2, 2000-01-02 in column 'A', 2000-01-04 in 'B'). I need to return True if they are the same from that point on and False if they are different. I have started by merging, which gives me: df2.merge(df1, how = 'left', on = 'Date') Date A.x B.x C.x A.y B.y C.y 2000-01-01 NaN NaN NaN 3.0 4.0 5.0 2000-01-02 5.0 NaN NaN 5.0 9.0 2.0 2000-01-03 1.0 NaN 5.0 1.0 6.0 5.0 2000-01-04 2.0 4.0 8.0 2.0 4.0 1.0 2000-01-05 1.0 3.0 4.0 1.0 3.0 3.0 I have figured out how to find the common date, but am stuck as to how to do the same/different comparison. Can anyone help me compare the columns from the point at which there is a common value? A dictionary comes to mind as a useful output format, but wouldn't be essential: comparison_dict = { "A" : True, "B" : True, "C" : False } Many thanks.
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/52119890
has title: Compare columns in different pandas dataframes
has answer: http://stackoverflow.com/a/52119721
favorite count: 0

http://stackoverflow.com/comment/91433926
has text: Perhaps as an illustration of @BřetislavHájek 's point about the broadness of the question - there is also the Dataset API (https://www.tensorflow.org/guide/datasets) as an alternative to using `feed_dict`. I'd advocate familiarity with this API as a pretty high priority for using TF effectively 'in the wild' with real data but I recognise that's a personal viewpoint. YMMV
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52241667

http://stackoverflow.com/a/52163410
answers question: http://stackoverflow.com/q/52162402
type: Answer
accepted answer of: http://stackoverflow.com/q/52162402
has comment: http://stackoverflow.com/comment/91301386
has comment: http://stackoverflow.com/comment/91301501
has body: tf.metrics.mean_per_class_accuracy creates variables in the tf.GraphKeys.LOCAL_VARIABLES, rather than GLOBAL_VARIABLES. This means they aren't being initialized by your tf.global_variables_initializer(). Fortunately, there's a corresponding tf.local_variables_initializer() to help you out. Throw it in alongside your global initializer and you should be good to go! sess.run([tf.global_variables_initializer(), tf.local_variables_initializer()])
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/91354050
comment on: http://stackoverflow.com/a/52201887
type: AnswerComment
score: 0
type: Comment
has text: Yes if the encoded representation is meant to be fed inside another lstm layer then it would make sense to encode to a 3 dimesnional shape. So simply put `return_sequences = True` in your third lstm layer and delete the Repeat Vector Layer.

http://stackoverflow.com/comment/91425431
has text: I think you’re looking for `enum.IntEnum`?
score: 0
comment on: http://stackoverflow.com/q/52238303
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52163734
has comment: http://stackoverflow.com/comment/91277068
has comment: http://stackoverflow.com/comment/91277578
type: Question
has title: pandas concat gives no entries after pandas rename
has comment: http://stackoverflow.com/comment/91277160
score: 0
has body: concatting dataframes worked well until I renamed columns of a specific dataframe. The renaming is before the concatting. The code for the renaming is as following and this dataframe will be returned after that. ret=output_excel.rename(index=str, columns={"Home":str(self.hhid)+" Home","HH1 distance [km]":str(self.hhid)+" Distance Car1 [km]", "Energy [kWh]":str(self.hhid)+" Energy Car1 [kWh]"}) return ret After I concat the different dataframes, the entries of the renamed columns are empty. How can this happen? If I do not rename the columns everything works fine. The concatting code: for i in range(len(df_input)): O.read_input() O.compute_model() #The dataframes are generated here O.output() df_old=O.output() df_old=df_old df_new=df_old df=pd.concat([df,df_new],axis=1) Did I miss something? Is it easy to fix that? Thanks for Help
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/52164116
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52114980
favorite count: 0
has comment: http://stackoverflow.com/comment/91181019
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91181024
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52115428
has body: I'm trying to draw random numbers from a normal distribution with given mean, variance, skewness and kurtosis. My first attempt was to use the numpy function random.normal however to this function as far as i understand i can only pass a location (mean) and a scale (std) parameter. Second attempt is to draw random numbers from the uniform distribution in the interval [0,1] and then pass them through the scipy.stats.norm method ppf. I see that scipy has the ability to treat skewness and kurtosis, however i cannot see how i can pass skewness and kurtosis values into the function. If the problem should be solved in an entirely different way please let me know. Attempt 1: import numpy as np def draw_normal(): return np.random.normal(loc=0, scale=1) # how to pass skew and kurtosis (excess kurtosis) to the function Attempt 2 import numpy as np from scipy.stats import norm def draw_uniform(): return np.random.uniform(0,1) def draw_normal_alt(): return norm.ppf(draw_uniform(),loc=0, scale=1) #how to pass skew and kurtosis (excess kurtosis) to func
type: Question
tagged with: normal-distribution
tagged with: scipy
tagged with: numpy
has title: How to draw random numbers from a normal distribution with given mean, variance, skewness and kurtosis
tagged with: random
has comment: http://stackoverflow.com/comment/91181063
answer count: 1

http://stackoverflow.com/comment/110145496
type: Comment
has text: By any means is it possible to bring these variable back? I tried re-installing Anaconda and Spyder but doesn't help.
type: AnswerComment
comment on: http://stackoverflow.com/a/52151887
score: 0

http://stackoverflow.com/comment/91358294
score: 0
has text: I edited the question. Help would be appreciated @Toto
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52204336

http://stackoverflow.com/q/52152258
tagged with: python
tagged with: unix
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52152335
has title: untar multiple tar files with identical names to a concatenated/appended file
score: 0
accepted answer: http://stackoverflow.com/a/52152982
type: Question
tagged with: gzip
tagged with: http://stackoverflow.com/tag/tar
tagged with: bash
answer count: 2
has answer: http://stackoverflow.com/a/52152982
has answer: http://stackoverflow.com/a/52152335
has body: My situation is as follows: have a couple of tar files called tar1.tar.gzip, tar2.tar.gzip etc. each one contains a different file but with the same name - fn.csv. if I untar one after the other to the same dir, I get the last one, Is there a way to make tar append the content rather than stepping over it? so far, I've added copy to unique file name after each untar and then concatenated all the files, is there a more direct way (python or bash)?

http://stackoverflow.com/comment/91449600
type: Comment
comment on: http://stackoverflow.com/q/52250960
has text: Add a plain python tag
score: 0
type: QuestionComment

http://stackoverflow.com/q/52124767
tagged with: distutils
has body: I work at a small enterprise, where the number of end users and contributes for a particular set of packages would be no more than 5 forever (this is guaranteed). For the past 3 months, we've just been doing all our research and development on a shared windows drive using anaconda and local git repos for each project. As you can imagine, the resulting source code has become a bit of a mess, with each person's code pointing at a specific package in someone else's folder and dependencies breaking all the time. We've finally gotten a github repository and much of our code has become production stable. I want to distribute this code in a tarball and have each person build from source with disutils in a shared anaconda environment. The full package would be organized by each subpackage and would contain both cython and python files. Ultimately, it would look something like this |tools |setup.py (created with disutils) | __init__.py |package A (dir) |__init__.py |module A1.py |module A2.pyx .... |package B (dir) |__init__.py |package B1.py |package B2.pyx I am going to put the "tools" package into the github repo. Every time an important change happens to anything the tools package, we pull from the master branch and rerun setup.py to keep their local tools package up to date. In addition, we would all be using a shared anaconda environment, so that dependencies on external packages would not break the tools package install. Is this the correct way to distribute production code among a small number of end users? I'm coming from a research not software development background and I genuinely don't know how software distribution works. Is forcing everyone to rebuild from source every single time we update the "tools" package overkill? Traditionally when I install using conda/pip I can just say something like "pip install mypackage --upgrade." Is there some similar sort of procedure we can use here?
has comment: http://stackoverflow.com/comment/91209231
tagged with: github
answer count: 0
has comment: http://stackoverflow.com/comment/91210599
type: UnansweredQuestion
tagged with: python
tagged with: anaconda
tagged with: code-sharing
has comment: http://stackoverflow.com/comment/91200847
type: Question
has title: How to distribute python package to small enterprise
score: 0

http://stackoverflow.com/q/52210750
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/52211282
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/91371996
has title: Using two columns in an existing SQLite database to create a third column using Python
upvote count: 3
has body: I have created a database with multiple columns and am wanting to use the data stored in two of the columns (named 'cost' and 'Mwe') to create a new column 'Dollar_per_KWh'. I have created two lists, one contains the rowid and the other contains the new value that I want to populate the new Dollar_per_KWh column. As it iterates through all the rows, the two lists are zipped together into a dictionary containing tuples. I then try to populate the new sqlite column. The code runs and I do not receive any errors. When I print out the dictionary it looks correct. Issue: the new column in my database is not being updated with the new data and I am not sure why. The values in the new column are showing 'NULL' Thank you for your help. Here is my code: conn = sqlite3.connect('nuclear_builds.sqlite') cur = conn.cursor() cur.execute('''ALTER TABLE Construction ADD COLUMN Dollar_per_KWh INTEGER''') cur.execute('SELECT _rowid_, cost, Mwe FROM Construction') data = cur.fetchall() dol_pr_kW = dict() key = list() value = list() for row in data: id = row[0] cost = row[1] MWe = row[2] value.append(int((cost*10**6)/(MWe*10**3))) key.append(id) dol_pr_kW = list(zip(key, value)) cur.executemany('''UPDATE Construction SET Dollar_per_KWh = ? WHERE _rowid_ = ?''', (dol_pr_kW[1], dol_pr_kW[0])) conn.commit()
downvote count: 0
has answer: http://stackoverflow.com/a/52211282
has comment: http://stackoverflow.com/comment/91377623
type: AnsweredQuestion
score: 3
tagged with: sqlite
has comment: http://stackoverflow.com/comment/91373934

http://stackoverflow.com/q/52212063
type: UnansweredQuestion
score: 1
upvote count: 1
has title: Other packages available from my package's tab-completion
tagged with: pypi
type: Question
tagged with: tab-completion
tagged with: python-import
has answer: http://stackoverflow.com/a/52212125
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91373546
tagged with: package
tagged with: python
has body: When I import a Python 3 package I created, the tab-completion for the package includes some packages that are imported by my package from other packages like pandas. The package has this basic structure: foo/ foo/ __init__.py bar.py baz.py qux.py setup.py My __init__.py contains from .bar import * from .baz import * from .qux import * The problem is that baz.py looks like this import pandas as pd def f1(data): # do something with pandas (pd) def f2(data): # do something different with pandas (pd) Thus, when I import foo, I get tab-completion options like foo.pd, which is not really a valid anything. For all foo.X I want X to be a function or class defined by me, not imported from another package. What is the best way around this? Should I add import pandas as pd to __init__.py? I know I could import pandas as pd inside of every single function, but that seems like overkill for anything more than a trivial example like this one. Is it just a problem with Jupyter's tab-completion?

http://stackoverflow.com/comment/91472423
type: QuestionComment
has text: This `container_id="$(docker ps | grep <container> | awk '{print $1}')"` doesn't look right. I think you forgot to replace `<container>` with the actual container.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52262351

http://stackoverflow.com/a/52267723
has comment: http://stackoverflow.com/comment/91497673
accepted answer of: http://stackoverflow.com/q/52254466
has comment: http://stackoverflow.com/comment/91738488
type: Answer
has body: The problem is that your model input batch_input_shape is fixed. The length of your test length is 1257 and cannot be divisible by 32. It should be changed as follows: model.add(LSTM(10, return_sequences=True,batch_input_shape=(None,1,18))) You should modify test shape before the model evaluate test. x_test= x_test.reshape(len(x)-x_train_size,1,18) y_test= y_test.reshape(len(y)-x_train_size,1,1) score = model.evaluate(x_test, y_test,batch_size=32) Of course, you have to reshape predicted and y_test before inverse_transform. predicted = model.predict(x_test) predicted= predicted.reshape(len(y)-x_train_size,1) y_test= y_test.reshape(len(y)-x_train_size,1)
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91500839
answers question: http://stackoverflow.com/q/52254466
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91721129

http://stackoverflow.com/comment/91247677
comment on: http://stackoverflow.com/a/52146189
type: Comment
score: 1
type: AnswerComment
has text: Puuuh I am sorry but I don't think that is possible. How should the computer know if the hyphen belongs to a word like mother-in-law or is random like in func-tional. Perhaps you can change the read in algorithm to include new line characters or something. I means that is what they are for, to tell the computer when a new line begins.

http://stackoverflow.com/comment/91448221
type: Comment
comment on: http://stackoverflow.com/a/52249844
score: 1
type: AnswerComment
has text: If you to get a single item, use `.get()` instead of `filter()` and `[0]`.

http://stackoverflow.com/q/52220716
has answer: http://stackoverflow.com/a/52226887
has title: python regex two words separated
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/14154263
upvote count: 0
has answer: http://stackoverflow.com/a/52221108
favorite count: 0
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/91389999
tagged with: regex
has comment: http://stackoverflow.com/comment/91389904
duplicate of: http://stackoverflow.com/q/14154263
has body: I have this regex: ^[ ]{0,1}[^\s]+$ who matches only one word, for example: Silver or min. I want to add another word space separated. For example: Silver silver or 1 min should be a match as well.
type: UnansweredQuestion
downvote count: 3

http://stackoverflow.com/q/52142386
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/52142512
has comment: http://stackoverflow.com/comment/91234816
type: Question
has answer: http://stackoverflow.com/a/52142427
has body: I'm working on a web scraping program using Python & BeautifulSoup. I encountered a problem when scraping a table. My problem is, I need to extract selected tags only and not the entire table. I only need the numbers for 52 Week High, 52 Week Low, Earnings Per Share and Price to book value. Is there anyway I can do that? Sample Table 52-Week High: 1,116.00 Earnings Per Share TTM (EPS): 47.87 (15.57%) Price to Book Value (P/BV): 2.5481125565 52-Week Low: 867.50 Price-Earnings Ratio TTM (P/E): 20.8272404429 Return on Equity (ROE): 12.42% Fair Value: - Dividends Per Share (DPS): - Recommendation: None Last Price: 984.5 I also showed my codes for your reference. Any help would be very much appreciated! Thank you! from bs4 import BeautifulSoup as soup from urllib.request import Request, urlopen import pandas as pd myurl = "https://www.investagrams.com/Stock/ac" hdr = {'User-Agent': 'Mozilla/5.0'} req = Request(myurl,headers=hdr) # Open connection to website uClient = urlopen(req) # Offloads the content to variable page_html = uClient.read() #just closing it uClient.close() # html parser page_soup = soup(page_html, "html.parser") table = page_soup.find("div", {"id":"FundamentalAnalysisPanel"}).find("table") print(table.text)
answer count: 2
possible better answer: http://stackoverflow.com/a/52142427
accepted answer: http://stackoverflow.com/a/52142512
downvote count: 0
has comment: http://stackoverflow.com/comment/91234789
favorite count: 0
tagged with: beautifulsoup
has title: How to extract specific from table
tagged with: python

http://stackoverflow.com/comment/130105609
score: 0
comment on: http://stackoverflow.com/a/52178638
type: Comment
has text: I assume, `labels` meant to be `classes`?
type: AnswerComment

http://stackoverflow.com/a/52132527
downvote count: 0
has comment: http://stackoverflow.com/comment/91340652
answers question: http://stackoverflow.com/q/52132450
has comment: http://stackoverflow.com/comment/91303149
upvote count: 2
has comment: http://stackoverflow.com/comment/91340889
type: AcceptedAnswer
has body: Yes, that is completely possible. Full Tutorial and Documentation to save: Tensorflow variables are only alive inside a session. So, you have to save the model inside a session by calling save method on saver object. import tensorflow as tf saver = tf.train.Saver() sess = tf.Session() sess.run(tf.global_variables_initializer()) saver.save(sess, 'my_test_model') For saving the model after 1000 iterations, call save by passing the step count: saver.save(sess, 'my_test_model',global_step=1000) To use pre-trained model for fine-tuning: with tf.Session() as sess: saver = tf.train.import_meta_graph('my-model-1000.meta') saver.restore(sess,tf.train.latest_checkpoint('./')) print(sess.run('w1:0')) ##Model has been restored. Above statement will print the saved value of w1. To add more operations by adding more layers and then train it: sess=tf.Session() #First let's load meta graph and restore weights saver = tf.train.import_meta_graph('my_test_model-1000.meta') saver.restore(sess,tf.train.latest_checkpoint('./')) # Now, let's access and create placeholders variables and # create feed-dict to feed new data graph = tf.get_default_graph() w1 = graph.get_tensor_by_name("w1:0") w2 = graph.get_tensor_by_name("w2:0") feed_dict ={w1:13.0,w2:17.0} #Now, access the op that you want to run. op_to_restore = graph.get_tensor_by_name("op_to_restore:0") #Add more to the current graph add_on_op = tf.multiply(op_to_restore,2) print sess.run(add_on_op,feed_dict) #This will print 120.
type: Answer
accepted answer of: http://stackoverflow.com/q/52132450
score: 2

http://stackoverflow.com/a/52229026
downvote count: 0
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/91994316
upvote count: 1
has comment: http://stackoverflow.com/comment/91984522
has comment: http://stackoverflow.com/comment/92045984
has comment: http://stackoverflow.com/comment/91991320
has body: You can select all of the elements that require modification by generating a mask. I'm not sure how compatible this is which what you already have, but this is the way. It'll basically blow the doors off of the while loop solution speed-wise. import numpy as np x = np.arange(0.0,5.0,0.1) y = np.arange(0.0,5.0,0.1) z = np.arange(0.0,5.0,0.1) points = np.array(np.meshgrid(x,y,z)).T def make_mask(points,a,b,c,r,tol=1e-2): """generates a boolean mask of positions within tol distance of the surface of the sphere (x-a)**2 + (y-b)**2 + (z-c)**2 = r**2""" mask = (points[...,0]-a)**2+(points[...,1]-b)**2+(points[...,2]-c)**2 &lt; (r+tol)**2 return mask mask = make_mask(points,2.5,2.5,2.5,1.0,tol=0.2) # this will tell you all of the points in voxelgrid which need modification voxelgrid[mask] #will return them all If you want to add a value to every point near the surface of the sphere you can do voxelgrid[mask]+=value provided that the voxelgrid and points coordinates coincide in the sense that voxelgrid[i,j,k] is the container associated with the point points[i,j,k].. you will have to use your resolution parameter to make the x,y,z so that this is true. Here's a lame plot showing that it works for me: The code for this plot is from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(*points[mask].T) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.show() plt.savefig('works.png') You can maybe calculate the mask more cleanly with something like: x0 = np.array([a,b,c]) mask = np.sum((points-x0)**2,axis=-1)&lt;(r+tol)**2 but it's a little harder to read. It may be faster ? I am not sure on this. (can anyone weigh in? )
answers question: http://stackoverflow.com/q/52225045
has comment: http://stackoverflow.com/comment/91993001
has comment: http://stackoverflow.com/comment/91995245

http://stackoverflow.com/comment/91181301
has text: otherwise assign the output to a variable, e.g. `axes = ...`
comment on: http://stackoverflow.com/q/52115244
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/comment/91220448
score: 0
type: AnswerComment
has text: appended empty row to jth of array arr, but while assigning arr[j][i] = arr_input[index], its shows the same error.
type: Comment
comment on: http://stackoverflow.com/a/52134986

http://stackoverflow.com/a/52121146
downvote count: 0
has comment: http://stackoverflow.com/comment/91193903
accepted answer of: http://stackoverflow.com/q/52121094
has comment: http://stackoverflow.com/comment/91195287
type: Answer
has comment: http://stackoverflow.com/comment/91195458
answers question: http://stackoverflow.com/q/52121094
has comment: http://stackoverflow.com/comment/91197352
score: 1
has comment: http://stackoverflow.com/comment/91194955
has comment: http://stackoverflow.com/comment/91195473
has comment: http://stackoverflow.com/comment/91195156
has comment: http://stackoverflow.com/comment/91195364
has body: To remove first part of the scraped string separated by / character you can use the following solution: value = driver.find_element_by_xpath("element_xpath").get_attribute("innerHTML").split("/")[1] As per your comment update if you want to extract the sub-string Uncle Drew from the string Wujek Drew / Uncle Drew (2018) you can use the following solution: import re value = driver.find_element_by_xpath("element_xpath").get_attribute("innerHTML") #value='Wujek Drew / Uncle Drew (2018)' print(re.split('[/()]',value)[1])
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/91194350
has text: Grass, it will be more useful to you and readers if you write the errors in the question instead of the image...
score: 2
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52121506

http://stackoverflow.com/comment/91298316
type: Comment
has text: those will be eliminated automatically if you set `error_bad_lines=False`. If you don't want to see the error lines being printed out then you can pass this parameter as well: `warn_bad_lines=False`
comment on: http://stackoverflow.com/a/52173542
score: 0
type: AnswerComment

http://stackoverflow.com/a/52173794
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91298601
answers question: http://stackoverflow.com/q/52173793
type: Answer
accepted answer of: http://stackoverflow.com/q/52173793
has body: Since x is the list the passed index is being converted to the integer representation. The integer representation of the True and False are 1 and 0 respectively. As result it leads to the modification of the first and second elements in the list. From the Python Data model documentation: These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively. In addition to the sample with the list that causes interesting behaviour for the dictionary: x = {} x[True] = 'a' print(x) # --&gt; {True: 'a'} x[1] = 'b' print(x) # --&gt; {True: 'b'} and not {True: 'a', 1: 'b'}
has comment: http://stackoverflow.com/comment/91336363
score: 4
upvote count: 4

http://stackoverflow.com/comment/91216066
comment on: http://stackoverflow.com/q/52132779
has text: If you don't return anything, the return value will be `None`. And in some cases, you don't return anything, namely here: `is_palindrome(middle(word))`.
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/q/52133114
has body: I am very new at Python3 (and Python 2.x) I use a lot nmap to scan my servers on regular basis to make sure the proper ports are open or closed. My goal is to write a Python3 script with nmap for other IT people to use . I would like my script to do the following: choose an option to scan option 1 quick scan option 2 most common tcp ports option 3 scan ports 1-6000 ask the user if she/he would like write the result of the scan to an output file or just run the scan and read the output from the terminal. Enter the IP address to scan I was able to write the code for 1. and 3. but i don't seem to be able write a code with the option for yes do i want an output file os.system("nmap -T4 -A -v -Pn -oN outputfile.txt"+ str(ip) or no I do not want an output file os.system("nmap -T4 -A -v -Pn "+ str(ip) I hope i was clear in my post. I would be happy to share the code that i already wrote. Here is the code. I am sure there are mistakes. Any help will be greatly appreciated. Thank you. #!/usr/bin/python #Library import os, sys, time print (sys.argv) import subprocess # Clear the screen subprocess.call('clear', shell=True) print('Welcome to ScanNmap') print(' ') def main(): print('Please make your selection') print(' ') print('[1] Quick scan') print('[2] most common tcp ports + OS detection') print('[3] Scan - all TCP ports.') print('[9] Exit.') print(' ') option = input('Choose your Scanning Option:') if (option == 1): print('Do you want an output file?') answer = input() if answer == 'no': ip = input('Input IP Address / Hostname:') os.system("nmap -T4 -v -Pn"+ str(ip)) print('\n[**] Done \n') main() else answer == 'yes': ip = input('Input IP Address / Hostname:') os.system('nmap -T4 -v -Pn -oN outputfile.txt'+ str(ip) #print("\n[**] Done \n") main() if (option == 2): print('Do you want an output file?') answer = input() if answer == 'no': ip = input('Input IP Address / Hostname:') os.system('nmap -T4 -A -v -Pn'+ str(ip)) print('\n[**] Done \n') main() else answer == 'yes': i…
score: 0
has comment: http://stackoverflow.com/comment/91343693
has comment: http://stackoverflow.com/comment/91216705
tagged with: python-3.x
has title: Python3 nmap script with Yes No option
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/52197844
favorite count: 0

http://stackoverflow.com/comment/91413627
type: QuestionComment
score: 1
has text: Please note that enumerate returns a tuple : index and value. So `item` here is a tuple. You might have to compare it with `item[1]`
comment on: http://stackoverflow.com/q/52232068
type: Comment

http://stackoverflow.com/q/52129778
upvote count: 0
score: -2
answer count: 1
has title: Cuda Parallelize Kernel
has answer: http://stackoverflow.com/a/52130143
linked to: http://stackoverflow.com/q/52118485
favorite count: 0
has body: I'm trying to parallelize a simple update loop of a simulation on the GPU. Basically there are a bunch of "creatures" represented by circles that in each update loop will move and then there will be a check of whether any of them intersect. radii is the radius of the different types of creatures. import numpy as np import math from numba import cuda @cuda.jit('void(float32[:], float32[:], float32[:], uint8[:], float32[:], float32[:], float32, uint32, uint32)') def update(p_x, p_y, radii, types, velocities, max_velocities, acceleration, num_creatures, cycles): for c in range(cycles): for i in range(num_creatures): velocities[i] = velocities[i] + acceleration if velocities[i] &gt; max_velocities[i]: velocities[i] = max_velocities[i] p_x[i] = p_x[i] + (math.cos(1.0) * velocities[i]) p_y[i] = p_y[i] + (math.sin(1.0) * velocities[i]) for i in range(num_creatures): for j in range(i, num_creatures): delta_x = p_x[j] - p_x[i] delta_y = p_y[j] - p_y[i] distance_squared = (delta_x * delta_x) + (delta_y * delta_y) sum_of_radii = radii[types[i]] + radii[types[i]] if distance_squared &lt; sum_of_radii * sum_of_radii: pass acceleration = .1 creature_radius = 10 spacing = 20 food_radius = 3 max_num_creatures = 1500 num_creatures = 0 max_num_food = 500 num_food = 0 max_num_entities = max_num_creatures + max_num_food num_entities = 0 cycles = 1 p_x = np.zeros(max_num_entities, dtype=np.float32) p_y = np.zeros(max_num_entities, dtype=np.float32) radii = np.array([creature_radius, creature_radius, food_radius], dtype=np.float32) types = np.zeros(max_num_entities, dtype=np.uint8) velocities = np.zeros(max_num_creatures, dtype=np.float32) max_velocities = np.zeros(max_num_creatures, dtype=np.float32) # types: # male - 0 # female - 1 # food - 2 for x in range(1, 800 // spacing): for y in range(1, 600 // spacing): if num_creatures % 2 == 0: types[num_creatures] = 0 else: types[num_creatures] = 1 p_x[num_creatures] = x * spacing p_y[num_creatures] = y * spacing max_velocities[num_creatures…
downvote count: 2
tagged with: numba
tagged with: python
tagged with: cuda
tagged with: parallel-processing
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52130143
type: Question

http://stackoverflow.com/comment/91291739
comment on: http://stackoverflow.com/q/52169356
type: QuestionComment
type: Comment
has text: When you launcher your c++ program is the .so next to exécutable or is it un /usr/local/lib ?
score: 0

http://stackoverflow.com/a/52302754
answers question: http://stackoverflow.com/q/52261803
score: 0
has body: Assuming that you are using a simple DFT: 1. The number of the spectral lines is equal to the number of the samples. Mind that there are spectral lines in both positive and negative frequencies. 2. The value and the implementation of the frequency vector calculation can be found here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fftfreq.html
type: Answer

http://stackoverflow.com/a/74826072
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52116245
has body: Since tf.math.top_k can be used to get the k largest elements, you can negate the values, perform the operation, then negate them again to get the values back: -tf.math.top_k( -x, k ) Pass sorted=False to obtain an equivalent formula to the code you sent in the question.

http://stackoverflow.com/comment/91326043
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52188133
has text: The `=None` is unnecessary here. That implies that the argument is optional, which makes no sense for a reverse function.

http://stackoverflow.com/comment/91352956
type: QuestionComment
has text: How is `array_add` going to know the length of these arrays?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52199057

http://stackoverflow.com/comment/91434702
has text: Add more detail to your code so that your figure is reproducable. Currently it's no good at all without knowing the variables
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52240633

http://stackoverflow.com/q/52178627
type: UnansweredQuestion
score: -3
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91307335
tagged with: list
downvote count: 3
has answer: http://stackoverflow.com/a/52178659
type: Question
has body: &gt;&gt;&gt; from string import ascii_lowercase &gt;&gt;&gt; from random import shuffle &gt;&gt;&gt; shuffle(alp) &gt;&gt;&gt; alp ['n', 'c', 'q', 'l', 's', 't', 'w', 'a', 'o', 'r', 'g', 'u', 'd', 'm', 'k', 'p', 'x', 'v', 'z', 'y', 'j', 'h', 'i', 'f', 'e', 'b'] &gt;&gt;&gt; ck = {x:alp.pop() for x in ascii_lowercase} &gt;&gt;&gt; ck {'a': 'b', 'b': 'e', 'c': 'f', 'd': 'i', 'e': 'h', 'f': 'j', 'g': 'y', 'h': 'z', 'i': 'v', 'j': 'x', 'k': 'p', 'l': 'k', 'm': 'm', 'n': 'd', 'o': 'u', 'p': 'g', 'q': 'r', 'r': 'o', 's': 'a', 't': 'w', 'u': 't', 'v': 's', 'w': 'l', 'x': 'q', 'y': 'c', 'z': 'n'} What make's and why alp list assigned to ck from the last list element of alp? Like "a:b b:e..."
upvote count: 0
answer count: 1
favorite count: 0
has title: Why do dict from list assigned from last element?

http://stackoverflow.com/q/52207138
score: 0
tagged with: azure
answer count: 1
tagged with: adal
has title: Adal for Flask WebApp Azure will not work
tagged with: python
accepted answer: http://stackoverflow.com/a/52214848
type: AnsweredQuestion
has body: I'm at my wit's end here trying to get Azure Active Directory user authentication for my Flask webapp. Before trying any of the user authentication stuff, it was working, but now I've followed all the examples I could find and I don't know what I'm doing wrong. Maybe I'm headed down the wrong path completely, but I could use some feedback if anyone can tell what I'm doing wrong. It won't work either on the local host or on the website itself. On the website, I just get a 500 error that the request timed out. On the local host, it'll get me the sign in request, but then it returns an error after that. I've followed this documentation step by step: https://github.com/Azure-Samples/active-directory-python-webapp-graphapi I registered my webapp in the Azure Active Directory and I set the App IDU URI to: https://{company_domain.com}/{appname} Home Page URL to: https://{appname}.azurewebsites.net Reply URLs to: https://{appname}.azurewebsites.net Required Permissions to allow Delegated Permissions to "Sign in and read user profile" In my code, I created a config.py file that looks like this: RESOURCE = "https://{app_name}.azurewebsites.net" TENANT = "{company_domain_name.com}" AUTHORITY_HOST_URL = "https://login.microsoftonline.com" CLIENT_ID = "{client_id}" # copy the Application ID of your app from your Azure portal CLIENT_SECRET = "{client_secret_key}" # copy the value of key you generated when setting up the application Then in my init.py file I have the following code: from flask import Flask, render_template, Response, session, request, url_for, redirect import adal import config import requests import uuid AUTHORITY_URL = config.AUTHORITY_HOST_URL + '/' + config.TENANT REDIRECT_URI = 'https://{appname}.azurewebsites.net/getAtoken' TEMPLATE_AUTHZ_URL = ('https://login.microsoftonline.com/{}/oauth2/authorize?' + 'response_type=code&amp;client_id={}&amp;redirect_uri={}&amp;' + 'state={}&amp;resource={}') @app.route("/") def main(): login_url = 'http://&lt;app_name&gt;…
tagged with: azure-active-directory
has answer: http://stackoverflow.com/a/52214848
type: Question
tagged with: flask
linked to: http://stackoverflow.com/q/49087407

http://stackoverflow.com/a/52136379
score: 0
type: Answer
has body: Using numpy and rotate (90) import numpy as np list = [[1, 4, 6],[6, 3, 7],[2, 7, 9]] np.diag(np.rot90(array)) Output : array([6, 3, 2]) or without using numpy: list = [[1, 4, 6],[6, 3, 7],[2, 7, 9]] res=[] i=-1 for elm in list : res.append(elm[i]) i-=1 print res #[6, 3, 2]
answers question: http://stackoverflow.com/q/52131612

http://stackoverflow.com/comment/91810040
has text: are you sure `*` works in `df*'xywh' = ...`. I keep getting `SyntaxError: invalid syntax`
score: 0
comment on: http://stackoverflow.com/a/52172018
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91468927
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52260330
has text: Thank you for these valuable hints, I try to implement them!

http://stackoverflow.com/q/52260838
has title: pearson correlation using np.random.rand failing
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52260926
tagged with: python
has body: I have the following code to calculate the correlation coefficient using two different ways to generate number series. It fails to work for the first way (corr_coeff_pearson) but works for the 2nd way (corr_coeff_pearson_1). Why is this so? In both cases, the variables are of class 'numpy.ndarray' import numpy as np np.random.seed(1000) inp_vct_lngt = 5 X = 2*np.random.rand(inp_vct_lngt,1) y=4+3*X+np.random.randn(inp_vct_lngt,1) print(type(X)) corr_coeff_pearson=0 corr_coeff_pearson = np.corrcoef(X,y) print("Pearson Correlation:") print(corr_coeff_pearson) X_1 = np.random.randint(0,50,5) y_1 = X_1 + np.random.normal(0,10,5) print(type(X_1)) corr_coeff_pearson_1 = np.corrcoef(X_1,y_1) print("Pearson Correlation:") print(corr_coeff_pearson_1) Is there some way to "convert" the number in the first way of generating the series that I am missing?
accepted answer: http://stackoverflow.com/a/52260926
type: AnsweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91469249
type: Question
tagged with: numpy

http://stackoverflow.com/comment/91192605
comment on: http://stackoverflow.com/q/52119002
score: 0
type: QuestionComment
has text: *"... errors related to crt1.o' is incompatible with i386:x86-64..."* Maybe you need to remove `-m32` somewhere? Or maybe add `-m64` somewhere? Hard to say without seeing error messages.
type: Comment

http://stackoverflow.com/q/52140395
has answer: http://stackoverflow.com/a/52140462
accepted answer: http://stackoverflow.com/a/52140462
type: Question
type: AnsweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/52141884
has body: I need help retrieving a value from a JSON response object in python. Specifically, how do I access the prices-asks-price value? I'm having trouble: JSON object: {'prices': [{'asks': [{'liquidity': 10000000, 'price': '1.16049'}], 'bids': [{'liquidity': 10000000, 'price': '1.15989'}], 'closeoutAsk': '1.16064', 'closeoutBid': '1.15974', 'instrument': 'EUR_USD', 'quoteHomeConversionFactors': {'negativeUnits': '1.00000000', 'positiveUnits': '1.00000000'}, 'status': 'non-tradeable', 'time': '2018-08-31T20:59:57.748335979Z', 'tradeable': False, 'type': 'PRICE', 'unitsAvailable': {'default': {'long': '4063619', 'short': '4063619'}, 'openOnly': {'long': '4063619', 'short': '4063619'}, 'reduceFirst': {'long': '4063619', 'short': '4063619'}, 'reduceOnly': {'long': '0', 'short': '0'}}}], 'time': '2018-09-02T18:56:45.022341038Z'} Code: data = pd.io.json.json_normalize(response['prices']) asks = data['asks'] asks[0] Out: [{'liquidity': 10000000, 'price': '1.16049'}] I want to get the value 1.16049 - but having trouble after trying different things. Thanks
answer count: 2
possible better answer: http://stackoverflow.com/a/52141884
upvote count: 1
favorite count: 0
tagged with: series
has title: Retrieve value in JSON from pandas series object
tagged with: pandas
tagged with: python
downvote count: 0

http://stackoverflow.com/comment/91414466
type: QuestionComment
comment on: http://stackoverflow.com/q/52232315
has text: As I mentioned in my data set ,I have two text files. One having fname, lname, vehical_brought_city, Vehical Brand ,Vehicle Price.First text file dont have the values for vehicle price .And other text file has vehical brought city,vehicle brand nad vehical price.So what I need to do depending upon the combination of vehical brought city and vehical brand as a combination vehical price need to enter in text file 1 .Like in row 0 I want price as 5000 and for row 4 want price value as 4000.
score: 0
type: Comment

http://stackoverflow.com/comment/91672062
type: Comment
comment on: http://stackoverflow.com/a/52276902
score: 0
type: AnswerComment
has text: Solr is a search engine, and is used in CKAN to search for datasets and resources. That usually takes only the metadata into account (title, description, etc.). You can use [ckanext-extractor](https://github.com/stadt-karlsruhe/ckanext-extractor) to also include information from the actual resource data in the search index (full disclosure: I'm the author of ckanext-extractor).

http://stackoverflow.com/comment/93543632
comment on: http://stackoverflow.com/a/52115260
type: Comment
has text: @JPG I got similar problem and your solution did worked and I was able to update the response. But in my case, I want to show a custom response message when the authentication fails, like: response={'result':0, 'message':'Bad Request'}, and when it passes its shoud give result 1 with a key value and user primary key. How could I achieve this. You could check my link of question asked- https://stackoverflow.com/questions/53319843/modify-response-from-django-rest-api-using-customusermodel-extending-default-use
score: 0
type: AnswerComment

http://stackoverflow.com/a/52226455
upvote count: 1
has comment: http://stackoverflow.com/comment/91532315
answers question: http://stackoverflow.com/q/52225735
type: Answer
downvote count: 0
score: 1
has body: If you don't have to use regex Just use split(below is example) result = [] for x in body.split(): if x not in result: result.append(x) for y in x.split('-'): if y not in result: result.append(y)

http://stackoverflow.com/q/52195386
tagged with: pandas
has title: Pandas: Converting part of a row into a list
answer count: 1
has answer: http://stackoverflow.com/a/52195394
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52195394
tagged with: python
type: AnsweredQuestion
type: Question
has body: I have a dataframe that looks like this: df2 = pd.DataFrame(['Apple, eggs, pineapple pizza', 'orange, soda, pepsi, cola', 'pear, watermelon, pizza, lasagna', 'apple, eggs, human sandwich, human chili'], columns=['A']) A 0 Apple, eggs, pineapple pizza 1 orange, soda, pepsi, cola 2 pear, watermelon, pizza, lasagna 3 apple, eggs, human sandwich, human chili What I want to output is this: ['apple, eggs, pineapple, pizza', 'orange, soda, pepsi, cola', 'pear, watermelon, pizza, lasagna', 'apple, eggs, human sandwich, human chili'] I am not sure where to begin, any suggestions?
score: 0

http://stackoverflow.com/q/52236700
has comment: http://stackoverflow.com/comment/91883201
tagged with: raspberry-pi
tagged with: smbus
has title: I²C bytes received out of order using Raspberry Pi Python SMBus
has answer: http://stackoverflow.com/a/52469789
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52254844
tagged with: sensors
tagged with: python
has body: I am setting up a Raspberry Pi to record data (CO2, humidity, and temperature) from the Sensirion SCD30 sensor. My code is in Python&nbsp;3, using the SMBus library to communicate with the sensor over the I²C pins in the Raspberry Pi's GPIO. There is a command to determine whether the sensor is ready to send data. Link to SCD30 interface datasheet Link to SCD30 library for Arduino by Sparkfun The value 0x0202 is sent over I²C, and three bytes of data are returned: 0x00 0x00 0x81 for data not ready 0x00 0x01 0xB0 for data ready The first two bytes are the MSB and the LSB of the data ready value. Combined properly, they should be 0x0000 and 0x0001. The third byte is the CRC8 of the first two bytes. This is calculated with a polynomial of 0x31 and an initialization of 0xFF. About half the time, the bytes are sent in the wrong order. Instead of MSB LSB CRC it is sent MSB CRC LSB. For example, if the data is ready it might send 0x00, 0xB0, 0x01 instead of 0x00, 0x01, 0xB0. I can't figure out why this is happening, and I'm concerned there is some corruption or issues in sending data. I could change the code to recognize if the CRC is the second byte, but I would like to find the underlying problem. I am sending and receiving I²C data using the smbus library. This is my code to send commands and read data: bus = smbus.SMBus(0) I2C_ADDRESS = 0x61 def sendCommand(self, cmd): # Sends a 2 byte command (cmd) data = [0]*2 data[0] = cmd &gt;&gt; 8 # Splits 2 byte command into MSB and LSB data[1] = cmd &amp; 0xFF bus.write_i2c_block_data(I2C_ADDRESS, data[0], data[1:]) def readRegister(self, reg, length): # Sends 2 byte command (reg) and receives (length) bytes sendCommand(reg) data = bus.read_i2c_block_data(I2C_ADDRESS, 0, length) return data For the example I gave above, I would run the following code: ready = readRegister(0x0202, 3) # Returns a list of 3 bytes print(ready) And it would return a list of the three bytes demonstrated above.
answer count: 4
upvote count: 11
type: UnansweredQuestion
tagged with: i2c
has answer: http://stackoverflow.com/a/53334897
score: 11
has answer: http://stackoverflow.com/a/52470624
type: Question

http://stackoverflow.com/a/52128120
answers question: http://stackoverflow.com/q/52127854
type: AcceptedAnswer
downvote count: 0
upvote count: 8
has body: The default CPython __hash__ implementation for a custom class is written in C and uses the memory address of the object. Therefore, it does not have to access absolutely anthing from the object and can be done very quickly, as it is just a single integer operation in CPU, if even that. The "very basic" __hash__ from the example is not as simple as it may seem: def __hash__(self): return hash(self.a) This has to read the attribute a of self, which I'd say in this case will call object.__getattribute__(self, 'a'), and that will look for the value of 'a' in __dict__. This already involves calculating hash('a') and looking it up. Then, the returned value will be passed to hash. To answer the additional question: Is there a way to implement a faster __hash__ method that returns predictable values, I mean that are not randomly computed at each run as in the case of the memory address of the object ? Anything accessing attributes of objects will be slower than the implementation which does not need to access attributes, but you could make attribute access faster by using __slots__, or implementing a highly optimized C extension for the class. There is, however, another question: is this really a problem? I cannot really believe that an application is becoming slow because of slow __hash__. __hash__ should still be pretty fast unless the dictionary has trillions of entries, but then, everything else would become slow and ask for bigger changes... I did some testing and have to make a correction. Using __slots__ is not going to help in this case at all. My tests actually showed that in CPython 3.7 the above class becomes slightly slower when using __slots__.
type: Answer
has comment: http://stackoverflow.com/comment/91207007
score: 8
has comment: http://stackoverflow.com/comment/91206907
accepted answer of: http://stackoverflow.com/q/52127854
has comment: http://stackoverflow.com/comment/91206770

http://stackoverflow.com/comment/91452833
has text: try to pass a list for friends.
comment on: http://stackoverflow.com/q/52252586
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52115190
tagged with: selenium-webdriver
has title: Checking whether element is there or not
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/52118767
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91187117
has answer: http://stackoverflow.com/a/52115336
tagged with: selenium
has comment: http://stackoverflow.com/comment/91194891
upvote count: 1
has body: def status_button_check(): if(driver.find_element_by_xpath("//div[@role='button' and @title='Status']")): s_b_c_status = "True" else: s_b_c_status = "False" print(s_b_c_status) status_button_check() trying to check element if is there or not, but it gave me following error: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: "method":"xpath","selector":"//div[@role='button' and @title='Status']"}
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/45695874
has comment: http://stackoverflow.com/comment/91194914
has comment: http://stackoverflow.com/comment/91183012
tagged with: webdriver
has comment: http://stackoverflow.com/comment/91181975
score: 0
has comment: http://stackoverflow.com/comment/91181314
has comment: http://stackoverflow.com/comment/91183244
answer count: 2
accepted answer: http://stackoverflow.com/a/52115336
has comment: http://stackoverflow.com/comment/91182792
has comment: http://stackoverflow.com/comment/91195011
has comment: http://stackoverflow.com/comment/91181722
has comment: http://stackoverflow.com/comment/91187875
favorite count: 0
has answer: http://stackoverflow.com/a/52115319
has comment: http://stackoverflow.com/comment/91183371
has comment: http://stackoverflow.com/comment/91188428
duplicate of: http://stackoverflow.com/q/45695874
tagged with: python
possible better answer: http://stackoverflow.com/a/52115319

http://stackoverflow.com/a/52216820
type: AcceptedAnswer
downvote count: 0
has body: You need: df.pivot_table(index='final_score',columns='date',aggfunc='count').fillna(0) df.columns = df1.columns.levels[1].astype(str) date 2018-09-05 2018-09-06 2018-09-07 final_score 17 0.0 1.0 0.0 39 0.0 1.0 0.0 42 1.0 0.0 0.0 56 0.0 1.0 0.0 58 1.0 0.0 0.0 60 0.0 1.0 0.0 61 0.0 0.0 1.0 63 0.0 0.0 1.0 64 0.0 1.0 0.0 79 0.0 1.0 0.0 df['2018-09-05'] final_score 17 0.0 39 0.0 42 1.0 56 0.0 58 1.0 60 0.0 61 0.0 63 0.0 64 0.0 79 0.0 Name: 2018-09-05, dtype: float64
has comment: http://stackoverflow.com/comment/91382911
has comment: http://stackoverflow.com/comment/91382432
type: Answer
has comment: http://stackoverflow.com/comment/91382779
upvote count: 3
answers question: http://stackoverflow.com/q/52216737
has comment: http://stackoverflow.com/comment/91382333
accepted answer of: http://stackoverflow.com/q/52216737
score: 3

http://stackoverflow.com/q/52231632
has comment: http://stackoverflow.com/comment/91412765
tagged with: google-cloud-platform
downvote count: 0
favorite count: 0
has title: Assign a URL to a python script to run a cron job on Google Cloud?
has comment: http://stackoverflow.com/comment/91412823
type: Question
tagged with: cron
has comment: http://stackoverflow.com/comment/91427277
tagged with: python
score: 1
has body: I have a simple Django app that displays some data it pulls from a database. I have a Python script that updates the data and I would like it to run every day. I'm having trouble figuring out how to format my app.yaml handlers so they respond to the cron.yaml. cron.yaml looks like this: cron: - description: "daily update" url: /go schedule: every 24 hours the app.yaml looks like this (minus some sensitive parts): runtime: python entrypoint: gunicorn -b :$PORT rcg_new.wsgi # specific to a GUnicorn HTTP server deployment env: flex handlers: - url: /static static_dir: static - url: /go script: scripto.app runtime_config: python_version: 3 the script looks like this: import pandas as pd import numpy as np import requests import webapp2 import urllib2 import urllib3 import certifi import json import re from rcg_func_dj import pull_rc, pull_artists, artist_cycle, tally import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rcg_new.settings") import django django.setup() from rcg_app.models import Gender, Groups http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) spot_id = os.environ['SPOT_ID'] spot_sec = os.environ['SPOT_SEC'] class update_dbs(webapp2.RequestHandler): def get(self): self.response.headers["Content-Type"] = "text/html" self.response.write('running rcg...') rc = pull_rc(spot_id, spot_sec) artists_unprocessed = pull_artists(rc) artists_processed = artist_cycle(artists_unprocessed) tally(artists_processed) self.response.write('rcg done!') routes = [('/go', update_dbs)] app = webapp2.WSGIApplication(routes, debug=True) the script works, as i used it to populate the db in the first place! it shows up fine in the task queue, but gives me a "failed" status when i try to run it. nothing shows up in the logs though.
tagged with: django
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/52248904
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91412808

http://stackoverflow.com/comment/91194886
comment on: http://stackoverflow.com/q/52121006
score: 0
has text: @Chris just a mock up here, I wrote in the question, so please forgive those errors.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52222110
upvote count: 3
tagged with: selenium
type: Question
answer count: 2
downvote count: 0
favorite count: 0
has title: Cannot run Firefox (geckodriver) properly from PyCharm python console
type: UnansweredQuestion
tagged with: geckodriver
tagged with: python
score: 3
has body: So i use PyCharm 2018.2.3, geckodriver 0.20, Firefox 63.0 and Python 3.6.5 in it for my Selenium auto-tests. What I try to do in Python Console to run the driver: from selenium import webdriver profile = webdriver.FirefoxProfile() profile.accept_untrusted_certs = True wd = webdriver.Firefox(executable_path="C:\\Users\\user\\geckodriver.exe", firefox_profile=profile) So the geckodriver runs in a new window. Then I ususally write url = "https://website-address.com/" wd.get(url) But this time I get the message: Previous command is still running. Please wait or press Ctrl+C in console to interrupt. And then in like a couple of minutes geckodriver exit with these messages in log: Traceback (most recent call last): File "&lt;input&gt;", line 4, in &lt;module&gt; File "C:\Users\user\project\venv\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 170, in __init__ keep_alive=True) File "C:\Users\user\project\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 156, in __init__ self.start_session(capabilities, browser_profile) File "C:\Users\user\project\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 251, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "C:\Users\user\project\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 320, in execute self.error_handler.check_response(response) File "C:\Users\user\project\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: newSession Please help me to understand what is going on and how to fix it.
has answer: http://stackoverflow.com/a/52279642
has answer: http://stackoverflow.com/a/52228695

http://stackoverflow.com/comment/91228412
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52139043
type: Comment
has text: No, because rsplit starts at the end and goes left. It would see `Activity-Location-UserCode`, and then split to `Activity-Location, UserCode`, because `maxsplit=1`. Without setting `maxsplit`, yes you would be correct in saying `[1]` would give `Location` - in which case there would be no difference in using `split` or `rsplit`.

http://stackoverflow.com/q/52263978
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52264058
linked to: http://stackoverflow.com/q/16105856
has title: Read 4 column 1000 row txt file into Eclipse
score: 0
upvote count: 1
tagged with: eclipse
downvote count: 1
type: Question
has body: I am new to coding and have a program that produces 1000 3d points into a txt file for a scatter plot in which I lay an elipsoid over it. I need to perform an ellipsoid equation that reads all of those points into a loop that will give me the percentage at the end of how many points lie in the ellipsoid. How do I read a large txt file directly into a loop with a equation? the equation I need it read into is if (x/2)^2+(y/2)^2+(z/1)^2 &lt; 1 then it is in the ellipsoid. Any help is appreciated thank you!

http://stackoverflow.com/comment/91424029
comment on: http://stackoverflow.com/q/52226198
has text: Also its not a duplicate of that other question, I ultimately needed to verify the verification to output to the console for readability/ understanding for other users. Just running the code isn't enough to someone just running the test.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91290356
comment on: http://stackoverflow.com/a/52165680
type: Comment
score: 1
has text: Inleed; and yet, this is a fairly reasonable aporoximation of what Bash actually does. The way to proceed is to implement `cd`, variable assigments, and eventually other shell builtins in your Python shell itself.
type: AnswerComment

http://stackoverflow.com/comment/91207245
type: Comment
type: QuestionComment
has text: Apparently it is. Didn't know about that one! :)
comment on: http://stackoverflow.com/q/52128294
score: 0

http://stackoverflow.com/a/52271393
has body: If I understood correctly, what you want is to tokenize your reviews to use Naive Bayes. One hot encoding is for labels or categorical data. You should use it on your labels to have 0 and 1 instead of positive and negative but not on your reviews For your text, there are functions built in sklearn to tokenize, typically CountVectorizer will probably work here. I suggest to look at the follwing link which explains how to work with text in detail.
type: Answer
answers question: http://stackoverflow.com/q/52270766
score: 0
has comment: http://stackoverflow.com/comment/91491210

http://stackoverflow.com/q/52124659
downvote count: 1
has answer: http://stackoverflow.com/a/52124803
tagged with: lstm
type: Question
answer count: 1
tagged with: neural-network
tagged with: keras
score: 0
has title: What should be 'y_train' in Keras LSTM?
has body: I refer to the example given at the Keras website here: from keras.models import Sequential from keras.layers import LSTM, Dense import numpy as np data_dim = 16 timesteps = 8 num_classes = 10 # expected input data shape: (batch_size, timesteps, data_dim) model = Sequential() model.add(LSTM(32, return_sequences=True, input_shape=(timesteps, data_dim))) # returns a sequence of vectors of dimension 32 model.add(LSTM(32, return_sequences=True)) # returns a sequence of vectors of dimension 32 model.add(LSTM(32)) # return a single vector of dimension 32 model.add(Dense(10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # Generate dummy training data x_train = np.random.random((1000, timesteps, data_dim)) y_train = np.random.random((1000, num_classes)) # Generate dummy validation data x_val = np.random.random((100, timesteps, data_dim)) y_val = np.random.random((100, num_classes)) model.fit(x_train, y_train, batch_size=64, epochs=5, validation_data=(x_val, y_val)) For a real-world example, what should be y_train and y_val? Should they be the same as x_train and x_val respectively, since they come from the same sequence? Also, how should I understand data_dim and num_classes?
tagged with: python
favorite count: 0
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 1

http://stackoverflow.com/q/52133445
tagged with: sparse-matrix
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52133696
has title: "Merge" two sparse matrices based on column names (in separate list)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91227259
tagged with: python
has comment: http://stackoverflow.com/comment/91217354
has comment: http://stackoverflow.com/comment/91222776
tagged with: scipy
type: Question
tagged with: numpy
has body: I have two sparse matrices like the following: import numpy as np from scipy.sparse import csr_matrix m1_colnames = ['a', 'b', 'd', 'e', 't', 'y'] m1 = csr_matrix(np.array([[1, 2, 0, 4, 5, 0], [1, 2, 0, 4, 5, 0]])) m2_colnames = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] m2 = csr_matrix(np.array([[1, 2, 0, 0, 4, 0, 4, 5, 0], [1, 2, 0, 0, 4, 0, 4, 5, 0]])) Essentially what I want to do (in pandas terms) is merge by column name, to get a final sparse matrix that is of size 11 (11 unique column names) by 4 (4 rows). However, I cannot convert to pandas then back, as my real dataset is over 1000000 rows by 100000 columns (sparse matrices). How can this be done? I would need a final list of column names so I know the order of things in the merged sparse matrix. Thanks, Jack EDIT: Desired output: final_colnames = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 't', 'y'] final_m = csr_matrix(np.array([[1, 2, 0, 0, 4, 0, 4, 5, 0, 0, 0], [1, 2, 0, 0, 4, 0, 4, 5, 0, 0, 0], [1, 2, 0, 0, 4, 0, 0, 0, 0, 4, 5], [1, 2, 0, 0, 4, 0, 0, 0, 0, 4, 5]])) Way of doing desired in pandas, though I am looking for a method without pandas: df1 = pd.DataFrame(m1.A, columns = m1_colnames) df2 = pd.DataFrame(m2.A, columns = m2_colnames) final_df = pd.concat(df1, df2) final_df = final_df.fillna(0) final_sparse = csr_matrix(final_df.values) final_colnames = final_df.columns final_sparse and final_colnames is what I am looking for.

http://stackoverflow.com/comment/91366790
comment on: http://stackoverflow.com/q/52208585
score: 0
type: Comment
type: QuestionComment
has text: Can you share the error you're getting?

http://stackoverflow.com/a/52155436
has comment: http://stackoverflow.com/comment/91261380
upvote count: 2
has comment: http://stackoverflow.com/comment/91261328
type: Answer
has body: You could use sub to match the date like pattern (Note that that does not validate a date) from the start of the string ^\d{2}\.\d{2}\.\d{4} and replace with an empty string. And as @UnbearableLightness mentioned, you have to escape the dot \. if you want to match it literally. import re result = re.sub(r'^\d{2}\.\d{2}\.\d{4}', '', '01.10.2018Any text..') print(result) # Any text.. Demo
score: 2
answers question: http://stackoverflow.com/q/52155370
downvote count: 0
has comment: http://stackoverflow.com/comment/91261135

web
tags question: http://stackoverflow.com/q/52171547
type: Tag
tags question: http://stackoverflow.com/q/52257555
tags question: http://stackoverflow.com/q/52128379
tags question: http://stackoverflow.com/q/52135929
tags question: http://stackoverflow.com/q/52135670
tags question: http://stackoverflow.com/q/52140773
tag name: web
tags question: http://stackoverflow.com/q/52113219
tags question: http://stackoverflow.com/q/52133582
tags question: http://stackoverflow.com/q/52164812
tags question: http://stackoverflow.com/q/52178689
tags question: http://stackoverflow.com/q/52242818

http://stackoverflow.com/comment/91233889
has text: Hard to tell the structure of your data here. Can you share some more information to make sure folks trying to answer it can replicate the issue?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52141951

http://stackoverflow.com/a/52219908
answers question: http://stackoverflow.com/q/52219864
upvote count: 5
has body: Leverage broadcasting extending dims for A to 3D with None/np.newaxis, perform the elementwise multiplication and reshape back to 2D - (A[:,None]*B).reshape(-1,B.shape[1]) which essentially would be - (A[:,None,:]*B[None,:,:]).reshape(-1,B.shape[1]) Schematically put, it's : A : M x 1 x N B : 1 x K x N out : M x K x N Final reshape to merge last two axes and give us (M x K*N) shaped 2D array. We can also use einsum to perform the extension to 3D and elementwise multiplication in one function call - np.einsum('ij,kj-&gt;ikj',A,B).reshape(-1,B.shape[1])
score: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52219864
type: Answer

http://stackoverflow.com/comment/91257540
type: Comment
has text: So what do I do if I want to print Vga3?
type: AnswerComment
comment on: http://stackoverflow.com/a/52153648
score: 0

http://stackoverflow.com/comment/91446258
type: QuestionComment
has text: Ah, that makes sense! Thank you for the great help and the links!
comment on: http://stackoverflow.com/q/52240631
score: 0
type: Comment

http://stackoverflow.com/q/52149300
score: 1
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/31323499
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52149388
tagged with: python
has title: Input contains NaN, infinity or a value too large for dtype('float64') when I scale my data
accepted answer: http://stackoverflow.com/a/52149388
has body: I am trying to normalize my data like this : scaler = MinMaxScaler() trainX=scaler.fit_transform(X_data_train) and I get this error : ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). X_data_train is a pandas DataFrame of size (95538, 550). What is really odd is that when I write print (X_data_train.min().min()) it gives -5482.4473 and similarly for the max, I get 28738212.0, which does not seem for me to be extra-high values... Moreover, based on the command given by the 54+ voted answer, I did check I have no NaN or Infinity for sure. Moreover, I don't have blanks in my csvor things like that, as I checked the dimensions So, where is the problem ??
type: AnsweredQuestion

http://stackoverflow.com/comment/91274836
type: QuestionComment
has text: Yes, the problem is somehow with the pipeline. But that would lead too far here. I am now trying without a pipeline.
comment on: http://stackoverflow.com/q/52146092
score: 0
type: Comment

http://stackoverflow.com/comment/91417975
has text: can you share a minimum amout of data to work with?
comment on: http://stackoverflow.com/q/52234518
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91312884
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52181417
score: 3
has text: out of 0-9999 numbers, 1000-9999 are 4 digit numbers. So, it is highly probable that you get a 4 digit number when each number is equally probable.

http://stackoverflow.com/q/52240205
tagged with: pyqt
score: 3
has body: I'm writing a simple gui application for flashcards. The user generates flash cards and they are saved to a list. I want to save only the list to a file so the user could have multiple decks and just File-> open what they want. In my uneducated brain, I feel saving them in a python file would make the whole process easier, assuming I did something along the lines of the following upon load: for c in filename.allCards: allCards.append(c) I've tried using both name.setNameFilters(["*.py"]) and name.selectNameFilter("Python Files (*.py)") with no luck. So now I have basically two questions. 1) is this the most efficient way to do this and 2) if so what am I missing because even when I save after adding the .py extension manually it still saves as a text file? for reference here is my save function def saveFunc(self): name = QtWidgets.QFileDialog.getSaveFileName(self, 'Save File',"Python Files (*.py)") name.setNameFilters(["*.py"]) name.selectNameFilter("Python Files (*.py)") file = open(name, 'w') which I call in my main window through a menu action. Here is the entire script import os import sys from PyQt5.QtWidgets import * #QApplication, QWidget, QPushButton from PyQt5.QtGui import* # QIcon from PyQt5.QtCore import pyqtSlot from PyQt5 import QtWidgets, QtCore import cards from PyQt5.Qt import QPlainTextEdit from PyQt5.uic.Compiler.qtproxies import QtGui class App(QMainWindow): def __init__(self): super().__init__() self.title = 'Flash Cards' self.left = 10 self.top = 10 self.width = 640 self.height = 480 self.initUI() def initUI(self): self.allCards = [] self.cardShow = 0 self.backShow = 0 self.setWindowTitle(self.title) self.windowApp = self.frameGeometry() self.screenRes = app.desktop().screenGeometry() centerPoint = QDesktopWidget().availableGeometry().center() self.windowApp.moveCenter(centerPoint) self.move(self.windowApp.topLeft()) self.setFixedSize((self.screenRes.width() / 2.5),(self.screenRes.height() /2.25)) #text displays self.l1 = QPlainTextEdit(self) se…
has comment: http://stackoverflow.com/comment/91429379
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91429311
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52243686
has comment: http://stackoverflow.com/comment/91429563
tagged with: python
has comment: http://stackoverflow.com/comment/91431383
has title: PyQt5 QfileDialog specifically save file as python file
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/91429693
downvote count: 1
has comment: http://stackoverflow.com/comment/91430998
has comment: http://stackoverflow.com/comment/91429369
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/91429319
has comment: http://stackoverflow.com/comment/91429499
has comment: http://stackoverflow.com/comment/91431460

http://stackoverflow.com/comment/91275978
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52163240
has text: what is your expected output?
score: 0

http://stackoverflow.com/comment/91343719
type: Comment
type: QuestionComment
has text: Actually looking again, you *could* get it right by also updating `xopt` and `yopt` (in your case as `yopt += thing_speed*(someconstant - 1)`, but I'd strongly suggest to rather store the coordinates of each object and not pass the offsets (the `opt` values) to your drawing function.
score: 1
comment on: http://stackoverflow.com/q/52188563

http://stackoverflow.com/q/52180520
tagged with: python
tagged with: destructor
has title: Python how to ensure file writing completely when closing program?
has comment: http://stackoverflow.com/comment/91311179
downvote count: 0
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52180944
type: Question
has comment: http://stackoverflow.com/comment/91311012
upvote count: 1
answer count: 1
favorite count: 0
has body: I have a python script which dump yaml file every second while running. However, I found sometimes the yaml file is not completed. My guess is it is coincidence that at the same time I am closing the progress (the script is running in Windows commend line), while the file is saving. Sample code as following: class State(object): def __init__(self): ... self.__t = threading.Thread(name='StateAutoSave', target=self.__auto_save) self.__t.start() def __auto_save(self): while 1: try: ... self.__save() except Exception as err: logging.exception(err) time.sleep(1) def __save(self): ... with open(self.__yaml_file, 'w') as outfile: yaml.dump(data, outfile, default_flow_style=False) How to avoid this problem? or is there a method like destructor function in python, so that we can do something when the program is being closed? (It seems that 'with' does not fully work here)
has comment: http://stackoverflow.com/comment/91323293

http://stackoverflow.com/q/52201990
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91353263
has comment: http://stackoverflow.com/comment/91353413
score: 22
has body: I'm doing a time complexity analysis of an algorithm and need to know what kind of complexities certain numpy operations have. For some, I assume they match the underlying mathematical operation. Like np.dot(array1, array2) would be O(n). For others, I am not as sure. For example, is np.array(my_array) O(1)? or is it O(n)? Does it simply reassign a pointer or is it iterating over the list and copying out each value? I want to be sure of each operation's complexity. Is there somewhere I can find this information? Or should I just assume they match the mathematical operation?
has comment: http://stackoverflow.com/comment/91353199
answer count: 2
tagged with: time-complexity
downvote count: 1
accepted answer: http://stackoverflow.com/a/52208910
upvote count: 23
favorite count: 0
tagged with: big-o
has answer: http://stackoverflow.com/a/52208910
has title: Is there a list of big O complexities for the numpy library?
tagged with: python
has answer: http://stackoverflow.com/a/52202378
has comment: http://stackoverflow.com/comment/91364310
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52202378

http://stackoverflow.com/comment/91442692
type: QuestionComment
comment on: http://stackoverflow.com/q/52246669
has text: @MaharshiRoy You don't need a trie to do this, just a set. I'm not sure you understand what a trie is. Please see my answer below
score: 0
type: Comment

http://stackoverflow.com/comment/91212529
has text: if you are uncertain of position, then use the escape character method although you still do not need to create 2 dataframes. Read in the csv by just selecting the specific columns you'd like. Don't read in the whole csv then select the columns. You are using 20X the memory by doing that if you are selecting 5/6 columns out of 100.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52130812

http://stackoverflow.com/q/52168533
linked to: http://stackoverflow.com/q/51551173
accepted answer: http://stackoverflow.com/a/52168783
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has body: I created a script to go over the needed data, using pandas. I'm now receiving more files that I need to go over, and sadly these files do not have the same headers. For example I have placed in my list of columns to use 'id_num' and in some of the files it appears as 'num_id'. Is it possible to still use the usecols list I created, and allow certain elements in it to "connect" with different header strings, for example by using regex?
has comment: http://stackoverflow.com/comment/91289435
has title: How to use usecols elements which are regex rather than strings?
tagged with: pandas
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/60116315
favorite count: 0
has comment: http://stackoverflow.com/comment/91287825
has answer: http://stackoverflow.com/a/52168783
has comment: http://stackoverflow.com/comment/91287263
tagged with: python
tagged with: regex

http://stackoverflow.com/comment/91266553
comment on: http://stackoverflow.com/a/52158173
type: AnswerComment
score: 0
type: Comment
has text: Oh okay that makes much more sense as to where the “b’ ‘“ came from. Thank you.

http://stackoverflow.com/comment/91340923
comment on: http://stackoverflow.com/a/52195640
type: Comment
has text: Note: This is strictly an implementation detail of the current version of CPython (the reference interpreter). The overallocation rules have changed over time, can continue to change in the future, and likely differ on every other non-CPython interpreter (e.g. Jython might reasonably use `ArrayList` under the hood and inherit its behavior). No documented language feature requires any specific implementation. Relying on a specific resizing algorithm is a bad idea.
score: 12
type: AnswerComment

http://stackoverflow.com/comment/91341778
type: Comment
has text: Thanks, that's similar to the second solution in the question. I just can't believe that the broadcasting doesn't work in pandas...
comment on: http://stackoverflow.com/a/52196192
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91305612
comment on: http://stackoverflow.com/q/52177780
type: Comment
type: QuestionComment
has text: Do you wants to send text on textarea ?
score: 1

http://stackoverflow.com/q/52232559
tagged with: python
accepted answer: http://stackoverflow.com/a/52238949
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91414844
score: 3
has body: when comparing this two ways of doing the same thing: import numpy as np import time start_time = time.time() for j in range(1000): bv=np.loadtxt('file%d.dat' % (j+1)) if(j%100==0): print bv[300,0] T1=time.time() - start_time print("--- %s seconds ---" % T1) and import numpy as np import time start_time = time.time() for j in range(1000): a=open('file%d.dat' % (j+1),'r') b=a.readlines() a.close() for i in range(len(b)): b[i]=b[i].strip("\n") b[i]=b[i].split("\t") b[i]=map(float,b[i]) bv=np.asarray(b) if(j%100==0): print bv[300,0] T1=time.time() - start_time print("--- %s seconds ---" % T1) I have noticed that the second one is way faster. Is there any way to have something as concise as the first method and as fast as the second one? Why is loadtxt so slow with respect to performing the same task manually?
upvote count: 3
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/15096269
linked to: http://stackoverflow.com/q/26347297
has comment: http://stackoverflow.com/comment/91414774
has answer: http://stackoverflow.com/a/52238949
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91414449
linked to: http://stackoverflow.com/q/18259393
favorite count: 0
has title: numpy.loadtxt is way slower than open.....readlines()

http://stackoverflow.com/a/52159527
has comment: http://stackoverflow.com/comment/91445531
downvote count: 0
answers question: http://stackoverflow.com/q/52142180
type: Answer
has body: If you do the key combination in the browser, you will see this only brings up the 'save page' dialog box. You need to additionally send ALT+S to save the page, in Windows it will be saved in your Downloads folder by default. saveas = ActionChains(driver).key_down(Keys.CONTROL).send_keys('S').key_up(Keys.CONTROL).send_keys('MyDocumentName').key_down(Keys.ALT).send_keys('S').key_up(Keys.ALT) EDIT: ActionChains are unreliable. It would be easier not to interact with the browser GUI. from selenium import webdriver driver = webdriver.Chrome(executable_path=r"C:\Program Files (x86)\Selenium\chromedriver.exe") driver.get("http://www.example.com") with open('page.html', 'w') as f: f.write(driver.page_source)
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/140217270

http://stackoverflow.com/comment/91323214
type: Comment
type: QuestionComment
has text: If the problem is in C++ code, why not call it from a stand-alone executable? If you need to debug the Python interface also, make a Python script that crashes, and debug from Python. There is no need to dig through so many layers! Also, instrumentation is your friend. If the out-of-bounds write triggers this, MATLAB might crash but a stand-alone executable might not. Instrumentation (e.g. sanitizer) might help find it quicker.
comment on: http://stackoverflow.com/q/52177390
score: 0

http://stackoverflow.com/comment/91319472
type: Comment
type: QuestionComment
has text: Got KeyError: 'data'. So tried removing ['data'] and got this result: dataset dimension {'Region': {'label': 'region', 'category': {'i... label Folkmängden efter region, tabellinnehåll och år source Statistiska centralbyrån (SCB) status {'50': '..'} updated 2018-09-05T11:52:00Z value [7931193, 8004270, 8081142, 8115165, 8129129, ... Which has the values I want but not the years.
comment on: http://stackoverflow.com/q/52183449
score: 0

http://stackoverflow.com/q/52122399
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52122474
has body: So I have two dataframes eqdf symbol qty 0 DABIND 1 1 INFTEC 6 2 DISHTV 8 3 HINDAL 40 4 NATMIN 5 5 POWGRI 40 6 CHEPET 6 premdf share strike lprice premperc d_strike 0 HINDAL 250.0 237.90 1.975620 5.086171 1 RELIND 1280.0 1254.30 1.642350 2.048952 2 POWGRI 205.0 201.15 1.118568 1.913995 I want to compare columns premdf['share'] and eqdf['symbol'] and if there is a match premperc,d_strike,strike value is to be added to the end of the eqdf row in which there is a match. I have tried eqdf.loc[eqdf['symbol']==premdf['share'],eqdf['premperc'] == premdf['premperc']] I keep getting errors ValueError: Can only compare identically-labeled Series objects Expected Output: eqdf symbol qty premperc d_strike strike 0 DABIND 1 NaN NaN NaN 1 INFTEC 6 NaN NaN NaN 2 DISHTV 8 NaN NaN NaN 3 HINDAL 40 1.975620 5.086171 250.0 4 NATMIN 5 NaN NaN NaN 5 POWGRI 40 1.118568 1.913995 205.0 6 CHEPET 6 NaN NaN NaN What is the correct way to do this? Thanks
type: Question
tagged with: pandas
upvote count: 1
has title: Compare two dataframes, one column, and add certain values on match?
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52122474
tagged with: python

http://stackoverflow.com/comment/91687169
has text: Thank you, it wasnt really written that it was only the metadata ! I thought i could download this file querying one more time the api
comment on: http://stackoverflow.com/a/52169216
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52141780
tagged with: amazon-elastic-beanstalk
has answer: http://stackoverflow.com/a/52168749
has title: How can I handle multiple Python requests on my AWS EC2 instance?
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/10938360
has body: I have a Flask app deployed on Elastic Beanstalk onto an EC2 instance on AWS. If 100 people simultaneously connected to my server, then wouldn't that mean that they have to wait in a queue of 100 since the app can only handle one instance at a time? How can I make it so that I can handle more requests using the same IP address to connect to? Thanks!
type: Question
tagged with: amazon-web-services
tagged with: flask
score: 0
tagged with: amazon-ec2
answer count: 1

http://stackoverflow.com/a/52138363
has body: Here code you can try: from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait wait = WebDriverWait(driver, 10) #... fromPlace = "Delhi Indira Gandhi" #If will not enter text to FROM field, uncomment click code below #driver.find_elements_by_css_selector('#s2id_location_from a').click() driver.find_element_by_id('s2id_autogen12').send_keys(fromPlace) wait.until(EC.visibility_of_element_located((By.XPATH, "//div[@class='select2-result-label' and contains(.,'"+ fromPlace +"')]"))).click()
has comment: http://stackoverflow.com/comment/91227020
has comment: http://stackoverflow.com/comment/91226996
score: 0
has comment: http://stackoverflow.com/comment/91238276
type: Answer
answers question: http://stackoverflow.com/q/52137903

http://stackoverflow.com/q/52117827
upvote count: 2
score: 1
has title: Fill area between 2 lines (when one is below another)
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52118010
type: AnsweredQuestion
tagged with: matplotlib
has body: When this is run, the graph shown does not shade some parts that are below 5. How should I edit it such that it covers the entire area? import matplotlib.pyplot as plt x = [1,2,3,4,5,6,7,8,9,10] y = [4,9,1,3,6,2,4,7,6,3] z = [5]*len(y) plt.plot(x,y) plt.plot(x,z) plt.fill_between(x,y,z,where=[(y[i]&lt;z[i]) for i in range(len(x))],facecolor='r') plt.show()
answer count: 1
accepted answer: http://stackoverflow.com/a/52118010
favorite count: 0
tagged with: python

http://stackoverflow.com/a/52213127
downvote count: 1
has comment: http://stackoverflow.com/comment/91377923
has comment: http://stackoverflow.com/comment/91375853
has comment: http://stackoverflow.com/comment/91376585
answers question: http://stackoverflow.com/q/52213070
has comment: http://stackoverflow.com/comment/91377913
has comment: http://stackoverflow.com/comment/91375868
has comment: http://stackoverflow.com/comment/91375889
has body: Try the below, you don't need regex for this: &gt;&gt;&gt; import random,string &gt;&gt;&gt; l=random.sample(string.ascii_lowercase,4) &gt;&gt;&gt; l.append(str(random.randint(0,10))) &gt;&gt;&gt; random.shuffle(l) &gt;&gt;&gt; ''.join(l) 'iNx1k' &gt;&gt;&gt; Or if want more: import random,string lst=[] for i in range(3): l=random.sample(string.ascii_lowercase,4) l.append(str(random.randint(0,10))) random.shuffle(l) lst.append(''.join(l)) Update: import random,string lst=[] for i in range(3): l=random.sample(string.ascii_lowercase,4) l[-1]=l[0] l.append(str(random.randint(0,10))) random.shuffle(l) lst.append(''.join(l)) print(lst) To answer yours: import re def check(val): return len(set(val))!=len(val) and len(re.sub('\d+','',val)) and val.islower() and len(val)==5 a = check("a1abc") print(a)
type: Answer
has comment: http://stackoverflow.com/comment/91375995
has comment: http://stackoverflow.com/comment/91375767
has comment: http://stackoverflow.com/comment/91375801
score: 0
has comment: http://stackoverflow.com/comment/91377922
upvote count: 1

http://stackoverflow.com/a/52185519
type: Answer
accepted answer of: http://stackoverflow.com/q/52185208
answers question: http://stackoverflow.com/q/52185208
type: AcceptedAnswer
score: 0
has body: If you round the rebuilt values before converting to integers, you get zero failed ints. That is, use rebuilt_int = np.round(rebuilt_float).astype(np.int64) The output is then Failed FLOATS: 11062 Failed INTS: 0 Sum of FLOATS: 4999950000.0 Sum of INTS: 4999950000

http://stackoverflow.com/q/52231902
favorite count: 0
has answer: http://stackoverflow.com/a/52233831
has title: Conditional Subtraction of rows in Python Pandas Dataframe
upvote count: 2
type: UnansweredQuestion
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/91413362
score: 1
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/91413405
tagged with: pandas
has body: I am trying to solve a problem at hand as explained. I have a Dataframe as shown below: Date Item Type Qty Price 1/1/18 Orange Add 100 25 5/1/18 Orange Add 20 40 8/1/18 Orange Add 40 20 18/1/18 Orange Add 10 35 27/2/18 Orange Sub 100 55 15/4/18 Orange Sub 30 45 and I want to get the intermediate Dataframe like below: Date Item Type Qty Price Diff 1/1/18 Orange Add 0 25 30 5/1/18 Orange Add 0 40 5 8/1/18 Orange Add 30 20 25 18/1/18 Orange Add 10 35 and then the final Dataframe I want it like this below: Date Item Type Qty Price 8/1/18 Orange Add 30 20 18/1/18 Orange Add 10 35 NOTE: Diff is a difference of Sub and Add Price. And Qty is also updated with Qty of Sub subtracted from Qty of Add. Could anyone of you please help with the way it can be achieved. I was trying with groupby, apply and transform but till now I have not got this. I have below code, still in development and not complete: def FruitSummary(): df = pd.DataFrame([ ['01/1/18', 'Orange', 'Add', 100, 25], ['05/1/18', 'Orange', 'Add', 20, 40], ['08/1/18', 'Orange', 'Add', 40, 20], ['18/1/18', 'Orange', 'Add', 10, 35], ['27/2/18', 'Orange', 'Sub', 100, 55], ['15/4/18', 'Orange', 'Sub', 30, 45], ['02/1/18', 'Banana', 'Add', 110, 7], ['04/1/18', 'Banana', 'Add', 20, 9], ['11/1/18', 'Banana', 'Add', 40, 4], ['10/2/18', 'Banana', 'Add', 10, 3], ['15/3/18', 'Banana', 'Sub', 100, 9], ['15/4/18', 'Banana', 'Sub', 50, 8], ['10/3/18', 'Kiwi', 'Add', 80, 29], ['12/3/18', 'Berry', 'Add', 25, 5], ['18/4/18', 'Berry', 'Add', 15, 8]], columns=['Date', 'Item', 'Type', 'Qty', 'Price']) print(df) def fruit_stat(dfIN): print(dfIN) print((dfIN['Type'] == 'Sub').unique(), (dfIN['Type'] == 'ODD').unique()) if len(dfIN) &gt; 1 and (True in (dfIN['Type'] == 'Sub').unique()): print(dfIN['Item'].iloc[1], "'len &gt; 1'", "'Sub True'") dfFS = df.groupby(['Item']).apply(fruit_stat) print(dfFS)
answer count: 1
has comment: http://stackoverflow.com/comment/91413402

http://stackoverflow.com/a/52246545
has comment: http://stackoverflow.com/comment/91441179
type: Answer
upvote count: 3
has body: Try str.format with "General format" as described here. In [1]: print('{:.9g}'.format(8.5)) 8.5 In [2]: print('{:.9g}'.format(9.0)) 9
score: 3
answers question: http://stackoverflow.com/q/52246391
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91441340
accepted answer of: http://stackoverflow.com/q/52246391

http://stackoverflow.com/comment/91240126
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52145195
has text: The returned function as a reference to the variable, hence it is not garbage collected.

http://stackoverflow.com/q/52124737
answer count: 3
accepted answer: http://stackoverflow.com/a/52125774
linked to: http://stackoverflow.com/q/44392748
tagged with: python
tagged with: midi
score: 2
type: AnsweredQuestion
tagged with: download
has answer: http://stackoverflow.com/a/52125774
has comment: http://stackoverflow.com/comment/91201697
possible better answer: http://stackoverflow.com/a/52124813
tagged with: python-requests
type: Question
has body: I'm trying to download a series of classical music midi files with python and the requests library. Unfortunately, I can't seem to actually download the midi files themselves. The only thing I'm downloading is HTML files. I have searched SO and tried some other solutions, such as this post, and this post, but both solutions didn't work for me. Here is the code I've written: from bs4 import BeautifulSoup import requests import re url = 'http://www.midiworld.com/classic.htm' headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'} r = requests.get(url, headers=headers) data = r.text soup = BeautifulSoup(data, "html.parser") links = [] for link in soup.find_all("a", href=re.compile("mid$")): links.append(link['href']) def get_filename(links): filenames = [] """ Will return a list of filenames for the files to be downloaded """ for link in links: url = link if url.find('/'): f_name = url.rsplit('/', 1)[1] print(url.rsplit('/', 1)[1]) filenames.append(f_name) return filenames def download_files(links, filenames): for link, filename in zip(links, filenames): r = requests.get(url, allow_redirects=True) with open(filename, 'wb') as saveMidi: saveMidi.write(r.content) filenames = get_filename(links) download_files(links, filenames) I can't figure out why I'm getting html files returned. Any ideas on how to get the midi files downloaded properly?
tagged with: web-crawler
upvote count: 2
has answer: http://stackoverflow.com/a/66589399
has title: Why can't I download a midi file with python requests?
downvote count: 0
linked to: http://stackoverflow.com/q/48239112
has answer: http://stackoverflow.com/a/52124813
favorite count: 0

http://stackoverflow.com/a/52157889
upvote count: 2
has comment: http://stackoverflow.com/comment/91294410
accepted answer of: http://stackoverflow.com/q/52157511
answers question: http://stackoverflow.com/q/52157511
has comment: http://stackoverflow.com/comment/91294525
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91291306
has body: That means the project top directory. There should be a setup.py file in that dir
type: Answer
score: 2

http://stackoverflow.com/a/52195390
answers question: http://stackoverflow.com/q/52195378
upvote count: 1
has body: Make sure that you're adding /dir1/dir2/file1.json to your Docker image or mounting it as a volume. Having the file present at that location on the host isn't sufficient.
type: Answer
has comment: http://stackoverflow.com/comment/91340548
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91340387

http://stackoverflow.com/comment/91362282
comment on: http://stackoverflow.com/a/52206169
type: AnswerComment
score: 2
type: Comment
has text: Note `iterrows` is not recommended when vectorised operations are possible.

http://stackoverflow.com/comment/91284263
type: QuestionComment
comment on: http://stackoverflow.com/q/52129773
has text: If you want to reduce dimensions, why not start with lower n_features in HashingVectorizer in the first place?
type: Comment
score: 0

http://stackoverflow.com/q/52134006
has answer: http://stackoverflow.com/a/52134075
has comment: http://stackoverflow.com/comment/91218306
has comment: http://stackoverflow.com/comment/91218357
has body: Lokesh-mac-mini-pro-2:instabot.py-master Lokeshmacminipro$ python example.py 02.09.2018_10:03 Instabot v1.2.0 started at 02.09.2018 10:03: 02.09.2018_10:03 Trying to login as moneshrallapalli... Traceback (most recent call last): File "example.py", line 52, in &lt;module&gt; unfollow_whitelist=['example_user_1', 'example_user_2']) File "/Users/lokemone/Desktop/instabot.py-master/src/instabot.py", line 234, in __init__ self.login() File "/Users/lokemone/Desktop/instabot.py-master/src/instabot.py", line 303, in login self.user_id = ui.get_user_id_by_login(self.user_login) File "/Users/lokemone/Desktop/instabot.py-master/src/userinfo.py", line 42, in get_user_id_by_login json_info = json.loads(re.search('{"activity.+show_app', info.text, re.DOTALL).group(0)+'":""}') AttributeError: 'NoneType' object has no attribute 'group' Lokesh-mac-mini-pro-2:instabot.py-master Lokeshmacminipro$ please tell how to avoid AttributeError: 'NoneType' object has no attribute ‘group'
type: Question
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/52134062
has title: AttributeError: 'NoneType' object has no attribute ‘group’ {for instagram}
has comment: http://stackoverflow.com/comment/91218405
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91218416
has comment: http://stackoverflow.com/comment/91402315
tagged with: python

http://stackoverflow.com/a/52197387
answers question: http://stackoverflow.com/q/52195301
score: 0
has body: Using update is not going to work, because the value for for the key organizations is a sequence and loads as the list-like type CommentedSeq. So append-ing would be the right thing to do. That that doesn't work is a bit unclear since you don't provide that input that you start with, nor the code used when doing the appending which gets an AttributeError on CommentedMap. Here is what works if you have one organization and add another: import sys import ruamel.yaml yaml_str = """\ version: x.x.x is_enterprise: 'true' license: secrets/license.txt organizations: - description: xyz name: abc """ org_data = dict( description='pqr', name='def', ) yaml = ruamel.yaml.YAML() yaml.indent(mapping=4, sequence=4, offset=2) cur_yaml = yaml.load(yaml_str) cur_yaml['organizations'].append(org_data) yaml.dump(cur_yaml, sys.stdout) This gives: version: x.x.x is_enterprise: 'true' license: secrets/license.txt organizations: - description: xyz name: abc - description: pqr name: def If you have no organizations yet, make sure your input YAML looks like: version: x.x.x is_enterprise: 'true' license: secrets/license.txt organizations: [] On older versions of Python the order of the keys in the data you added is not guaranteed. To enforce that order on older version as well do: org_data = ruamel.yaml.comments.CommentedMap((('description', 'pqr'), ('name', 'def'))) or org_data = ruamel.yaml.comments.CommentedMap() org_data['description'] = 'pqr' org_data['name'] = 'def'
has comment: http://stackoverflow.com/comment/91344614
type: Answer

http://stackoverflow.com/q/52224432
has answer: http://stackoverflow.com/a/52227298
has answer: http://stackoverflow.com/a/52225729
tagged with: class
answer count: 3
favorite count: 0
has title: Tensorflow graph inside class - how to manage sessions and scopes
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/91400371
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/52323131
has body: I am trying to build a generic tensorflow infrastructure wrapped inside a simple one layer NN class (see code below). I will be creating many NNets so I was wondering what was the best way to manage the sessions and the variables. Typically, I'd like to get tf.trainable_variables() for only one network, not all of them (in the "show" function) so that I can print the network I want. I also have to pass the session variable "sess" to every function, so that the variables are not re-initialized. I think I am not doing everything properly... Can someone help ? class oneLayerNN: """ Implements a 1 hidden-layer neural network: y = W2 * ([W1 * x + b1]+) + b1 """ def __init__(self, ...): ... self.initOp = tf.global_variables_initializer() def show(self, sess): tvars = tf.trainable_variables() tvals = sess.run(tvars) for var, val in zip(tvars,tvals): print(var.name, val) print() def initializeVariables(self, sess): sess.run(self.initOp) def forwardPropagation(self, sess, x): labels = sess.run(self.yHat, feed_dict={self.x: x}) return labels def train(self, sess, dataset, epochs, batchSize, debug=False, verbose=False): dataset = dataset.batch(batchSize) iterator = dataset.make_initializable_iterator() next_element = iterator.get_next() for epoch in range(epochs): sess.run(iterator.initializer) while True: try: batch_x, batch_y = sess.run(next_element) _, c = sess.run([self.optimizer, self.loss], feed_dict={self.x: batch_x, self.y: batch_y}) except tf.errors.OutOfRangeError: break with tf.Session() as sess: network.initializeVariables(sess) network.show(sess)
downvote count: 0

http://stackoverflow.com/q/52241539
has comment: http://stackoverflow.com/comment/91432399
has comment: http://stackoverflow.com/comment/91446685
has comment: http://stackoverflow.com/comment/91432798
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91433032
tagged with: python
tagged with: conv-neural-network
answer count: 0
has comment: http://stackoverflow.com/comment/91436292
has comment: http://stackoverflow.com/comment/91432810
has title: maxpooling2d keras does not do pooling at all
has body: I am writing a CNN for text classification. The max pooling2D layer seems does not work as the output shape is same as conv2D. I have attached my code and output shape below. Thanks for helping me! from keras.layers import Dense, Input, Flatten from keras.layers import Conv2D, MaxPooling2D, Embedding, Reshape, Concatenate, Dropout from keras import optimizers from keras.models import Model convs = [] filter_sizes = [2,4,8] BATCH_SIZE = 10 sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32') embedded_sequences = embedding_layer(sequence_input) reshape = Reshape((MAX_SEQUENCE_LENGTH, EMBEDDING_DIM,1))(embedded_sequences) conv_0 = Conv2D(filters = 128, kernel_size=(MAX_SEQUENCE_LENGTH, filter_sizes[0]), activation='relu')(reshape) conv_1 = Conv2D(filters = 128, kernel_size=(MAX_SEQUENCE_LENGTH, filter_sizes[1]), activation='relu')(reshape) conv_2 = Conv2D(filters = 128, kernel_size=(MAX_SEQUENCE_LENGTH, filter_sizes[2]), activation='relu')(reshape) maxpool_0 = MaxPooling2D(pool_size=(MAX_SEQUENCE_LENGTH - filter_sizes[0] + 1,1), strides=(1,1), padding='same')(conv_0) maxpool_1 = MaxPooling2D(pool_size=(MAX_SEQUENCE_LENGTH - filter_sizes[1] + 1, 1), strides=(1,1), padding='same')(conv_1) maxpool_2 = MaxPooling2D(pool_size=(MAX_SEQUENCE_LENGTH - filter_sizes[2] + 1, 1), strides=(1,1), padding='same')(conv_2) concatenated_tensor = Concatenate(axis = 2)([maxpool_0, maxpool_1, maxpool_2]) flatten = Flatten()(concatenated_tensor) dense = Dense(2048, activation='relu')(flatten) dense_out = Dropout(0.5)(dense) preds = Dense(label_dim, activation='sigmoid')(dense_out) model = Model(sequence_input, preds) opt = optimizers.Adam(lr=0.0001) model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['acc']) output shape for each layer
tagged with: max-pooling
type: Question
has comment: http://stackoverflow.com/comment/91446704
tagged with: keras
score: 0
tagged with: deep-learning

http://stackoverflow.com/comment/91231555
has text: I now have: TypeError: expected a string or other character buffer object
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52140439

http://stackoverflow.com/q/52248937
has answer: http://stackoverflow.com/a/52248960
accepted answer: http://stackoverflow.com/a/52248980
favorite count: 0
has body: I am trying to compute the min value of 2nd column which belong to a certain 1st column values. so my dataframe is as follows: name CEMS star ACC CEMS-1 3 ACC CEMS-2 4 ACC CEMS-3 5 ACC CEMS-4 5 ARTi CEMS-1 4 ARTi CEMS-2 5 ARTi CEMS-3 4 ARTi CEMS-4 5 Now I want to find a minimum star value for each name in a separate column from the different values of CEMS I want my dataframe to look like this: Name CEMS star min ACC CEMS-1 3 ACC CEMS-2 4 ACC CEMS-3 5 ACC CEMS-4 5 3 ARTi CEMS-1 4 ARTi CEMS-2 5 ARTi CEMS-3 4 ARTi CEMS-4 5 4 Can anyone help me out?
type: Question
tagged with: python
score: -1
downvote count: 2
answer count: 3
upvote count: 1
possible better answer: http://stackoverflow.com/a/52248953
has answer: http://stackoverflow.com/a/52248953
has comment: http://stackoverflow.com/comment/91445946
has answer: http://stackoverflow.com/a/52248980
tagged with: dataframe
has title: Add min value of a group in only the last row of the group with pandas
has comment: http://stackoverflow.com/comment/91445984
tagged with: pandas-groupby
tagged with: pandas
type: AnsweredQuestion

http://stackoverflow.com/a/52330046
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/52142475
has body: The values in y are un-indexed matrix. The case x['A'] = y works here as it take the first item from the matrix and assign it to the 'A'. Similarly, x = pd.DataFrame(np.zeros((4, 2)), columns=['A', 'B']) y = np.random.randn(4, 2) x'A', 'B' = y will also work because the extra data is being discarded by pandas. If you're trying to pass less columns, say: x = pd.DataFrame(np.zeros((4, 2)), columns=['A', 'B']) y = np.random.randn(4, 1) x'A', 'B' = y That will also work as it will assign the same values to both the columns. This case is similar to x['A'] = 0 which will replace all the data in column A with zeros.
downvote count: 1
score: 5
has comment: http://stackoverflow.com/comment/91776550
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91793510
answers question: http://stackoverflow.com/q/52142475

http://stackoverflow.com/a/56406567
answers question: http://stackoverflow.com/q/52122389
has body: Use these following commands, this will solve the error: sudo apt-get install postgresql sudo apt-get install python-psycopg2 sudo apt-get install libpq-dev A)For error: flask-babel 0.11.1 has requirement Babel>=2.3, but you'll have babel 1.3 which is incompatible. pip install flask-htmlmin For Error: testtools 2.3.0 has requirement extras>=1.0.0, but you'll have extras 0.0.3 which is incompatible. enter: wget https://files.pythonhosted.org/packages/03/e9/e915af1f97914cd0bc21e125fd1bfd4106de614a275e4b6866d9ac/extras-1.00-py2.py3-none-any.whl
score: 0
type: Answer

http://stackoverflow.com/comment/91268461
type: AnswerComment
score: 0
type: Comment
has text: >>> d = {'message': [{'name': 'raghav', 'id': 10}, {'name': 'raghav', 'id': 11}]} >>> for key, value in d.items(): ... d[key] = [dict([t for k in value for t in k.items()])] ... print d
comment on: http://stackoverflow.com/a/52159038

http://stackoverflow.com/a/52224109
type: Answer
has comment: http://stackoverflow.com/comment/91471051
downvote count: 0
answers question: http://stackoverflow.com/q/52222834
has comment: http://stackoverflow.com/comment/91403724
score: 3
has comment: http://stackoverflow.com/comment/91402729
has comment: http://stackoverflow.com/comment/91487591
has body: pyvips can process huge images quickly using just a small amount of memory, and supports palette TIFF images. Unfortunately it won't support the extra geotiff tags, since libtiff won't work on unknown tag types. You'd need to copy that metadata over in some other way. Anyway, if you can do that, pyvips should work on your image. I tried this example: import sys import pyvips # the 'sequential' hint tells libvips that we want to stream the image # and don't need full random access to pixels ... in this mode, # libvips can read, process and write in parallel, and without needing # to hold the whole image in memory image = pyvips.Image.new_from_file(sys.argv[1], access='sequential') image = image.gaussblur(2) image.write_to_file(sys.argv[2]) On an image of the type and size you have, generating a JPEG-compressed TIFF: $ tiffinfo x2.tif TIFF Directory at offset 0x1a1c65c6 (438068678) Image Width: 23899 Image Length: 18330 Resolution: 45118.5, 45118.5 pixels/cm Bits/Sample: 8 Compression Scheme: None Photometric Interpretation: palette color (RGB from colormap) ... $ /usr/bin/time -f %M:%e python3 ~/try/blur.py x2.tif x3.tif[compression=jpeg] 137500:2.42 So 140MB of memory, 2.5 seconds. The output image looks correct and is 24mb, so not too far off yours.
has comment: http://stackoverflow.com/comment/91403771
upvote count: 3

http://stackoverflow.com/q/52184372
favorite count: 0
has answer: http://stackoverflow.com/a/52184500
type: UnansweredQuestion
tagged with: python
has title: returning whole string in Python; Remove None
has body: I am a beginner in Python and I want to remove all Capital numbers from the string. I have tried below code but getting None after each function call. What should I return from the function? def remove_capitals(a_string): for latter in a_string: if not (ord(latter) in range(65,91)): print(latter,end="") else: continue print(remove_capitals("A1B2C3D")) print(remove_capitals("Georgia Institute of Technology")) I am getting below Output 123None eorgia nstitute of echnologyNone
score: 1
has comment: http://stackoverflow.com/comment/91318388
type: Question
has comment: http://stackoverflow.com/comment/91318409
answer count: 2
tagged with: function
has comment: http://stackoverflow.com/comment/91318482
has comment: http://stackoverflow.com/comment/91318379
has comment: http://stackoverflow.com/comment/91318389
has answer: http://stackoverflow.com/a/52184415
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91318364
tagged with: string

http://stackoverflow.com/a/52217427
answers question: http://stackoverflow.com/q/52216449
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: The data which you want starts from tr[3]//td[1] - contains company Name as text tr[3]//td[3] - contains email but in href attribute So looping over tr starts from index 3 to rows WebElement length rows = driver.find_elements_by_xpath('//*[@id="Body_tbl"]/tbody/tr') for index, element in enumerate(rows,start=2): companyName = rows.find_element_by_xpath("//tr[" + index + "]//td[1]") if companyName is not None: companyName.getText(); companyEmail = driver.find_element_by_xpath("//tr[" + index + "]//td[3]/a") if companyEmail is not None: companyEmail.get_attribute("href"); // this will give exact if email is there Note - I was not able to test code, please take care of boundary conditions. Thanks

http://stackoverflow.com/comment/91372820
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52210917
has text: @JavierBuzzi Thank you for the advice but I dont see any other way of doing it. I added the relevant models. A user may have multiple Requisitions which may have multiple lines per Requisition. I want to get all the headers that have lines with the 2 filters i applied which is why i was adding them to a list. What approach would you take?
score: 0

http://stackoverflow.com/a/52259656
upvote count: 9
has comment: http://stackoverflow.com/comment/91466899
answers question: http://stackoverflow.com/q/52259631
has comment: http://stackoverflow.com/comment/138625131
type: AcceptedAnswer
downvote count: 0
has body: I believe need indexing with str, it working with all iterables: df = pd.DataFrame({'col':[['a', 'b', 'c', 'd'],['a', 'b'],['a'], []]}) df['last'] = df['col'].str[-1] print (df) col last 0 [a, b, c, d] d 1 [a, b] b 2 [a] a 3 [] NaN strings are iterables too: df = pd.DataFrame({'col':['abcd','ab','a', '']}) df['last'] = df['col'].str[-1] print (df) col last 0 abcd d 1 ab b 2 a a 3 NaN
type: Answer
accepted answer of: http://stackoverflow.com/q/52259631
has comment: http://stackoverflow.com/comment/138479912
score: 9

http://stackoverflow.com/a/73098884
type: AcceptedAnswer
downvote count: 0
score: 1
has body: #Date first created: September 6, 2018 v.0 #Version: v.1, modified 2021/08/31 #This is a Rock, Paper, Scissors game. #Rock beats scissors, scissors beats paper, and paper beats rock. import random #variable declaration and initialization game_moves = ["Rock","Paper","Scissors"] def is_input_numeric(str_val): '''(string) -> bool Returns whether a string input contains ONLY numeric values greater than zero >>> is_input_numeric('4') True >>> is_input_numeric("like 7") False ''' return str_val.isnumeric() and int(str_val) > 0 and int(str_val) <= 20 def is_input_numeric_range(str_val): '''(string) -> bool Returns whether a string input contains ONLY a numeric value greater than zero but less than or equal to two >>> is_input_numeric_range('y') False >>> is_input_numeric_range('3') False >>> is_input_numeric_range('2') True ''' return str_val.isnumeric() and int(str_val) >= 0 and int(str_val) <= 2 def validate_rounds(): '''(string) -> string checks str_val and passes control to is_input_numeric function, then returns a string value >>> validate_rounds() -> is_input_numeric("time") False >>> validate_rounds() -> is_input_numeric('0') False >>> validate_rounds()-> is_input_numeric('10') True ''' valid_rounds = False while not valid_rounds: rounds = input("Enter number of rounds to play[min = 1, max = 20]: ") valid_rounds = is_input_numeric(rounds) return rounds def validate_player_input(): '''(string) -> string checks string and passes control to is_input_numeric_range function, then returns the string value >>> validate_player_input() -> is_input_numeric_range('-1') False >>> validate_player_input() -> is_input_numeric_range('i') False >>> validate_player_input() -> is_input_numeric_range('3') False >>> validate_player_input() -> is_input_numeric_range('0') True ''' valid_player_control = False while not valid_player_control: player_move = input("ONLY (0)Rock,(1)Paper,(2)Scissors, allowed: ") valid_player_control = is_input_numeric_range(player_move) return player_move def…
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52267206
answers question: http://stackoverflow.com/q/52267206
has comment: http://stackoverflow.com/comment/129170159

http://stackoverflow.com/a/52151512
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/91253335
score: 2
answers question: http://stackoverflow.com/q/52151122
has body: According to Python's time complexity documentation, slicing a list is O(k) where k is the length of the slice. The function calls itself recursively on the two slices, each with size n / 2 (ignoring off-by-one due to integer rounding). The recurrence relation is thus: T(n) = 2 T(n / 2) + O(n) ... where O(n) comes from the two slicing operations a[:m] and a[m:]. According to the Master Theorem, this is O(n log n). To make the algorithm O(n) as it should be, one could pass sub-array indices instead of directly slicing the array, or use numpy's array type.
has comment: http://stackoverflow.com/comment/91253405
downvote count: 0

http://stackoverflow.com/a/52148481
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52148463
type: Answer
has comment: http://stackoverflow.com/comment/91246898
answers question: http://stackoverflow.com/q/52148463
has comment: http://stackoverflow.com/comment/91246975
has body: ".".join(str(i) for i in tuple_A) should do the trick

http://stackoverflow.com/a/52242901
answers question: http://stackoverflow.com/q/52236796
has body: I managed to make it work but I don't know why it don't work with file = open("C:/Users/" + getpass.getuser() + "/Wiappro/name.txt").read() file = ast.literal_eval(file) nor with file = open("C:/Users/" + getpass.getuser() + "/Wiappro/name.txt") file = ast.literal_eval(file.read()) but worked with file = open("C:/Users/" + getpass.getuser() + "/Wiappro/name.json") read = file.read() read = ast.literal_eval(read)) I hope it will be usefull for other people
score: 0
type: Answer

http://stackoverflow.com/comment/91191104
type: Comment
has text: Brilliant. Thank you!
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52118692

http://stackoverflow.com/comment/91192723
has text: `self._temperature = temperature` you aren't using the property, you are using the private variable that the property uses. Use the property: `self.temperature = temperature`
comment on: http://stackoverflow.com/q/52120764
type: Comment
type: QuestionComment
score: 8

http://stackoverflow.com/q/52127370
linked to: http://stackoverflow.com/q/19703975
has comment: http://stackoverflow.com/comment/91317432
tagged with: sqlite
has comment: http://stackoverflow.com/comment/91212523
has title: user-defined function raised exception occurred
has comment: http://stackoverflow.com/comment/91332247
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91317999
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91318612
has comment: http://stackoverflow.com/comment/91206729
score: 1
has comment: http://stackoverflow.com/comment/91317420
has comment: http://stackoverflow.com/comment/91317340
type: Question
has body: I have following error when I'm using below user defined function with raw query: Django Version: 2.1 Exception Type: OperationalError Exception Value: user-defined function raised exception from django.db.backends.signals import connection_created from django.dispatch import receiver @receiver(connection_created) def extend_sqlite(connection=None, **kwargs): if connection.vendor == "sqlite": # sqlite doesn't natively support math functions, so add them cf = connection.connection.create_function cf('acos', 1, math.acos) cf('cos', 1, math.cos) cf('radians', 1, math.radians) cf('sin', 1, math.sin) Here are is my raw query. query = """SELECT id, (6367*acos(cos(radians(%2f)) *cos(radians(lat))*cos(radians(long)-radians(%2f)) +sin(radians(%2f))*sin(radians(lat)))) AS distance FROM ksApp_outlet group by id having distance &lt; %2f """ % ( float(lat), float(lng), float(lat), float(radius) ) outletdata = Outlet.objects.raw(query) Here is table schema fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('outletTitle', models.CharField(max_length=100, unique=True)), ('address', models.CharField(blank=True, max_length=100, null=True)), ('phoneNumber', models.CharField(blank=True, max_length=100, null=True)), ('picturesX', models.FileField(blank=True, null=True, upload_to='')), ('lat', models.CharField(blank=True, default='foobar', max_length=50, null=True)), ('long', models.CharField(blank=True, default=None, max_length=50, null=True)), ('region', models.CharField(blank=True, default=None, max_length=50, null=True)), ('cuisine', models.ForeignKey(blank=True, null=True, on_delete='CASCADE', to='ksApp.CuisineType')), ('merchantName', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='ksApp.Merchant')), ], Not sure what I'm doing wrong here. Can any one help me to figure out this error?
downvote count: 0
has comment: http://stackoverflow.com/comment/91317604
favorite count: 0

http://stackoverflow.com/comment/103391974
comment on: http://stackoverflow.com/q/52168491
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [RTSP stream and OpenCV (Python)](https://stackoverflow.com/questions/20891936/rtsp-stream-and-opencv-python)

http://stackoverflow.com/q/52153594
has comment: http://stackoverflow.com/comment/91328850
answer count: 0
has comment: http://stackoverflow.com/comment/91327027
duplicate of: http://stackoverflow.com/q/4151128
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91326924
tagged with: arrays
score: 0
linked to: http://stackoverflow.com/q/4151128
has comment: http://stackoverflow.com/comment/91260945
tagged with: matrix
has comment: http://stackoverflow.com/comment/91326236
has comment: http://stackoverflow.com/comment/91257560
has body: EDIT with more details about the data structure. (Please notice that even if it seems to be a duplicate question, it's a specific case of array to matrix transformation). In the end of the code below, after applying many operations to the same set of data, I've built a final 3D array by transforming a list of arrays into a 3D array (that's in the last lines of the code, details specified in comments). #!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import glob big_list = [] #list used to store all data built from multiple .txt files. for a in range(1,21): #loop to open and take data from multiple .txt files. for s in range(1,11): for e in range(1,4): #specify path (with vars from loop) path = '/home/user/plots/Files/a{0}_s{1}_e{2}_skeleton.txt'.format(a, s,e) archive = glob.glob(path) #if the .txt file's opened, starts operations with data taken from it. if (archive): movement = np.loadtxt(path) num_skeletons = int(len(movement)/20) list_for_array = [] #list to take all data from the file. for i in range(num_skeletons): #list_for_array is transformed in a 2D array: list_for_array.append(movement[(i*20):((i+1)*20),:3]) #that same 2D array is made into a 3D array: coords_array= np.array(list_for_array) # a 3D matrix is made from the 3D array. dist_matrix = np.zeros((num_skeletons,20,20)) for k in range(num_skeletons): for i in range(20): for j in range(20): dist_matrix[k,i,j] = np.linalg.norm(coords_array[k,i,:] - coords_array[k,j,:]) #end of the 3D matrix construction. #the 3D matrix is made into a list of 2D array (each array with 1 line and 400 columns). for m in range(num_skeletons): array = dist_matrix[m].reshape((1,400)) #the m 2D arrays are added to a list: big_list.append(array) #dist_matrix = None #now, big_list has all the data from all .txt files (many 2D arrays). big_array = np.array(big_list) #and finally, big_list is made into a 3D array, or, an array made of many 2D arrays. I didn't explain what's the deep meaning of the code because it…
has comment: http://stackoverflow.com/comment/91260427
type: UnansweredQuestion
tagged with: python
has title: Transform 3D array into a 2D matrix with NumPy

http://stackoverflow.com/q/52150440
has title: Get full module path to class
upvote count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has body: I'm using a wrapper to dock a Qt window in a program. The issue is the wrapper takes any window class as a str, then initialises it later, making it not very pythonic if you have split things over multiple files (see the original edit for an idea of how it works, not important to the question though). For example: import module.submodule.MainWindow: The path is "module.submodule.MainWindow" import module.submodule.MainWindow as MW: The path is "MW" from module import submodule: The path is "submodule.MainWindow" My current workaround is module.MainWindow.shpw(namespace="module.MainWindow"), but I would prefer not to be required to provide it as an argument I tried making a function to parse globals() to find the path, and it does work quite nicely at the top level. However, I found out that globals() is unique to each import, so it does nothing when called from within my template class. from types import ModuleType import inspect import site site_packages_loc = site.getsitepackages() default_modules = set([sys.modules[i] for i in set(sys.modules.keys()) &amp; set(sys.builtin_module_names)]) def get_class_namespace(search, globals_dict=None, path=[]): if globals_dict is None: globals_dict = globals() #Find all objects that are modules modules = {} for k, v in globals_dict.iteritems(): if v == search: return '.'.join(path + [v.__name__]) if isinstance(v, ModuleType) and v not in default_modules: modules[k] = v #Check recursively in each module for k, v in modules.items(): #Check it's not a built in module module_path = inspect.getsourcefile(v) if any(module_path.startswith(i) for i in site_packages_loc): continue module_globals = {func: getattr(v, func) for func in dir(v)} return_val = get_class_namespace(search, module_globals, path=path+[k]) if return_val is not None: return return_val Is there a better way to go about this, or could I somehow request the very top level globals() from within an import?
tagged with: python
has comment: http://stackoverflow.com/comment/91251543
answer count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/91251365

http://stackoverflow.com/comment/91481786
type: Comment
has text: What's a "PilImage" exactly?
type: QuestionComment
comment on: http://stackoverflow.com/q/52266935
score: 0

http://stackoverflow.com/a/52198654
type: Answer
has body: There are multiple things wrong here: for feature_colunm_name in feature_columns_to_use: X_train[feature_colunm_name] = CountVectorizer().fit_transform(X_train[feature_colunm_name]).todense() X_test[feature_colunm_name] = CountVectorizer().fit_transform(X_test[feature_colunm_name]).todense() 1) You are trying to assign mutliple columns (result of CountVectorizer will be a 2-d array where columns represent features) to a single column 'feature_colunm_name' of DataFrame. Thats not going to work and will produce error. 2) You are fitting the CountVectorizer again on the test data, which is wrong. You should use the same CountVectorizer object on test data that you used on trainind data and only call transform(), not fit_transform(). Something like: cv = CountVectorizer() X_train_cv = cv.fit_transform(X_train[feature_colunm_name]) X_test_cv = cv.transform(X_test[feature_colunm_name]) 3) GradientBoostingClassifier works well with sparse data. Its not mentioned in documentation yet (seems like a mistake on the documentation). 4) You seem to be transforming multiple columns of your original data to bag-of-words form. For that you will need to use those many CountVectorizer objects and then merge all the output data into a single array which you pass to GradientBoostingClassifier. Update: You need to setup something like this: # To merge sparse matrices from scipy.sparse import hstack result_matrix_train = None result_matrix_test = None for feature_colunm_name in feature_columns_to_use: cv = CountVectorizer() X_train_cv = cv.fit_transform(X_train[feature_colunm_name]) # Merge the vector with others result_matrix_train = hstack((result_matrix_train, X_train_cv)) if result_matrix_train is not None else X_train_cv # Now transform the test data X_test_cv = cv.transform(X_test[feature_colunm_name]) result_matrix_test = hstack((result_matrix_test, X_test_cv)) if result_matrix_test is not None else X_test_cv Note: If you have other columns also which you did not process through th…
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91346421
accepted answer of: http://stackoverflow.com/q/52194375
answers question: http://stackoverflow.com/q/52194375
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/91327446
comment on: http://stackoverflow.com/q/52188784
has text: Here it is: `https://i.imgur.com/TGJHFe1.jpg`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91265940
type: Comment
type: QuestionComment
has text: Is backend on your PYTHONPATH?
score: 0
comment on: http://stackoverflow.com/q/52157214

http://stackoverflow.com/q/52191628
favorite count: 0
tagged with: python-3.x
tagged with: python
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3391076
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/52191719
accepted answer: http://stackoverflow.com/a/52191719
has title: Assigning characters [a-c] to rows in Pandas Dataframe iteratively until end of column length
tagged with: series
has body: say I have a pandas dataframe with the following structure: col1 col2 0 Jack Jill 1 Michael Micah 2 Derrick Daliah 3 Martin Martha 4 Patrick Patricia 5 Dennis Denise I have a list of characters: characters = ['a', 'b', 'c'] I want to create a new column in the dataframe, so the df has the following structure (output): col1 col2 label 0 Jack Jill a 1 Michael Micah b 2 Derrick Daliah c 3 Martin Martha a 4 Patrick Patricia b 5 Dennis Denise c I thought I could do this by iterating through the two lists together, but zip only iteratres to the length of the shortest list: for x,y in zip(df['col1', characters): print(y) output: a b c and a nested for loop: for x in df['col1']: for y in characters: print(y) prints each character for every name in x in col1 (so I get a,b,c for Jack, a,b,c for Michael, etc.) If I could get the iteration to repeat for characters once the characters list is done, as displayed in my example output, I could append them to a list and then just: df['label'] = characters_list_for_df Any help would be great!
tagged with: pandas
downvote count: 0
answer count: 1
tagged with: string

qvtkwidget
tags question: http://stackoverflow.com/q/52213973
type: Tag
tag name: qvtkwidget

http://stackoverflow.com/a/52203447
has comment: http://stackoverflow.com/comment/91360133
type: Answer
score: 3
downvote count: 0
has body: I think your best option is to use tricontour. You already have the triangulation, right? It creates plots like this one: (from here) https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tricontour.html
has comment: http://stackoverflow.com/comment/91362090
has comment: http://stackoverflow.com/comment/91401043
has comment: http://stackoverflow.com/comment/91360250
upvote count: 3
answers question: http://stackoverflow.com/q/52202014
has comment: http://stackoverflow.com/comment/91360931
has comment: http://stackoverflow.com/comment/91357955

http://stackoverflow.com/a/59432060
has comment: http://stackoverflow.com/comment/109094868
type: Answer
answers question: http://stackoverflow.com/q/52261597
downvote count: 0
has comment: http://stackoverflow.com/comment/109954759
has comment: http://stackoverflow.com/comment/105313319
score: 31
has comment: http://stackoverflow.com/comment/109952114
has comment: http://stackoverflow.com/comment/109735282
has comment: http://stackoverflow.com/comment/109954998
has body: Took me a while to see this but I just added built-in support for keras in tqdm (version &gt;= 4.41.0) so you could do: from tqdm.keras import TqdmCallback ... model.fit(..., verbose=0, callbacks=[TqdmCallback(verbose=2)]) This turns off keras' progress (verbose=0), and uses tqdm instead. For the callback, verbose=2 means separate progressbars for epochs and batches. 1 means clear batch bars when done. 0 means only show epochs (never show batch bars).
upvote count: 31

http://stackoverflow.com/comment/91402080
comment on: http://stackoverflow.com/q/52159852
has text: You should build code from source using the instruction: https://tech.yandex.com/catboost/doc/dg/installation/python-installation-method-build-from-source-linux-macos-docpage/. Or you can wait for a few days, when the new version will be published on pypi, it will be there in the middle of September in version 0.10.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52238039
upvote count: 2
has comment: http://stackoverflow.com/comment/91445057
has body: The functions are inverses of each other, within some computational errors (which may be complex), and up to reordering of roots. pol_c = np.poly([-1, 1, 1, 10]) root_val = np.roots(pol_c) print(np.real_if_close(np.around(root_val, 6))) prints [10. -1. 1. 1.] which is the same as we started with, in another order. Of course, the order need not be the same: the original order of roots is lost when pol_c was formed, and there is no canonical order for the roots of polynomials (which are generally complex) anyway.
type: Answer
has comment: http://stackoverflow.com/comment/91443025
has comment: http://stackoverflow.com/comment/91446418
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52237570
has comment: http://stackoverflow.com/comment/91443242

http://stackoverflow.com/q/52237777
has answer: http://stackoverflow.com/a/52237811
accepted answer: http://stackoverflow.com/a/52237811
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: I want to generate a unique value, or uuid, (I do not care if it is a number or hex) for some script produced documents in a python3 script, but this should be unique between multiple executions of the script. etc. The script might run every two (2) or three (3) days. I do not want to get the same uuid twice. A simple yet practical way I thought of is using the epoch time (since the script won't run twice at the same second) and the machine it will be running will be 64bit (2038 problem), but it seems to simple to be foolproof. Another way to achieve this would be to use uuid4(). Will this be unique between executions and different machines?
has title: Unique identification value in python3
tagged with: python
has answer: http://stackoverflow.com/a/52238048
type: AnsweredQuestion
tagged with: uuid
upvote count: 3
type: Question
score: 3
tagged with: uniqueidentifier
possible better answer: http://stackoverflow.com/a/52238048
answer count: 2
linked to: http://stackoverflow.com/q/1155008

vectorization
tags question: http://stackoverflow.com/q/52209695
tags question: http://stackoverflow.com/q/52114107
tags question: http://stackoverflow.com/q/52212443
tag name: vectorization
type: Tag
tags question: http://stackoverflow.com/q/52267901
tags question: http://stackoverflow.com/q/52194407
tags question: http://stackoverflow.com/q/52258933
tags question: http://stackoverflow.com/q/52184885

http://stackoverflow.com/q/52224440
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/122024512
score: 1
has comment: http://stackoverflow.com/comment/91429692
downvote count: 0
favorite count: 0
has title: PyPDF2 not printing for pdf File Version 1.4 and below
tagged with: http://stackoverflow.com/tag/pdf
has comment: http://stackoverflow.com/comment/91435836
tagged with: python
answer count: 0
has body: I am not able to print the content of a pdf file with PDF version is 1.4 or less in Python 3.x. The code works fine for pdf files with PDF version 1.5 and above. The code is as follows: import PyPDF2 pdfReader = PyPDF2.PdfFileReader('C:/Users/ravi/Documents/pdf-sample.pdf') pageObj = pdfReader.getPage(0) print(pageObj.extractText())
tagged with: pypdf
type: UnansweredQuestion

http://stackoverflow.com/q/52199157
has answer: http://stackoverflow.com/a/52199534
type: Question
has title: AttributeError at /post/106/
has body: I want to create a "update post" function for my django post app. But I get an error. AttributeError at /post/106/ 'Post' object has no attribute 'slug' views.py def post_update(request, slug): if not request.user.is_authenticated(): return Http404() post = get_object_or_404(Post, slug=slug) form = PostForm(request.POST or None, request.FILES or None, instance=post) if form.is_valid(): form.save() messages.success(request, "updated") return HttpResponseRedirect(post.get_absolute_url()) context = { 'form': form } return render(request, "blog/post_edit.html", context) models.py class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = RichTextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def get_update_url(self): return reverse('post:update', kwargs={'slug': self.slug}) post_detail.html update urls.py ... url(r'^(?P<slug>[\w-]+)/update/$', post_update, name="update"), How can I my mistake? Thanks.
accepted answer: http://stackoverflow.com/a/52199534
answer count: 1
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91347801
favorite count: 0
upvote count: 1
tagged with: django
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91347298

http://stackoverflow.com/a/52209600
answers question: http://stackoverflow.com/q/52155766
score: 0
has body: In case someone experiences similar issue, it is most likely caused by incorrectly reckoned coordinates for drawing. After amending the code as follows, it draws everything correctly: from pyqtgraph.Qt import QtCore, QtGui import pyqtgraph.opengl as gl import numpy as np import pyqtgraph as pg class NestedDict(dict): def __getitem__(self, item): if item not in self: self[item] = NestedDict() return super().__getitem__(item) mainList = [['BM', 'Butterfly', 'E-shop', '1400'], ['BM', 'Butterfly', 'Fler', '2450'], ['BM', 'Butterfly', 'Holesovice', '2450'], ['Climbing presents', 'Ear-rings', 'Holesovice', '136'], ['Climbing presents', 'Other jewellery', 'E-shop', '160'], ['Climbing presents', 'Other jewellery', 'Other', '112'], ['PP', 'Skirts', 'Fler', '1380'], ['PP', 'Skirts', 'Holesovice', '1320'], ['PP', 'Skirts', 'Sashe', '450'], ['PP', 'Bags', 'E-shop', '2500'], ['PP', 'Skirts', 'E-shop', '5600'], ['PP', 'Dresses', 'Other', '6551'], ['Mar', 'Dresses', 'Holesovice', '1000'], ['Mar', 'Skirts', 'Holesovice', '3000'], ['Mar', 'Ear-rings', 'Holesovice', '2000']] app = QtGui.QApplication([]) w = gl.GLViewWidget() w.opts['distance'] = 50 w.showMaximized() w.setWindowTitle('pyqtgraph example: GLViewWidget') ax = gl.GLAxisItem() ax.setSize(10,10,10) w.addItem(ax) labels = dict(zip(list(set([x[0] for x in mainList])), [2*i for i,j in enumerate(list(set([x[0] for x in mainList])))])) shops = dict(zip(list(set([x[2] for x in mainList])), [2*i for i,j in enumerate(list(set([x[2] for x in mainList])))])) items = dict(zip(list(set([x[1] for x in mainList])), [2*i for i,j in enumerate(list(set([x[1] for x in mainList])))])) d = NestedDict() for tag, item, source, qty in mainList: d[tag][source][item] = qty for key, value in d.items(): for nkey, nvalue in value.items(): val = [] for index, nvalue_ in enumerate(nvalue.values()): if index == 0: val.append(0) else: val.append(float(list(nvalue.values())[index-1])/1000) size = np.empty((1,1,3)) size[...,0:2] = 1 size[...,2] = float(list…
type: Answer

http://stackoverflow.com/comment/91202835
has text: thanks for the comment, In that case we can directly use the variable "magician" instead using another variable (e.g. full-name) to make more compact code writing. The reason for popping was to clear the old list and fill the new list.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52125853
type: AnswerComment

http://stackoverflow.com/comment/91297234
type: QuestionComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/179412/discussion-between-andrew-and-ren-lyke).
comment on: http://stackoverflow.com/q/52171582
score: 0
type: Comment

http://stackoverflow.com/comment/91446749
type: QuestionComment
has text: I've edited my question to show how it differs from the links you sendt, but thank you for the suggestions.
comment on: http://stackoverflow.com/q/52248950
score: 0
type: Comment

http://stackoverflow.com/comment/91316932
score: 0
has text: `\ud83d\ude04` looks like UTF-16 **en**coding of the code point [`U+1F604`](https://www.charbase.com/1f604-unicode-smiling-face-with-open-mouth-and-smiling-eyes), you can not further "encode the encoding" (it doesn't make any sense whatsoever), you can only **de**code it into code points, and then again encode it using some different encoding. What exactly do you want? How is splitting the text into lines supposed to help?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52179465

http://stackoverflow.com/comment/91282045
score: 0
has text: @Muzol thank you for that
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52156828

http://stackoverflow.com/q/52149149
score: 1
has body: I am not sure how I should create this as a "multiple choice" quiz game. I don't know how to continue on. I am not sure how to use class in this instance. If I can get the first question working with answers, I'm sure I am continue on from there but I am in need of help. Here is my current code: from tkinter import * from tkinter import ttk #User Interface Code root = Tk() # Creates the window root.title("Quiz Game") def new_window(): newWindow = Toplevel() message = Label(newWindow, text="What is the capital of France?", font = ("Arial", "24"), pady=30) display = Label(newWindow, width=150, height=40) class letsQuiz: def __init__(self, questions, answers): self.questions = questions self.answers = answers self.label = Label(newWindow, text="What is the capital of France?") self.label.pack() self.answer1button = Button(newWindow, text="Madrid") self.answer2button = Button(newWindow, text="Paris") self.answer3button = button(newWindow, text="London") self.answer1button.pack() self.answer2button.pack() self.answer3button.pack() message.pack() display.pack() message_label1 = Label(text="Let's quiz some of your knowledge :)", font = ( "Arial", "25"), padx=40, pady=20) message_label2 = Label(root, text="Click 'Continue' to begin.", wraplength=250) button1 = Button(root, text ="Continue", command=new_window, width=16, bg="red") display2 = Label(root, width=100, height=30) message_label1.pack() message_label2.pack() button1.pack() display2.pack() root.mainloop() # Runs the main window loop
has comment: http://stackoverflow.com/comment/91251505
type: Question
has answer: http://stackoverflow.com/a/52151005
has comment: http://stackoverflow.com/comment/91248132
answer count: 1
has comment: http://stackoverflow.com/comment/91248288
has comment: http://stackoverflow.com/comment/91249600
accepted answer: http://stackoverflow.com/a/52151005
favorite count: 0
tagged with: tkinter
upvote count: 2
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/91251202
type: AnsweredQuestion
has title: How to enhance quiz game for multiple choice?

http://stackoverflow.com/q/52155170
type: Question
has comment: http://stackoverflow.com/comment/91262054
answer count: 2
has answer: http://stackoverflow.com/a/71334261
tagged with: avro
tagged with: apache-spark-sql
downvote count: 0
tagged with: pyspark
tagged with: apache-spark
has title: Loading avro files into pyspark dataframes from hdfs
has comment: http://stackoverflow.com/comment/91408341
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91408288
has answer: http://stackoverflow.com/a/69187411
has comment: http://stackoverflow.com/comment/91261544
has comment: http://stackoverflow.com/comment/91261717
has body: I've built a small data pipeline that moves some fictional test data from a local directory (json-format) to hdfs (avro format). This seemed to have worked correctly (no errors shown by flume), but it might be the case that the error lays already here. The next step was to transform an avro file into some pyspark dataframe using the databricks loader (only python library I could found for this). Now let me explain how I did this, so you can see where I might failed: 1 ) Creating avro files out of a json file by using flume My goal is to push json data from a local directory to HDFS, so I can analyse it with pySpark. For this I'm using flume. Since json has bad compression on HDFS, I'm also converting everyfile to avro by using the following flume.conf: agent.sources.tail.type = exec agent.sources.tail.shell = /bin/bash -c agent.sources.tail.command = cat /home/user/Data/json/* agent.sources.tail.batchsize = 10 agent.sources.tail.channels = MemChannel agent.channels.MemChannel.type = memory agent.channels.MemChannel.capacity = 100 agent.channels.MemChannel.transactionCapacity = 100 agent.sinks.HDFS.channel = MemChannel agent.sinks.HDFS.type = hdfs agent.sinks.HDFS.hdfs.fileType = DataStream agent.sinks.HDFS.hdfs.fileSuffix=.avro agent.sinks.HDFS.hdfs.path = hdfs://localhost:9000/home/user/Data/hdfs/test_data agent.sinks.HDFS.hdfs.batchSize = 100 agent.sinks.HDFS.hdfs.rollSize = 0 agent.sinks.HDFS.hdfs.rollCount = 100 agent.sinks.HDFS.serializer=avro_event agent.sinks.HDFS.serializer.compressionCodec=snappy This did run without any error, so I assume flume moved every file as an correct avro file to HDFS. 2) Creating a dataframe by loading an avro file Now comes the part where I'm trying to read a single avro file as a dataframe within pyspark: from pyspark.sql.types import * from pyspark.sql import SQLContext from pyspark import SparkContext sc = SparkContext() sqlContext = SQLContext(sc) sqlContext.setConf("spark.sql.avro.compression.codec","snappy") # creates a dat…
score: 1
has comment: http://stackoverflow.com/comment/91261669
upvote count: 1

http://stackoverflow.com/comment/91337404
comment on: http://stackoverflow.com/q/52193776
has text: You mean the host your script is running on, or proxy6.net? And do you expect a port other than 443?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91225094
has text: @SachinKukreja that did it thank you! even though I am redirecting before I call it should still send them email though?
comment on: http://stackoverflow.com/q/52137709
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/52243840
has body: IntegrityError, NOT NULL constraint failed: papers_paper.seminary_id. This error means that you have Foreign Key to Seminary in Paper model with not null constraint but while creating a Paper object you are not passing the value of the Seminary(Foreign Key).
has comment: http://stackoverflow.com/comment/91437126
has comment: http://stackoverflow.com/comment/91437071
answers question: http://stackoverflow.com/q/52243738
has comment: http://stackoverflow.com/comment/91436431
score: 0
type: Answer

http://stackoverflow.com/comment/91222659
comment on: http://stackoverflow.com/q/52136423
score: 1
has text: Irrelevant to your issue, but you are mixing a regression loss (MSE) with a classification metric (accuracy), which should not be the case.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91434291
score: 0
type: Comment
type: QuestionComment
has text: It is not entirely clear what constraints you have. But if you can sort data set 1 and data set 2 on `col1` and `col2` (in Julia you could do this e.g. using JuliaDB if data is too big to fit in RAM) then write a loop iterating over both sets to produce consecutive groups. There is no need to load whole data sets into RAM nor store the result in RAM to achieve this.
comment on: http://stackoverflow.com/q/52241423

http://stackoverflow.com/a/58635575
type: Answer
has body: You can store it as lambda function: TEXT_AMOUNT = lambda amount: f'text {amount}' print(TEXT_AMOUNT(10)) out: 'text 10'
answers question: http://stackoverflow.com/q/52248776
score: 22
upvote count: 22
downvote count: 0

http://stackoverflow.com/q/52213884
favorite count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
answer count: 0
score: 1
type: Question
has body: I have a ModelFormSet with ~5 forms; each copy of form has a ModelChoiceField with all fields of one model Distance, ~1000 items. I want to make just one evaluation of the queryset Distance.objects.all(), not 5 such queries, and use its result in each form. How can I do it? I tried to provide the argument form_kwargs={'distances': models.Distance.objects.all()} to a ModelFormSet; but it appears that this queryset is still evaluated for each form copy. Can I ask Django to do it just once? Here is my form code: class RaceForm(forms.ModelForm): distance = forms.ModelChoiceField( queryset=models.Distance.objects.none(), required=True) distance_real = forms.ModelChoiceField( queryset=models.Distance.objects.none(), required=False) def __init__(self, *args, **kwargs): distances = kwargs.pop('distances') super(RaceForm, self).__init__(*args, **kwargs) self.fields['distance'].queryset = distances self.fields['distance_real'].queryset = distances And here is how I create a formset: def getRaceFormSet(user, event, data=None): RaceFormSet = modelformset_factory(models.Race, form=forms.RaceForm, can_delete=True, extra=N_EXTRA_RACES) return RaceFormSet( data=data, queryset=event.race_set.select_related('distance').order_by( 'distance__distance_type', '-distance__length', 'precise_name'), initial=[{'event': event, 'created_by': user}] * N_EXTRA_RACES, form_kwargs={'distances': models.Distance.objects.all().order_by('-popularity_value', 'distance_type', 'length')}, )
has comment: http://stackoverflow.com/comment/91473740
has title: Django, ModelFormField: using evaluated queryset several times
has comment: http://stackoverflow.com/comment/91377327
downvote count: 0

http://stackoverflow.com/comment/91200752
comment on: http://stackoverflow.com/a/52120654
has text: Thank you. I like the stack based approach idea.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/52116140
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52116002
answers question: http://stackoverflow.com/q/52116002
score: 1
has body: Currently you are trying to access the member "id" from a list with the string "parent" in the following line: my_dict["PARENT_ID"] = result.get(["parent"]["id"]) You have to check if the result dict contains the key "parent". The get method of your result dict can be used for this. It returns None if the dict does not contain the key "parent". Otherwise use the get method and try to get the id of the parent Your code has to be my_dict["PARENT_ID"] = result["parent"].get("id") if result.get("parent") else None
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/52129993
accepted answer: http://stackoverflow.com/a/52130263
tagged with: pandas
has title: Pandas stack date matirx value
downvote count: 0
answer count: 1
score: 1
favorite count: 0
tagged with: python-3.x
has body: My data format is like: year month 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 .. 31 1998 1 2.5 1 - - -2.5 - - - - - - - - - - - - - - 1.5 1998 2 2.5 1 - - -4.5 - - - - - - - - - - - - - - 1.5 1998 3 2.5 1 - - -3.5 - - - - - - - - - - - - - - 1.5 1998 4 2.5 1 - - -8.5 - - - - - - - - - - - - - - 1.5 1998 5 2.5 1 - - -1.5 - - - - - - - - - - - - - - 1.5 2001 5 2.5 1 - - -1.5 - - - - - - - - - - - - - - 1.5 explanation: -means the missing value. year column is the year. month column is the month. 1 2 3 4 and so on is the day column,so this is the datetime format matrix . Expect ouput: date value 1998-01-01 2.5 1998-01-02 2.8 1998-01-03 - # when is ismissing and the date is exist it show 1998-01-31 - ... 2008-02-28 - # 2008-02-29 - # this year the Febulary get 29 days 2008-03-01 3.4 ... 2008-04-30 - # missing value and the date exist. 2008-05-01 3.0
tagged with: datetime
tagged with: python
type: AnsweredQuestion
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52130263

http://stackoverflow.com/a/52125343
score: 1
downvote count: 0
has body: I do believe you were a good way there with your first attempt: var arr = userInputBox.Text.Split(‘,’); textbox.Text = new string(Array.ConvertAll(arr, s =&gt; (char)(int.Parse(s))); Where you used convertall to change an array of string to an array of int, I added a cast to char to make it output an array of chars instead (I explain why, below) and this can be converted to a string by passing it into a new string’s constructor This has resulted in a much more compact (and I could have make it a one liner to be honest) form but compactness isn’t always desirable from a learning perspective Hence, this is fixing your code if it’s easier to understand: decodeText = userInputBox.Text; var arr = decodeText.Split(‘,’); int[] myInts = Array.ConvertAll(arr, int.Parse); for(int i = 0; i &lt; myInts.Length; i++) { decodeBox.Text += (char)myInts[i]; } The crucial bit you were missing (apart from using string split to split the string into an array of numerical strings) was converting the int to a char In c# there is a direct mapping from int to char- letter A is 65, for example and if you take the int 65 and cast it to a char, with (char) it becomes A Then we just append this If the list of ints will be long, consider using a stringbuilder to build your string
answers question: http://stackoverflow.com/q/52125260
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/91201801

http://stackoverflow.com/q/52255875
score: 6
favorite count: 0
has answer: http://stackoverflow.com/a/52291523
type: Question
has title: Python 3.6 Generic Type Hints
tagged with: generics
upvote count: 6
tagged with: python-typing
has comment: http://stackoverflow.com/comment/91461707
has comment: http://stackoverflow.com/comment/91461537
has comment: http://stackoverflow.com/comment/91461120
tagged with: python
has body: I am trying to wrap my head around generic type hints. Reading over this section in PEP 483, I got the impression that in SENSOR_TYPE = TypeVar("SENSOR_TYPE") EXP_A = Tuple[SENSOR_TYPE, float] class EXP_B(Tuple[SENSOR_TYPE, float]): ... EXP_A and EXP_B should identify the same type. In PyCharm #PC-181.4203.547, however, only EXP_Bworks as expected. Upon investigation, I noticed that EXP_B features a __dict__ member while EXP_A doesn't. That got me to wonder, are both kinds of type definition actually meant to be synonymous? Edit: My initial goal was to design a generic class EXP of 2-tuples where the second element is always a float and the first element type is variable. I want to use instances of this generic class as follows from typing import TypeVar, Tuple, Generic T = TypeVar("T") class EXP_A(Tuple[T, float]): ... EXP_B = Tuple[T, float] V = TypeVar("V") class MyClass(Generic[V]): def get_value_a(self, t: EXP_A[V]) -> V: return t[0] def get_value_b(self, t: EXP_B[V]) -> V: return t[0] class StrClass(MyClass[str]): pass instance = "a", .5 sc = StrClass() a: str = sc.get_value_a(instance) b: str = sc.get_value_b(instance) (The section on user defined generic types in PEP 484 describes this definition of EXP as equivalent to EXP_B in my original code example.) The problem is that PyCharm complains about the type of instance as a parameter: Expected type EXP (matched generic type EXP[V]), got Tuple[str, float] instead`. With EXP = Tuple[T, float] instead, it says: Expected type 'Tuple[Any]' (matched generic type Tuple[V]), got Tuple[str, float] instead.
answer count: 1
has comment: http://stackoverflow.com/comment/91463299
has comment: http://stackoverflow.com/comment/91467898
has comment: http://stackoverflow.com/comment/91461010
has comment: http://stackoverflow.com/comment/91458977
downvote count: 0
type: UnansweredQuestion

import
type: Tag
tags question: http://stackoverflow.com/q/52120546
tags question: http://stackoverflow.com/q/52141592
tags question: http://stackoverflow.com/q/52164047
tag name: import
tags question: http://stackoverflow.com/q/52127011
tags question: http://stackoverflow.com/q/52146524
tags question: http://stackoverflow.com/q/52246659
tags question: http://stackoverflow.com/q/52239111
tags question: http://stackoverflow.com/q/52150763
tags question: http://stackoverflow.com/q/52238125
tags question: http://stackoverflow.com/q/52145516
tags question: http://stackoverflow.com/q/52175067
tags question: http://stackoverflow.com/q/52157207

http://stackoverflow.com/a/52257924
has body: You are right. It is just a convenience. Take the case of TensorFlow models defined here. If you take a specific look at InceptionV4.py, you will see that it has a scope argument in its definition. Just below you will see that InceptionV4 has been passed as a default scope. Therefore it was entirely not required to even has a scope argument in the definition. But it makes sense, if somebody gives scope=None. Think about it. Model definitions can get very comples very quickly. Therefore, a default_scope argument, helps in reinforcing the wisdom of the model definition writer to introduce some sort of deliberate structure in the model definition, even if the end user is very naive about it.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52256503

http://stackoverflow.com/q/52115698
score: 1
tagged with: group-by
type: Question
accepted answer: http://stackoverflow.com/a/52115763
tagged with: pandas
upvote count: 1
has body: My pandas data frame looks the following: title genre rating Shutter Island [Horror, Action] 8 Spectre [Action, Thriller] 7 I would like to group by genre and find the mean rating. The problem is that the genre column contains lists (of variable length). I just want to add a movie to a group if the genre appears in the list of genres. I know so far that as lists are mutable I can do something like movies['genre']=movies['genre'].apply(tuple) movies.groupby(['genre']).mean() But of course that is not what I want, because I way too many groups. As this may help, the set of all possible genres is {'Action', 'Adventure', 'Animation', 'Comedy', 'Crime', 'Documentary', 'Drama', 'Family', 'Fantasy', 'Foreign', 'History', 'Horror', 'Music', 'Mystery', 'Romance', 'Science Fiction', 'TV Movie', 'Thriller', 'War', 'Western'}
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52115763
tagged with: python
has title: groupby columns containing lists
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/52151054
accepted answer: http://stackoverflow.com/a/52151112
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: dataframe
type: Question
linked to: http://stackoverflow.com/q/51443725
downvote count: 0
has body: I have a df containing rows (sometimes thousands) of data, corresponding to a digital signal. I have added an extra column using: df['On/Off'] = np.where(df[col] &gt; value, 'On', 'Off') to label the signal as being on or off (value is set depending on the signal source). The following code gives an example dataframe albeit without actual measurement data: df = pd.DataFrame({"Time/s" : np.arange(0,100,2), "On/Off" : ("Off")}) df.at[10:13,"On/Off"] = "On" df.at[40:43,"On/Off"] = "On" df.at[47:,"On/Off"] = "On" I want to count how many times the signal registers as being on. For the above code, the result would be 2 (ideally with an index returned). Given how the dataframe is organised, I think going down the rows and looking for pairs of rows where column on/off reads as 'off' at row n, then 'on' at row_n+1 should be the approach, as in: i =0 # &lt;--- number of on/off pairings if cycle = [row_n]='On'; [row_n+1]='Off': i=+1 My current plan came from an answer for this (Pandas iterate over DataFrame row pairs) I think df.shift() offers a potential route, generating 2 dataframes, and then comparing rows for mismatches, but it feels there could be a simpler way, possibly using itertools, or pd.iterrows (etc.). As usual, any help is greatly appreciated.
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/52151112
favorite count: 0
has title: Looking for on/off signals or value-pairs across adjacent rows in pandas dataframe

http://stackoverflow.com/comment/91628470
comment on: http://stackoverflow.com/q/52245414
type: Comment
type: QuestionComment
score: 0
has text: i think that the definition of "newer" is quite clear from the context. If you normally need to write a page of very precise definitions and contextual information to explain a few phrases for example - that is very ineffective way of communication.

http://stackoverflow.com/comment/91401592
comment on: http://stackoverflow.com/q/52225981
score: 0
type: Comment
type: QuestionComment
has text: hmm, could you upload maybe a hand drawn chart that you want to build using matplotlib

http://stackoverflow.com/q/52112788
linked to: http://stackoverflow.com/q/29324025
tagged with: python
has comment: http://stackoverflow.com/comment/91178123
has comment: http://stackoverflow.com/comment/91176414
answer count: 0
has comment: http://stackoverflow.com/comment/91176459
tagged with: loops
has comment: http://stackoverflow.com/comment/91207232
has comment: http://stackoverflow.com/comment/91177433
type: Question
has comment: http://stackoverflow.com/comment/91177165
has comment: http://stackoverflow.com/comment/91177352
tagged with: for-loop
tagged with: nested-loops
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91176856
score: 0
has body: I am trying to kreate a nested loop to calculate the price combinations between the Car ModelName, e.g.: fact_date CarID Country Type ManufactureNameSum Sum_Costs 2017-07-14 1 USA Car Ford_Focus____VW_Jetta 34003 which means I have a combination of the ManufactorName and ModelName and the sum of the AcquisitionPrice. Somehow I receive the results twice due to the nested loop but just want to have it once. I was thinking solving it with the following line: row['ManufactureName'] != row2['ManufactureName'] but this only solves the problem with the same ManufactureName but not the one having due to two lists twice the result. Hope somehone could help here. Adjustment I adjusted the code for the nested loop, but still have the propblem concerning the fact_date indexing as I had before. Adjusted Code: import pandas as pd df = pd.read_csv('C:/Sales_Cars.csv', encoding='cp1252', sep=';', index_col=0).dropna() df2 = pd.DataFrame([]) for current_date in df.index.unique(): for i in range(0, len(df)): for j in range(i+1, len(df)): if ( df.iloc[i]['ManufactureName'] != df.iloc[j]['ManufactureName'] and df.iloc[i]['CarID'] == df.iloc[j]['CarID'] and df.iloc[i]['Country'] == df.iloc[j]['Country']): df2 = df2.append( pd.DataFrame({ 'CarID': df.iloc[i]['CarID'], 'Country': df.iloc[i]['Country'], 'Type': df.iloc[i]['Type'], 'ManufactureNameSum': ( df.iloc[i]['ManufactureName'] + '_' + df.iloc[i]['ModelName'] + '____' + df.iloc[j]['ManufactureName'] + '_'+df.iloc[j]['ModelName'] ), 'Sum_Costs': ( df.iloc[i]['AcquisitionPrice'] + df.iloc[j]['AcquisitionPrice'] ) }, index=[0]), ignore_index=True) print(df2) The data looks like the following: fact_date CarID ManufactureName ModelName Type Country AcquisitionPrice 2017-07-14 1 Ford Focus Car USA 11640 2017-07-14 2 Ford Mustang Car USA 12994 2017-07-14 3 Ford Fiesta Car USA 12842 2017-07-14 4 Ford Mondeo Car USA 14685 2017-07-14 1 VW Jetta Car USA 22363 2017-07-14 2 VW Polo Car USA 20107 2017-07-14 3 VW Golf Car USA 21256 2017-07-14 4 VW …
has comment: http://stackoverflow.com/comment/91180110
has comment: http://stackoverflow.com/comment/91176787
has title: Nested Loop counts several times the same values
has comment: http://stackoverflow.com/comment/91180404
has comment: http://stackoverflow.com/comment/91180173
type: UnansweredQuestion

http://stackoverflow.com/q/52259686
favorite count: 0
tagged with: python
tagged with: regex
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52261116
accepted answer: http://stackoverflow.com/a/52261116
has title: Regex matching multiple prefixes, unpack to columns
has body: Any suggestions for a regex to take this series import pandas as pd import numpy as np data = [ 'Apple: very tasty', 'Banana: Unpleasant', 'Apple: quite nice Banana: not bad either', '', ] ser = pd.Series(data=data) into this resulting DataFrame? pd.DataFrame(data=[ ['very tasty', np.nan], [np.nan, 'Unpleasant'], ['quite nice', 'not bad either'], [np.nan, np.nan], ], columns = ['Apple', 'Banana']) If Apple and Banana exist, they are always in the order Apple, Banana, and separated by a double space.
downvote count: 1
type: Question
score: 0
tagged with: pandas
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/91248490
type: QuestionComment
comment on: http://stackoverflow.com/q/52147403
score: 0
has text: My C code generates the table up to 10k in 0.043s using brute force. It doesn't do anything clever. (Note, there's a confusion between limits -- whether its all the elements of the sequence up to N, or whether it's the first N terms of the sequence).
type: Comment

wsgi
type: Tag
tags question: http://stackoverflow.com/q/52247901
tag name: wsgi

http://stackoverflow.com/q/52169101
possible better answer: http://stackoverflow.com/a/52169125
answer count: 3
has title: New list created by slicing old list; modifying 'new' changes 'old' as well?
tagged with: python
tagged with: python-3.x
tagged with: list
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52169587
has answer: http://stackoverflow.com/a/52169353
accepted answer: http://stackoverflow.com/a/52169587
type: Question
score: 0
has answer: http://stackoverflow.com/a/52169125
has body: Summary: I created a new list variable by taking a slice of an original one. When I tweak the new list, the previous one also changes, but I'm fairly certain they are two distinct lists! Here's my general method: 1.Create initial list all_info by calling a function. Each list item is itself a list with 5 elements. all_info = CrossReference(start_info, RBS_info, promoter_info) 2.Create a new list all_info_mod by slicing the initial list to remove the first item (I need to do this for later code). Then confirm thet are distinct. all_info_mod = all_info[1:] all_info #Shows original list all_info_mod #Shows sliced list 3.Increment the first 3 elements of each outer list by 1. Then check. for i in all_info_mod: for j in range(0, 3): i[j] += 1 all_info_mod #Successfully altered all_info #Also altered?! The initial list is also altered when it shouldn't be. I have tested with simpler examples and get the same result. Perhaps it's a result of my previous code that comes before this? (Can provide more details if needed). Thanks in advance!

http://stackoverflow.com/q/52192830
upvote count: 2
accepted answer: http://stackoverflow.com/a/52193011
tagged with: python
type: AnsweredQuestion
has body: I have a tuple full of bytes and i need to convert these bytes into one single utf-8 string, how can i do that? data = tuple([0, 4, 4, 6, 1, 53]) print(data as utf-8 string?)
type: Question
has comment: http://stackoverflow.com/comment/91335460
score: -2
has answer: http://stackoverflow.com/a/52193011
has title: Converting bytes inside a tuple to string
downvote count: 4
answer count: 1
has comment: http://stackoverflow.com/comment/91335567
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/52249889
favorite count: 0
tagged with: python-3.x
answer count: 5
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52249993
tagged with: dictionary
score: 2
has body: I am trying to find a match from my list to a list in a dictionary value For example, the dictionary contains dict = {"test1": [1, 2, 3, 4], "test2": [2, 2, 3, 4], "test3": [1, 2, 4, 5], "test4": [6, 2, 3, 4], "test5": [7, 2, 3, 4]} and the data I need to find matches for if answer = [6,2,3,4] I am trying to pull any test where the first value of the answer input must be different and the rest the same so for example [(this is different), 2,3,4] then at the end I want test1, test2, and test5 to be recorded.
upvote count: 3
has answer: http://stackoverflow.com/a/52250017
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52250019
has comment: http://stackoverflow.com/comment/91448000
has title: Find similar list value inside dictionary
has answer: http://stackoverflow.com/a/52250070
has answer: http://stackoverflow.com/a/52249981
has comment: http://stackoverflow.com/comment/91448079

http://stackoverflow.com/a/52147068
downvote count: 0
has body: If I understand correctly, you want an array of shape (n,3) i.e. a length n array of length 3 coordinates. You can do this with a list-comprehension and the np.array constructor: import numpy as np l = [[(-80983.957, 175470.593, 393.486), (-80994.122, 175469.889, 394.391), (-80996.591, 175469.757, 394.595), (-81006.72, 175469.298, 395.527), (-81019.538, 175468.399, 396.847), (-81025.594, 175467.643, 397.395), (-81030.366, 175467.25, 397.858), (-81030.455, 175467.776, 397.886), (-81033.209, 175470.89, 398.192)], [(-81037.166, 175471.423, 398.729), (-81037.911, 175471.237, 398.764), (-81038.01, 175472.285, 398.533)], [(-81030.537, 175472.562, 397.951), (-81029.792, 175472.896, 397.842), (-81029.668, 175472.131, 397.895)], [(-80847.281, 175417.644, 378.2), (-80853.651, 175417.621, 378.781)]] a = np.array([list(t) for ll in l for t in ll]) which gives a as: array([[ -80983.957, 175470.593, 393.486], [ -80994.122, 175469.889, 394.391], [ -80996.591, 175469.757, 394.595], [ -81006.72 , 175469.298, 395.527], [ -81019.538, 175468.399, 396.847], [ -81025.594, 175467.643, 397.395], [ -81030.366, 175467.25 , 397.858], [ -81030.455, 175467.776, 397.886], [ -81033.209, 175470.89 , 398.192], [ -81037.166, 175471.423, 398.729], [ -81037.911, 175471.237, 398.764], [ -81038.01 , 175472.285, 398.533], [ -81030.537, 175472.562, 397.951], [ -81029.792, 175472.896, 397.842], [ -81029.668, 175472.131, 397.895], [ -80847.281, 175417.644, 378.2 ], [ -80853.651, 175417.621, 378.781]])
has comment: http://stackoverflow.com/comment/91247640
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52146977
has comment: http://stackoverflow.com/comment/91250020
answers question: http://stackoverflow.com/q/52146977
type: Answer
has comment: http://stackoverflow.com/comment/91245657
score: 2
has comment: http://stackoverflow.com/comment/91245819

http://stackoverflow.com/q/52138920
tagged with: tensorflow
upvote count: 9
has answer: http://stackoverflow.com/a/57479262
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91231097
tagged with: deep-learning
has answer: http://stackoverflow.com/a/79392530
downvote count: 0
favorite count: 0
has body: I was lookking for GAN code in Github. The code I found uses pytorch. In this code, we first normalized the image to mean = 0.5, std = 0.5. Normally, normalize to min = 0 and max = 1. Or normal distribution with mean = 0 and std = 1. Why is this normalized to mean = 0.5 and std = 0.5? transformtransfo = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)) ])
score: 9
type: Question
tagged with: python
tagged with: computer-vision
has answer: http://stackoverflow.com/a/52140714
tagged with: pytorch
answer count: 3
has title: Why do we normalize the image to mean=0.5, std=0.5?

http://stackoverflow.com/comment/112268989
type: AnswerComment
score: 0
has text: This gives me the following error: 'ZipExtFile' object has no attribute '_orig_file_size'
type: Comment
comment on: http://stackoverflow.com/a/62119938

http://stackoverflow.com/q/52181421
tagged with: python
tagged with: repository
downvote count: 0
answer count: 0
type: UnansweredQuestion
tagged with: tensorflow
type: Question
score: 1
tagged with: ubuntu
tagged with: bazel
duplicate of: http://stackoverflow.com/q/51657913
has body: when i go for building the tensorflow in terminal via command /tensorflow$ bazel build -c opt //tensorflow/tools/pip_package:build_pip_package error occurs as follows /tensorflow.bzl:449:21: name 'set' is not defined ERROR: error loading package '': Extension 'tensorflow/tensorflow.bzl' has errors ERROR: error loading package '': Extension 'tensorflow/tensorflow.bzl' has error
upvote count: 1
linked to: http://stackoverflow.com/q/51657913
favorite count: 0
has title: encountered error while building tensorflow in terminal

http://stackoverflow.com/comment/91396130
has text: @user1283776 you can use [Date.UTC()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC) in javascript to get UTC time, and in python [utcfromtimestamp()](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcfromtimestamp)
score: 1
comment on: http://stackoverflow.com/a/52222514
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91241131
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52145106
has text: @littlely Try what I add.

http://stackoverflow.com/comment/91231380
score: 1
comment on: http://stackoverflow.com/a/52140735
type: AnswerComment
type: Comment
has text: @albertjan: and what would you imagine [the `dict.fromkeys()` implementation](https://github.com/python/cpython/blob/71f2dadf66c8f9f513bb67f3b06d320c406ac2ff/Objects/dictobject.c#L1415-L1509) would do when bound to a list instead? How would the C code I linked to even *work* in that case? It happens to already account for subclasses (that's what the `PyDict_CheckExact` calls are for), but making all C method implementations more flexible in the face of arbitrary types is a lot of work that is just not worth it for the very rare possible cases where you'd want to put the method on another class

http://stackoverflow.com/comment/91317878
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52184053
has text: Are your test, validation, and train sets all from the same distribution?

http://stackoverflow.com/a/52206393
type: Answer
downvote count: 0
has body: For this example I'll just use a list with straight numbers and no nested list: values = [3, 2, 4] result = dict.from_keys(values) for key, value in result.items(): value = {} for num in values: if num != key: value[num] = 1 This creates a dict with each number as a key. Now in each key, make the value a nested dict who's contents are num: 1 for each number in the original values list if it isn't the name of the key that we're in
score: 1
answers question: http://stackoverflow.com/q/52206196
upvote count: 1

http://stackoverflow.com/comment/91433100
score: 0
type: Comment
has text: Okay, now in the list, it contains the strings that are split, not the regular values
type: AnswerComment
comment on: http://stackoverflow.com/a/52242380

http://stackoverflow.com/a/52259820
has comment: http://stackoverflow.com/comment/91467659
has body: When you call df.plot, you can specify which axes you want to plot onto. ax1 = plt.subplot(121) df.drop("D", axis=1).plot(kind='bar', ax=ax1) ax2 = plt.subplot(122) df['D'].plot(kind='bar', ax=ax2) plt.show() Shows both plots:
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91467965
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52259693
answers question: http://stackoverflow.com/q/52259693

http://stackoverflow.com/a/52199029
upvote count: 0
answers question: http://stackoverflow.com/q/52198570
has comment: http://stackoverflow.com/comment/91348929
has comment: http://stackoverflow.com/comment/91349453
score: -1
downvote count: 1
type: Answer
has body: str(data) is not the right way of converting your dataframe to string representation. str(data) dumps newline(\n) and carriage return(\r) characters into the mail body which messes up the email rendering. Use body = data.to_html() to get your dataframe in html rows format. Send this body as the email content. Ref: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html#pandas-dataframe-to-html You will also have to do an additional change to send html instead of plain text as email body. from email.mime.text import MIMEText msg = MIMEText(data.to_html(), 'html') msg['From'] = 'from email id' msg['To'] = 'to email id' msg['Subject'] = subject .... .... server.sendmail(sent_from, to, msg.as_string())

cryptography
tag name: cryptography
type: Tag
tags question: http://stackoverflow.com/q/52236189

http://stackoverflow.com/comment/91482985
type: QuestionComment
comment on: http://stackoverflow.com/q/52267547
has text: so the only way is to have this kind of URL: /prefix/greeter/? but that seems odd to force a prefix, because most other RESTful URLs do not require a prefix: https://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api#restful maybe I should give up on separating into 2 separate files then. thanks again for your help
score: 0
type: Comment

http://stackoverflow.com/comment/91452550
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52249331
has text: `e = {}; for k, v in xs: e[k] = e.get(k,0)+v` should work. I also tend to think this will have least complexity as compared to the one with groupby, map, sum and for loop all at once
score: 0

http://stackoverflow.com/comment/91300992
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52170059
has text: thank you for answering my question, sorry i forget to tell this, i have used delim_whitespace=True, but that's not running and the message is : pandas.errors.ParserError: Error tokenizing data. C error: Expected 3 fields in line 6, saw 4

http://stackoverflow.com/q/52249150
has answer: http://stackoverflow.com/a/52249191
score: -1
answer count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/52249197
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91446546
has body: for day_num in range(1,8): sales=float(input("Enter the sales for Day {}".format(day_num))) bakery_temp_info.append(sales) bakery_sale.append(list(bakery_temp_info)) del bakery_temp_info[:] This is a section of an exemplar code that my teacher gave me. Can anyone explain how the variable "day_num" is used for this loop when it has not been previously defined. I have tried printing it out in the loop and it increases by 1 every time the loop runs. Any help appreciated, thanks.
has comment: http://stackoverflow.com/comment/91446492
has title: Why is day_num not defined?
tagged with: python
has comment: http://stackoverflow.com/comment/91446589
downvote count: 2
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91446548

http://stackoverflow.com/q/52196376
tagged with: terminal
has comment: http://stackoverflow.com/comment/91344373
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91345054
type: Question
has body: I am using logger.debug and a statement inside and I am seeing that DEBUG statement in my output /command line terminal. I thought logger.debug is not supposed to show up unless in verbose mode.. why is this?
has comment: http://stackoverflow.com/comment/91353136
has title: Why am I seeing DEBUG level logs in my output?
score: 0
has comment: http://stackoverflow.com/comment/91344358
tagged with: command-line

http://stackoverflow.com/q/52218891
has comment: http://stackoverflow.com/comment/91388544
has answer: http://stackoverflow.com/a/52222453
has comment: http://stackoverflow.com/comment/91387088
accepted answer: http://stackoverflow.com/a/52222453
favorite count: 0
possible better answer: http://stackoverflow.com/a/52219003
has body: im currently trying to convert a csv file to a xlsx file. I did find a lot of help on here how to do this but I have one major problem. my csv file has some data stored in different columns. If I convert that file to xlsx in python, all data gets put into one column with a ";" between them. But how can I keep the columns in the xlsx file? If I open the csv file and save it as xlsx it works too and everything stays the same. EDIT: import os import glob import csv from xlsxwriter.workbook import Workbook for csv_f in glob.glob(os.path.join('.', '*.csv')): workbook = Workbook(csv_f[:-4] + '.xlsx') worksheet = workbook.add_worksheet() with open(csv_f, 'rt', encoding='utf8') as f: reader = csv.reader(f) for r, row in enumerate(reader): for c, col in enumerate(row): worksheet.write(r, c, col) workbook.close()
has comment: http://stackoverflow.com/comment/91388670
tagged with: python
tagged with: excel
type: AnsweredQuestion
score: 2
type: Question
has answer: http://stackoverflow.com/a/52219003
has comment: http://stackoverflow.com/comment/91387614
has comment: http://stackoverflow.com/comment/91386588
downvote count: 0
has comment: http://stackoverflow.com/comment/91386867
has comment: http://stackoverflow.com/comment/91388641
has title: Convert csv to xlsx splitting at “;” to different columns
upvote count: 2
has comment: http://stackoverflow.com/comment/91388584
has comment: http://stackoverflow.com/comment/91388490
answer count: 2
has comment: http://stackoverflow.com/comment/91387503
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/91386667

http://stackoverflow.com/q/52152685
has comment: http://stackoverflow.com/comment/91256269
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52153035
tagged with: python
has comment: http://stackoverflow.com/comment/91256357
has answer: http://stackoverflow.com/a/52153122
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52153122
has body: Hi guys i don't know why the only block runs is my first function. i am trying to pass my coin_counter last value to the 2nd function but my first function is not passing the value after it's release. and also it doesn't print to the console import RPi.GPIO as GPIO import time import threading GPIO.setmode(GPIO.BCM) GPIO.setup(27,GPIO.IN, pull_up_down=GPIO.PUD_DOWN) lock = threading.Lock() counter = 1 pulse = 0 def coin_counter(): global counter lock.acquire() try: while True: time.sleep(.1) GPIO.wait_for_edge(27, GPIO.RISING) #print("Pulse comming ! (%s)") %counter counter += 1 return counter finally: lock.release() print(coin_counter()) def get_pulse_count(): while True: print('Hello World!') try: coincounter = threading.Thread(target=coin_counter) getpulse = threading.Thread(target=get_pulse_count) coincounter.start() getpulse.start() except KeyboardInterrupt: coincounter.stop() getpulse.stop() GPIO.cleanup()
type: Question
tagged with: raspberry-pi
accepted answer: http://stackoverflow.com/a/52153035
has title: Only first thread is running using python threading
score: 0
answer count: 2
tagged with: raspberry-pi3

http://stackoverflow.com/a/52235534
has body: You could do something like this: The condition is set to False, and is changed to True in main. After 5 seconds, the change_if_condition method is called, condition is checked, and if found True, the label textvariable is changed, and automatically updates the label. from tkinter import * def change_if_condition(): if condition: text1.set("IN Button Pressed.Loading Camera.") def main(): global condition condition= True window.after(5000, change_if_condition) window = Tk() text1 = StringVar() text1.set("Waiting for Button Press...") lbl = Label(window, textvariable=text1) # use textvariable, so the displayed text is changed when the variable changes lbl.pack() condition = False main() window.mainloop()
type: Answer
answers question: http://stackoverflow.com/q/52235287
score: 0

utm
tags question: http://stackoverflow.com/q/52221458
type: Tag
tag name: utm

http://stackoverflow.com/comment/91213152
has text: why do you torch.cat along first dimension (batch) rather than dim=1 channel dimension?
score: 0
comment on: http://stackoverflow.com/q/52130170
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52211929
has comment: http://stackoverflow.com/comment/91373258
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91373227
answer count: 2
score: 5
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52234706
has title: Diagonalization of ill-conditioned matrix and imposibility to compute eigenvectors. Different results with numpy/scipy
linked to: http://stackoverflow.com/q/52106978
has comment: http://stackoverflow.com/comment/91381418
tagged with: python
accepted answer: http://stackoverflow.com/a/52234706
has answer: http://stackoverflow.com/a/52219120
has body: Im am dealing with a sparse Matrix with very small elements. Consider a vector: vec=[-1.e-76 -1.e-72 -1.e-68 -1.e-64 -1.e-60 -1.e-56 -1.e-52 -1.e-48 -1.e-44 -1.e-40 -1.e-36 -1.e-32 -1.e-28 -1.e-24 -1.e-20 -1.e-16 -1.e-12 -1.e-08 -1.e-04 -1.e-02 -1.e-04 -1.e-08 -1.e-12 -1.e-16 -1.e-20 -1.e-24 -1.e-28 -1.e-32 -1.e-36 -1.e-40 -1.e-44 -1.e-48 -1.e-52 -1.e-56 -1.e-60 -1.e-64 -1.e-68 -1.e-72 -1.e-76] For those interested, those numbers represent the hopping amplitudes of a 1D system. They are not zero. The hamiltonian is given by a sparse matrix: H=sps.diags([vec,vec],[-1,1],dtype='f8') I am interested on the eigenvalues, but even more on the eigenvectors . As far as I know, there are two ways of deal with the diagonalization: scipy.linalg and numpy.linalg and the former is better. denseHam=H.toarray() The correct eigenvalue spectrum is given by all of these functions: import numpy as np import scipy.linalg as la s1= la.eigvalsh(denseHam) s2= np.linalg.eigvalsh(denseHam) s3= np.linalg.eigvals(denseHam) #I did not expect that! The correct spectrum is: spectrum=[-3.16230928e-03 -3.16227766e-08 -3.16227766e-13 -3.16227766e-18 -3.16227766e-23 -3.16227766e-28 -3.16227766e-33 -3.16227766e-38 -3.16227766e-43 -3.16227766e-48 -3.16227766e-53 -3.16227766e-58 -3.16224604e-63 3.16224604e-63 3.16227766e-58 3.16227766e-53 3.16227766e-48 3.16227766e-43 3.16227766e-38 3.16227766e-33 3.16227766e-28 3.16227766e-23 3.16227766e-18 3.16227766e-13 3.16227766e-08 3.16230928e-03] Nevertheless, the other functions (which involve the computation of the eigenvectors also) fail, and I can't go on because I need the eigenvectors. I have to say that C++ is able to compute correctly also the eigenvectors. So I have two questions: Why the function np.linalg.eigh(denseHam) gives different spectrum than np.linalg.eigvalsh(denseHam)? Is there any way to compute correctly the eigenvectors with python? Thank you very much in advance! --- UPDATE------ I paste here a minimal complete example. Note the exporeou…
type: AnsweredQuestion
upvote count: 5
tagged with: linear-algebra
possible better answer: http://stackoverflow.com/a/52219120

http://stackoverflow.com/comment/91277678
type: QuestionComment
comment on: http://stackoverflow.com/q/52164115
score: 0
has text: So, what would `counts` be here?
type: Comment

http://stackoverflow.com/a/52213160
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52201744
has body: According to your question in the above comment, I've come up with a working solution. However, I'm still not sure what you are trying to achieve because I'm missing the context you are using this operation in. But let me take a stab anyway. So each X row iterated has it's own label matrix given by the to_categorical operation. Therefore, I've designed Y (which I think is what you want) as a list. Then during iteration, I assign the newly created matrix to the corresponding element of the Y list. # load dataset dataframe = pandas.read_csv("data/development.csv") dataset = dataframe.values X = dataset[:,0:7].astype(int) num_classes = np.max(X) # Y is a list of matrices, one matrix for each row of X iterated below Y = [None for _ in range(X.shape[0])] encoder = LabelEncoder() for i in [3,4,5,6]: col = X[i] # Get the number of classes present in that vector num_classes = np.max(X[i]) encoder.fit(col) encoded_col = encoder.transform(col) # Set Y[i] to the new one-hot-encoded matrix Y[i] = np_utils.to_categorical(encoded_col) # Error is here print([y.shape for y in Y if y is not None])

http://stackoverflow.com/comment/91365578
comment on: http://stackoverflow.com/q/52185475
type: Comment
type: QuestionComment
has text: I have just edited my question with my newest attempt
score: 0

http://stackoverflow.com/q/52147970
score: 0
has body: Hey i'm making this space shooter game in pygame and want to spawn 10 enemies at a time. Here is the code i used: blocks.append([random.randrange(0, display_width),0]) for block in blocks: pygame.draw.rect(game_display, green, (block[0],block[1], 30, 40)) for leng in range(len(blocks)): blocks[leng][1]+=10 for block in blocks: if block[1]&lt;0: blocks.remove(block) Using this code, my screen gets filled with enemies(green rects). Is there any way i can spawn a certain number of enemies at a time and keep spawning more if the enemy goes off the screen or dies?
answer count: 1
tagged with: pygame
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
type: Question
has title: Enemies in pygame
has answer: http://stackoverflow.com/a/52150183

http://stackoverflow.com/q/52267088
favorite count: 0
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91482192
possible better answer: http://stackoverflow.com/a/52267105
type: AnsweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json
tagged with: dataframe
has answer: http://stackoverflow.com/a/52267128
accepted answer: http://stackoverflow.com/a/52267128
type: Question
has title: How to parse json into panda dataframe
answer count: 2
has answer: http://stackoverflow.com/a/52267105
tagged with: pandas
upvote count: 1
has body: I have the following json structure that I'm trying to parse: [ { "id": 0, "cuisine": "greek", "ingredients": [ "romaine lettuce", "black olives", "feta cheese crumbles" ] }, { "id": 1, "cuisine": "southern_us", "ingredients": [ "plain flour", "ground pepper", "milk", "vegetable oil" ] }....] There's thousands of values in this JSON-file and I want to parse it into a panda dataframe. How would I go about doing that considering there's a nested list under the ingredients key. Cheers :)

http://stackoverflow.com/comment/91373730
type: Comment
type: QuestionComment
has text: The error appears to be saying that you (or elm) are calling `len()` on an object that has no size.
comment on: http://stackoverflow.com/q/52212157
score: 0

http://stackoverflow.com/comment/91203889
type: Comment
type: QuestionComment
has text: I appreciate it, I was reading the values in from a file and didn't even think about that being a problem, if you wanna post that as the answer i'll mark it.
comment on: http://stackoverflow.com/q/52125760
score: 0

http://stackoverflow.com/comment/91371971
has text: sympy has a [`preview` function](https://docs.sympy.org/latest/modules/printing.html#sympy.printing.preview.preview) that does this.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52211220
type: QuestionComment

string
tags question: http://stackoverflow.com/q/52155591
tags question: http://stackoverflow.com/q/52243287
tags question: http://stackoverflow.com/q/52188408
tags question: http://stackoverflow.com/q/52254377
tags question: http://stackoverflow.com/q/52167339
tags question: http://stackoverflow.com/q/52182433
tags question: http://stackoverflow.com/q/52116006
tags question: http://stackoverflow.com/q/52176606
tags question: http://stackoverflow.com/q/52158344
tags question: http://stackoverflow.com/q/52133732
tags question: http://stackoverflow.com/q/52130001
tags question: http://stackoverflow.com/q/52207136
tags question: http://stackoverflow.com/q/52228525
tags question: http://stackoverflow.com/q/52144819
tags question: http://stackoverflow.com/q/52116762
tags question: http://stackoverflow.com/q/52191628
tags question: http://stackoverflow.com/q/52228662
tags question: http://stackoverflow.com/q/52141057
tags question: http://stackoverflow.com/q/52270401
tags question: http://stackoverflow.com/q/52126498
tags question: http://stackoverflow.com/q/52183330
tags question: http://stackoverflow.com/q/52236610
tag name: string
tags question: http://stackoverflow.com/q/52125152
tags question: http://stackoverflow.com/q/52195607
tags question: http://stackoverflow.com/q/52146661
tags question: http://stackoverflow.com/q/52184372
tags question: http://stackoverflow.com/q/52227266
tags question: http://stackoverflow.com/q/52240936
tags question: http://stackoverflow.com/q/52227548
tags question: http://stackoverflow.com/q/52255302
tags question: http://stackoverflow.com/q/52223059
tags question: http://stackoverflow.com/q/52231791
tags question: http://stackoverflow.com/q/52119128
tags question: http://stackoverflow.com/q/52239692
tags question: http://stackoverflow.com/q/52266352
tags question: http://stackoverflow.com/q/52241164
tags question: http://stackoverflow.com/q/52241969
tags question: http://stackoverflow.com/q/52176990
type: Tag
tags question: http://stackoverflow.com/q/52194174
tags question: http://stackoverflow.com/q/52209617
tags question: http://stackoverflow.com/q/52246391
tags question: http://stackoverflow.com/q/52244850
tags question: http://stackoverflow.com/q/52209092
tags question: http://stackoverflow.com/q/52199185
tags question: http://stackoverflow.com/q/52127529
tags question: http://stackoverflow.com/q/52171427
tags question: http://stackoverflow.com/q/52181024
tags question: http://stackoverflow.com/q/52149058
tags question: http://stackoverflow.com/q/52119879
tags question: http://stackoverflow.com/q/52211636
tags question: http://stackoverflow.com/q/52182944
tags question: http://stackoverflow.com/q/52260806
tags question: http://stackoverflow.com/q/52150727
tags question: http://stackoverflow.com/q/52229523
tags question: http://stackoverflow.com/q/52255550
tags question: http://stackoverflow.com/q/52254186
tags question: http://stackoverflow.com/q/52243247
tags question: http://stackoverflow.com/q/52139976
tags question: http://stackoverflow.com/q/52201340
tags question: http://stackoverflow.com/q/52125260
tags question: http://stackoverflow.com/q/52175020
tags question: http://stackoverflow.com/q/52194746
tags question: http://stackoverflow.com/q/52216053
tags question: http://stackoverflow.com/q/52233295
tags question: http://stackoverflow.com/q/52112783
tags question: http://stackoverflow.com/q/52176002
tags question: http://stackoverflow.com/q/52238462
tags question: http://stackoverflow.com/q/52235073
tags question: http://stackoverflow.com/q/52148560
tags question: http://stackoverflow.com/q/52155603
tags question: http://stackoverflow.com/q/52253357
tags question: http://stackoverflow.com/q/52240343
tags question: http://stackoverflow.com/q/52123501
tags question: http://stackoverflow.com/q/52134635
tags question: http://stackoverflow.com/q/52180879
tags question: http://stackoverflow.com/q/52176797
tags question: http://stackoverflow.com/q/52179198
tags question: http://stackoverflow.com/q/52215289

http://stackoverflow.com/comment/91393954
comment on: http://stackoverflow.com/a/52192168
has text: Yes, `content` returns a [normal string](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.content)
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52135412
has body: No, it isn't. It is an iterable view of the items in the dict: &gt;&gt;&gt; next({}.items()) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'dict_items' object is not an iterator &gt;&gt;&gt; It's __iter__ method returns a specialized iterator instance: &gt;&gt;&gt; iter({}.items()) &lt;dict_itemiterator object at 0x10478c1d8&gt; &gt;&gt;&gt;
type: AcceptedAnswer
type: Answer
upvote count: 9
accepted answer of: http://stackoverflow.com/q/52135345
answers question: http://stackoverflow.com/q/52135345
downvote count: 0
score: 9

http://stackoverflow.com/q/52223228
tagged with: django
has comment: http://stackoverflow.com/comment/91396594
has comment: http://stackoverflow.com/comment/91396363
has comment: http://stackoverflow.com/comment/91395482
has title: Django ORM Group BY and return additional fields
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91395595
has comment: http://stackoverflow.com/comment/91395982
tagged with: python
has comment: http://stackoverflow.com/comment/91395554
has comment: http://stackoverflow.com/comment/91396267
has body: I want to perform query like this: SELECT loan_id, tenor, amount COUNT(id) AS total FROM loan GROUP BY loan_id But, I want only use 1 group by field "loan_id", how to return other fields like "tenor", "amount" I don't want tenor and amount in GROUP BY clause. How to achive using django ORM? This is result without group by: loan_id | tenor | amount 36573 11 900000.00 36573 11 900000.00 36571 2 1800000.00 36571 11 1800000.00 I want to result like this: loan_id | tenor | amount | total 36571 2 1800000.00 2 36573 11 900000.00 2
answer count: 0
has comment: http://stackoverflow.com/comment/91395954
type: UnansweredQuestion
tagged with: django-orm
has comment: http://stackoverflow.com/comment/91395948

http://stackoverflow.com/a/52126609
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52126524
score: 10
upvote count: 10
has body: You could do this with a while loop inside the for loop, and only break out of that loop when the thing you attempted succeeded: for i in range(20): while True: result = do_stuff() # function should return a success state! if result: break # do_stuff() said all is good, leave loop Depends a little on the task, e.g. you might want try-except instead: for i in range(20): while True: try: do_stuff() # raises exception except StuffError: continue break # no exception was raised, leave loop If you want to impose a limit on the number of attempts, you could nest another for loop like this: for i in range(20): for j in range(3): # only retry a maximum of 3 times try: do_stuff() except StuffError: continue break

http://stackoverflow.com/q/52160845
has body: I have a page where the structure is something like &lt;body&gt; &lt;article&gt; &lt;!--article no 1--&gt; &lt;h3&gt; &lt;h2&gt; &lt;h1&gt; &lt;a&gt; &lt;!--first 'a' tag--&gt; &lt;article&gt; &lt;!--article no 2--&gt; &lt;h1&gt; &lt;h2&gt; &lt;a&gt; &lt;!--second 'a' tag--&gt; &lt;/article&gt; &lt;/article&gt; &lt;/body&gt; Now what I want is I want to extract all 'a' tags inside an article but such that no 'a' tag comes from any nested that is articles = browser.find_elements_by_tag_name("article") for i in article: print(i.find_elements_by_tag_name("a") for first article now i.find_elements will return all 'a' tags inside this article tag which will also include 'a' tags inside 'article tag' that is itself nested in current article tag but i dont want that I want if i call find_elements on article no 1 'a' tags in article no 2 or in any nested article should not come
has comment: http://stackoverflow.com/comment/91271588
has comment: http://stackoverflow.com/comment/91271706
type: AnsweredQuestion
score: 1
tagged with: selenium
possible better answer: http://stackoverflow.com/a/52160932
tagged with: web-scraping
upvote count: 1
has comment: http://stackoverflow.com/comment/91271533
has answer: http://stackoverflow.com/a/52160932
type: Question
accepted answer: http://stackoverflow.com/a/52160992
has comment: http://stackoverflow.com/comment/91271765
has answer: http://stackoverflow.com/a/52163955
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/91271451
favorite count: 0
has title: scraping only a particular tag without details from nested tag in that particular tag
has comment: http://stackoverflow.com/comment/91271352
has comment: http://stackoverflow.com/comment/91271380
tagged with: python
has answer: http://stackoverflow.com/a/52160992

http://stackoverflow.com/q/52228631
has comment: http://stackoverflow.com/comment/91406900
has title: Python3 RE match characters or no characters at end of line
has answer: http://stackoverflow.com/a/52228717
has comment: http://stackoverflow.com/comment/91407033
type: Question
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52228754
has body: I have a line of text that I need to pull a substring from that may or may not have characters following the substring. Examples: Robin Hood viewed item "something.mov" (99.12345.567891011) or... Robin Hood viewed item "something.mov" (88.123.456789101) some other stuff. I need to pull the substring that is inside the parentheses. The substring will always be three sets of digits separated by two periods. The string in quotes with the .mov at the end can also include arbitrary characters so the search should always start at the end of the line. If there are characters after the closing paren then there will be a . at the end of the line. If there are no characters following the closing paren then there will be no . at the end of the line. Right now I have: mo = re.search(r'(\d[\d.]*)\).*$', data1) However, this breaks on some matches. The problem is that the tool I'm using (Matillion) does not spit out the lines it fails on so I don't know why.
tagged with: python
tagged with: regex
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52228719

http://stackoverflow.com/comment/91382595
type: Comment
comment on: http://stackoverflow.com/a/52216863
has text: I edited my answer, please let me know if that's clear enough
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91449674
has text: Yes, the code is correct it works up to n being a 200 digit number, but when n exceeds a 200 digit number it does not work. The distance function just returns a constant. And it is not iterative.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52250960

http://stackoverflow.com/comment/131924766
type: AnswerComment
comment on: http://stackoverflow.com/a/52119433
type: Comment
has text: The sited source in this post has changed. It can be found [here](https://blogs.oracle.com/ai-and-datascience/post/introduction-to-bayesian-inference)
score: 0

http://stackoverflow.com/comment/91382555
type: Comment
has text: waiting @sandep's editing the answer, if not this is will be the best answer
comment on: http://stackoverflow.com/a/52216815
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91511573
type: AnswerComment
has text: I had the same problem when I tried to do it myself. That's when I gave up and posted it here, haha.
type: Comment
comment on: http://stackoverflow.com/a/52172004
score: 0

http://stackoverflow.com/a/52255476
score: 0
type: Answer
has body: The space matters too: return ''.join(letter if letter in vowels or letter == ' ' else (letter + 'o' + letter)for letter in sentence) So whole, code: vowels = list('aeiouyäöå') consonants = list('qwrtpsdfghjklzxcvbnm') # if letter is a consonant then double it and out 'o' in between. def rovarspraket(sentence): return ''.join(letter if letter in vowels or letter == ' ' else (letter + 'o' + letter)for letter in sentence) print(rovarspraket('hello friend')) Output: hohelollolo fofrorienondod
answers question: http://stackoverflow.com/q/52255302

http://stackoverflow.com/q/52233512
has comment: http://stackoverflow.com/comment/91431950
has comment: http://stackoverflow.com/comment/91417628
has comment: http://stackoverflow.com/comment/91416053
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91421009
type: Question
has title: Python integration of large array of coefficient
has answer: http://stackoverflow.com/a/52235336
has body: I'm trying to optimize simple integration in python which looks something like from scipy import integrate import numpy as np from scipy.special import kv import time #Example function def integrand(x, a, b, c): return a * (x ** (-b)) * (np.sqrt(x ** (c) + 1) - 1) #Real Function that I want to calculate def Bes(xx): return integrate.quad(lambda x: kv(5./3.,x), xx,np.inf) def F(x,a,b,c,d,e,f): zx = 1/((x**2.+1)*a) feq = e*x**(f) if (x&gt;c): feq *= c/x * np.exp(-(x/d)**2.) return b*Bes(zx)*feq*x**2. start = time.time() array_length = 10 a = np.random.rand(array_length)+3. b = np.random.rand(array_length)+1. c = np.random.rand(array_length) d = (np.random.rand(array_length)+1)*100. e = np.random.rand(array_length)*100. f = np.random.rand(array_length) inte = np.array([]) for i in range(array_length): result = integrate.quad(lambda x: F(x, a[i], b[i], c[i],d[i],e[i],f[i]),0.01,100000.) inte = np.append(inte,result[0]) print("For array length = %i" % array_length) print("Time = %.2f [sec]" %(time.time()-start)) But the problems that I'm facing are a, b, c are array with length > 10^7 (same length) integration range of x starts at 0.01 and extends to infinite Integration at the small x (like [0.01, 1]) is very important and needs small step. I want to integrate this function on each coefficient value and returns the entire array of integration as the result (length ~ 10^7), efficiently. What kind of tools should I use? (+) I just changed my code from simple example to actual integration form that I need to solve. Sorry for making confusion.
score: 0
has comment: http://stackoverflow.com/comment/91416068
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91359586
score: 0
type: AnswerComment
has text: Unless you can provide the exact code and similar data such that such that the error is reproducible, I'm not sure what else to suggest.
comment on: http://stackoverflow.com/a/52162206
type: Comment

http://stackoverflow.com/comment/91196950
score: 0
type: Comment
has text: thanks I will give it a try.
type: QuestionComment
comment on: http://stackoverflow.com/q/52122242

correlation
tags question: http://stackoverflow.com/q/52183321
tags question: http://stackoverflow.com/q/52181638
tag name: correlation
type: Tag
tags question: http://stackoverflow.com/q/52219949
tags question: http://stackoverflow.com/q/52147130

http://stackoverflow.com/q/52249702
score: 1
has comment: http://stackoverflow.com/comment/91447606
favorite count: 0
linked to: http://stackoverflow.com/q/52232129
tagged with: pandas
has title: Most computationally efficient way to map a unique number to each unique string in a column of lists
has comment: http://stackoverflow.com/comment/91447578
has comment: http://stackoverflow.com/comment/91447657
has answer: http://stackoverflow.com/a/52249909
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91447646
type: Question
accepted answer: http://stackoverflow.com/a/52249909
has body: This is a follow up to this question How to map a unique number to each unique string in a column of lists Which asks how to map a unique number to items across multiple pandas columns containing lists. The solution given seems to be very slow when the number of items (total of items in column A and column B) is in the range of ~40 million. I have found some ways that can assign unique numbers to datasets for ~40 million items faster, but none quite for the situation of multiple columns , one of which contains a list. Here was the minimal example and solution from the link above: Setting up the dataframe df = pd.DataFrame(data={'A': ['2f4', '1k1', 'nmk'], 'B': ['x', 'y', 'z']}) df.at[0, 'B'] = ['jki', 'gg4', 'k6k'] df.at[1, 'B'] = ['2f4', 'gg4', 'g24'] df.at[2, 'B'] = ['1k1', 'g24', '1k1', 'pir'] df A B 0 2f4 [jki, gg4, k6k] 1 1k1 [2f4, gg4, g24] 2 nmk [1k1, g24, 1k1, pir] Solution i, u = pd.factorize([*df.A, *np.concatenate(df.B)]) l = df.B.str.len()[:-1].cumsum() n = len(df) df.assign(MappedA=i[:n], MappedB=np.split(i[n:], l)) A B MappedA MappedB 0 2f4 [jki, gg4, k6k] 0 [3, 4, 5] 1 1k1 [2f4, gg4, g24] 1 [0, 4, 6] 2 nmk [1k1, g24, 1k1, pir] 2 [1, 6, 1, 7] I am trying to see if there's a more computationally efficient solutions. I suspect this is so because there are methods than can assign unique numbers to ~40 million items with in a few minutes (where as the solution above never seems to complete). Here is one such solution mapping = {k: v for v, k in enumerate(df.A.unique())} df['MappedA'] = df.A.map(mapping) I am wondering if there's a way to somehow apply this to my situation, where the items in column A and column B are mapped to unique numbers, starting at 0, with the items in column A getting the first numbers, then assigning leftover unique items in column B. Edit: A user mentioned that pandas is not the most computationally efficient way for dealing with lists of strings. I can convert this to a numpy array via numpyArray = df.values So if there's a way t…
answer count: 1
downvote count: 0

http://stackoverflow.com/a/52198149
score: 1
upvote count: 1
has body: I belive this should work: import io import os import subprocess def extract_audio(video,output): command = "ffmpeg -i {} -ac 1 -f flac -vn {}".format(video, output) subprocess.call(command,shell=True) extract_audio('dm.MOV','dm-new.flac')
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52197883

http://stackoverflow.com/comment/91457489
has text: You probably mean`print(children[count-2].tag, count)`. This can, however, still behave unexpectedly if `count` is `0` or `1`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52255060
score: 2

http://stackoverflow.com/comment/91278189
has text: The code is already there.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52163423

http://stackoverflow.com/a/52166830
answers question: http://stackoverflow.com/q/52166750
score: 2
downvote count: 0
upvote count: 2
has body: A dictionary cannot have identical keys. So, every time you are doing data['snm'] = i you are replacing the value. Also, your append adds the same dictionary every time, not a copy. So, you list does not have 5 dictionaries, it has 5 references to the same dictionary. And, when it changes, all positions of your list change. Short fix: add a new dict every time for i in range(5): atho.append({'snm': i})
type: Answer

http://stackoverflow.com/q/52122424
answer count: 1
has comment: http://stackoverflow.com/comment/91197884
has comment: http://stackoverflow.com/comment/91196267
favorite count: 0
has comment: http://stackoverflow.com/comment/91196461
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
tagged with: selenium
tagged with: google-chrome
has body: I want to save a webpage. This looks simples. I used the code below. This opens the browser but the page is not saved. Why? When this works, where the file will be saved? Thanks Detais: Chrome 68.0.3440.106 - 64 bits ChromeDriver 2.41 Code: from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys browser = webdriver.Chrome(executable_path=r"C:\Program Files (x86)\Selenium\chromedriver.exe") browser.get('https://automatetheboringstuff.com') ActionChains(browser).key_down(Keys.CONTROL).send_keys('s').key_up(Keys.CONTROL).perform()
type: Question
has answer: http://stackoverflow.com/a/52122598
has title: Selenium + Chrome + Python
score: 0

http://stackoverflow.com/a/52195409
has comment: http://stackoverflow.com/comment/91340470
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91340491
type: Answer
has comment: http://stackoverflow.com/comment/91340534
has comment: http://stackoverflow.com/comment/91340498
has comment: http://stackoverflow.com/comment/91340489
answers question: http://stackoverflow.com/q/52195208
has body: Just like in real life, word-by-word translation will require a dictionary. english_to_dovahzul = { 'the': 'faal', 'quick': 'nel', 'brown': 'prun' } def translate(text, dictionary, filler=None): return ' '.join([dictionary.get(word, filler or word) for word in text.split()]) print(translate('the quick brown fox', english_to_dovahzul, filler='?')) Output faal nel prun ? You will extend your language by adding words to the dictionary. To get the inverse translation, you can invert your dictionary like so. dovahzul_to_english = {v: k for k, v in english_to_dovahzul.items()} Of course, modern translation is far from using word-by-word like this, but it seems to be enough for your purpose.
score: 0
accepted answer of: http://stackoverflow.com/q/52195208

http://stackoverflow.com/q/52164137
has comment: http://stackoverflow.com/comment/91277712
has comment: http://stackoverflow.com/comment/91277775
has answer: http://stackoverflow.com/a/52164185
has answer: http://stackoverflow.com/a/52164216
has answer: http://stackoverflow.com/a/52164272
type: Question
upvote count: 4
tagged with: min
has title: Find minimum non zero value in dictionary (Python)
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/52169495
has body: I have a dictionary and I would like to get the key whose value is the minimum nonzero. E.g. given the input: {1:0, 2:1, 3:2} It would return 2.
favorite count: 0
tagged with: python-3.x
answer count: 5
has answer: http://stackoverflow.com/a/52165647
type: UnansweredQuestion
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/52142376
tagged with: python-3.x
type: UnansweredQuestion
has body: I'm working with some massive trees and I want to be able to store them in text files and reconstruct them elsewhere without having to recreate the tree each time. I'm using AnyTree to make my trees. The trees contain numpy arrays, so JSON conversion is not supported. I'm exporting them as nested dictionaries. This is how I write the tree to a text file. #Exports the tree to the given filename as a dictionary def TreetoDict(filename, root): exporter = DictExporter() dictoutput = exporter.export(root) string = str(dictoutput) with open(filename,"w") as f: f.write(string) f.close() print("Finished writing") return dictoutput Since the tree is so large, I presume turning the dictionary to a string put a lot of line breaks in the form of " " without my consent. This is what the text file looks like. ("{'center': array([0, 0, 0]), 'radius': 2, 'name': '([0 0 0],2)', " "'numpoints': 0, 'centerofmass': array([0, 0, 0]), 'children': [{'center': " "array([1., 1., 1.]), 'radius': 1.0, 'name': '([1. 1. 1.],1.0)', 'numpoints': " "0, 'centerofmass': array([0, 0, 0]), 'children': [{'center': array([1.5, " "1.5, 1.5]), 'radius': 0.5, 'name': '([1.5 1.5 1.5],0.5)', 'numpoints': 0, " "'centerofmass': array([0, 0, 0])}, {'center': array([1.5, 1.5, 0.5]), " "'radius': 0.5, 'name': '([1.5 1.5 0.5],0.5)', 'numpoints': 0, " "'centerofmass': array([0, 0, 0]), 'children': [{'center': array([1.75, 1.75, " "0.75]), 'radius': 0.25, 'name': '([1.75 1.75 0.75],0.25)', 'numpoints': 0, " "'centerofmass': array([0, 0, 0]), 'children': [{'center': array([1.875, " "1.875, 0.875]), 'radius': 0.125, 'name': '([1.875 1.875 0.875],0.125)', " "'numpoints': 0, 'centerofmass': array([0, 0, 0])}, {'center': array([1.875, " etc. How can I can format the dictionary as a string to be put in a text file, which I can subsequently read to reconstruct the tree?
tagged with: python
tagged with: tree
has answer: http://stackoverflow.com/a/52142670
downvote count: 1
type: Question
upvote count: 0
score: -1
has title: Create a massive tree from anytree from a text file (Python)
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/91208827
comment on: http://stackoverflow.com/q/52126516
score: 0
type: QuestionComment
type: Comment
has text: @Jezreel.Martin: With reference to the sketch of two buttons in one column, where do you want to see this i.e. in the RecycleView or Popup?

recaptcha
tag name: recaptcha
type: Tag
tags question: http://stackoverflow.com/q/52230088

http://stackoverflow.com/comment/91275421
comment on: http://stackoverflow.com/q/52148541
has text: It looks like the `(750, 750)` you have is too big for your GPU RAM. As for the other error, I can't really help you if you don't post the stack trace and show where the error generated in the code. Was the dimension of the image you used divisible by a power of 2?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52115204
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91180875
has comment: http://stackoverflow.com/comment/91181043
has comment: http://stackoverflow.com/comment/91180856
score: 1
has body: How can I match quotes around number: Here is what I have: "Austria","AU","ULO1","185","34","4dera" Here is what I need: "Austria","AU","ULO1",185,34,"4dera" This is the closest I did:\"(?=\d)|(?&lt;=\d)\", but the problem with that is that it also matches words that start with number and I can not put +,*or. in Look-behind or Look-ahead. I am trying to change .csv file with 1400 rows like this. I can replace it with Notepad++ because it supports regex or with python script.
tagged with: regex-negation
has answer: http://stackoverflow.com/a/52115304
type: Question
has comment: http://stackoverflow.com/comment/91180897
has comment: http://stackoverflow.com/comment/91180972
has title: How to match only quotes around word that has only numbers in it?
has comment: http://stackoverflow.com/comment/91180992
accepted answer: http://stackoverflow.com/a/52115373
has answer: http://stackoverflow.com/a/52115266
upvote count: 2
has answer: http://stackoverflow.com/a/52115292
downvote count: 1
possible better answer: http://stackoverflow.com/a/52115266
has answer: http://stackoverflow.com/a/52115373
favorite count: 0
tagged with: python
tagged with: regex
answer count: 4

http://stackoverflow.com/a/52233158
has comment: http://stackoverflow.com/comment/91416833
type: Answer
has body: I have reproduced your file With df = pd.read_csv('e1.csv', index_col=None ) print (df) Output id emp details createdat 0 1 john "{"Country":"USA","Salary":5000,"Review":null}" "2018-09-01" 1 2 sarah "{"Country":"Australia", "Salary":6000,"Review... "2018-09-05"
score: 0
has comment: http://stackoverflow.com/comment/91415375
has comment: http://stackoverflow.com/comment/91415343
answers question: http://stackoverflow.com/q/52233046

http://stackoverflow.com/comment/91284042
comment on: http://stackoverflow.com/q/52166920
has text: You proc must be the udf which you can control. mapping is just mapping the attributes to the function. It will fail if your attributes are erroneous or your udf is not able to consume the attributes passed as arguments to the udf. If mapping was successful then you will have a valid list otherwise control your udf to return something unusual values if something went wrong and check the list after executing the map. Hope it all makes sense.
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/a/52242440
has comment: http://stackoverflow.com/comment/91434666
type: AcceptedAnswer
downvote count: 0
has body: Do a groupby on the date every 15 minutes using the pd.Grouper, and then create a new DataFrame with the result: df['date'] = pd.to_datetime(df.date, errors='coerce') v = df.groupby(pd.Grouper(key='date', freq='15min'))['price'].apply(list) pd.DataFrame(v.tolist(), index=v.index).add_prefix('price ') price 0 price 1 price 2 date 2018-09-09 08:30:00 22.10 22.12 22.20 2018-09-09 08:45:00 22.13 22.19 22.39
type: Answer
has comment: http://stackoverflow.com/comment/91435054
score: 4
accepted answer of: http://stackoverflow.com/q/52242418
upvote count: 4
answers question: http://stackoverflow.com/q/52242418

http://stackoverflow.com/comment/91328061
type: Comment
comment on: http://stackoverflow.com/q/52188421
type: QuestionComment
score: 2
has text: Great spy tool - just the less and less space on the HD is limiting its usefullness ... and having to sieve through 8*60*12 = 5780 pictures each day to find the gems: banking information, shady frequented websites, work on code or private data that is confidential, ...

http://stackoverflow.com/a/67336354
type: Answer
answers question: http://stackoverflow.com/q/52255808
has comment: http://stackoverflow.com/comment/119043331
score: 0
has comment: http://stackoverflow.com/comment/119095624
has body: For Python 3.8 (Jupyter Notebook Anaconda) import matplotlib import matplotlib.pyplot as plt import matplotlib.ticker as mticker import matplotlib.dates as mdates import numpy as np import time def bytespdate2num(b): return mdates.datestr2num(b.decode('utf-8')) date, bid, ask = np.loadtxt('GBPUSD1d.txt', unpack=True, delimiter=',', converters={0:bytespdate2num}) def percentChange (startPoint, currentPoint): return ((float(currentPoint)-startPoint)/startPoint)*100.0 def patternFinder(): avgLine = ((bid+ask)/2) x = len(avgLine) - 30 y = 11 while y &lt; x: p1 = percentChange(avgLine[y-10], avgLine[y-9]) p2 = percentChange(avgLine[y-10], avgLine[y-8]) p3 = percentChange(avgLine[y-10], avgLine[y-7]) p4 = percentChange(avgLine[y-10], avgLine[y-6]) p5 = percentChange(avgLine[y-10], avgLine[y-5]) p6 = percentChange(avgLine[y-10], avgLine[y-4]) p7 = percentChange(avgLine[y-10], avgLine[y-3]) p8 = percentChange(avgLine[y-10], avgLine[y-2]) p9 = percentChange(avgLine[y-10], avgLine[y-1]) p10 = percentChange(avgLine[y-10], avgLine[y]) outcomeRange = avgLine[y+20:y+30] currentPoint = avgLine[y] print (sum(outcomeRange) / len(outcomeRange) ) print (currentPoint) print (' ____') print (p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) y += 1 time.sleep(5555) patternFinder() Output 1.553601 1.553555 -0.001930961683282023 -0.0032182694721319405 -0.0032182694721319405 -0.0035400964193622853 -0.003861923366564046 -0.005471058102644308 -0.0061147119970621205 -0.00450557726099615 -0.00450557726099615 -0.004827404208212203

http://stackoverflow.com/q/52270883
possible better answer: http://stackoverflow.com/a/52271046
score: 0
has answer: http://stackoverflow.com/a/52271476
has comment: http://stackoverflow.com/comment/91489085
has comment: http://stackoverflow.com/comment/91489009
has comment: http://stackoverflow.com/comment/91489087
tagged with: python
has answer: http://stackoverflow.com/a/52271046
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91489139
linked to: http://stackoverflow.com/q/13921091
has body: I am trying to create a directory crawler to search for specific keywords in all files inside a folder and all its subfolders. This is what I have so far (in this case I am looking for keyword 'olofx'): import os rootDir = os.getcwd() def scan_file(filename, dirname): print(os.path.join(dirname,filename)) contains = False if("olofx" in filename): contains = True else: with open(os.path.join(dirname,filename)) as f: lines = f.readlines() for l in lines: #print(l) if("olofx" in l): contains = True break if contains: print("yes") for dirName, subdirList, fileList in os.walk(rootDir): for fname in fileList: scan_file(fname, dirName) Problem is when I reach one of my sample excel files, the characters seem to be unreadable. here is some of the output for the excel file: ;���+͋�۳�L���P!�/��KdocProps/core.xml �(���_K�0���C�{�v�9Cہʞ n(���v 6H�ݾ�i���|Lι��sI���:��VJ' �@1ͅ�h�^�s9O��VP�8�(//r���6`��r���7c�v ��� I have worked with openpyxl and I know I can use that to read excel files, but I want one script that reads all kinds of files: word, excel, pdf etc. Anyway to represent files' contents regardless of file types? Thank you
type: Question
has title: Python directory crawler to scan all kinds of files and search for keyword
answer count: 2
accepted answer: http://stackoverflow.com/a/52271476

http://stackoverflow.com/comment/91342904
comment on: http://stackoverflow.com/q/52196721
has text: beware of `start[y]` and with `end[y]`, instead of `y` it goes `key`
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52145830
has answer: http://stackoverflow.com/a/52146014
tagged with: linux
has title: timing and redirecting subprocess:PIPE output to file
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/50111465
tagged with: python
tagged with: subprocess
linked to: http://stackoverflow.com/q/12270645
tagged with: timing
type: Question
tagged with: stdout
linked to: http://stackoverflow.com/q/21953835
score: 0
answer count: 1
has body: I'm trying to execute a bash and want to redirect the output on the shell to a file this is what I have so far baby = subprocess.Popen('some command', stdout = subprocess.PIPE, shell = True) print (baby.stdout.readlines()) #i wanna see it in console with open("log.txt","a") as fobj: #wanna create a file log.txt and save the output there as string fobj.write(stdout) but I get this error NameError: name 'stdout' is not defined I've looked at these question Run subprocess and print output to logging , subprocess.Popen() doesn&#39;t redirect output to file , Can you make a python subprocess output stdout and stderr as usual, but also capture the output as a string? but to no avail, they were all too complex for me, i got lost in all the code.. can't i just redirect the stdout to a normal txt file? and is there a way I can built a function to time the execution of that script and put it in that same log.txt file (i use time ./myscript.py to take the time but i also don't know how to redirect it to the txt file)

http://stackoverflow.com/comment/134018485
has text: This will measure the time to complete the response (both waiting and transferring data), NOT the time *waiting* for a response alone.
type: AnswerComment
comment on: http://stackoverflow.com/a/75977162
score: 0
type: Comment

http://stackoverflow.com/comment/91246447
type: Comment
has text: Oh yes, that could look like it does the trick. I'll try.
comment on: http://stackoverflow.com/q/52147558
score: 0
type: QuestionComment

http://stackoverflow.com/q/52180246
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 0
type: Question
downvote count: 0
has body: This is my code which just accepts numbers and add them and displays results in label, numbers are accepted through spinners. But I need splash screen before the main app is loaded. I want to know how we can use image as an splash screen and display for a while until the main app starts. from kivy.lang import Builder from kivy.uix.floatlayout import FloatLayout from kivy.properties import StringProperty from kivy.uix.spinner import Spinner from kivy.app import App Builder.load_string(''' &lt;MainScreen&gt;: GridLayout: orientation: 'vertical' cols: 1 canvas.before: Color: rgba: 1, 1, 1, 1 Rectangle: pos: self.pos size: self.size GridLayout: orientation: 'vertical' cols: 2 Spinner: id: first text: ' First Number' values: ['1','2','3','4','5','6','7','8','9'] Spinner: id: second text: ' Second Number' values: ['1','2','3','4','5','6','7','8','9'] Label: id: result text: ' Result' color: 0,0,0,1 Button: id: res on_press: root.onPow(first.text,second.text) text: 'Progress' ''') class MainScreen(FloatLayout): changet = StringProperty() def __init__(self, **kwargs): super(MainScreen, self).__init__(**kwargs) def onPow(self,fir,sec): a = 0 b = 0 for i in range((10000)): print(b) self.ids.result.text=str(b*(int(fir)*int(sec)+i)) b+=1 class TestApp(App): def build(self): return MainScreen() if __name__ == "__main__": TestApp().run() Image for splash screen: Even can we use labels with this image. Thank you.
has title: How to use image as splash screen in kivy python desktop application with labels?
tagged with: kivy
score: 1
tagged with: spinner
tagged with: splash-screen
favorite count: 0

http://stackoverflow.com/q/52215414
accepted answer: http://stackoverflow.com/a/52215584
tagged with: pandas
answer count: 1
favorite count: 0
score: -3
tagged with: python
has body: Input dataframe: load1 = pd.DataFrame({'A':list('abcdef'), 'B':[4,5,4,5,5,4], }) Rank: Sort B values on descending order and give rank from 1 on incremental order Rank_without_a_column: Leave the first column of the descending order sorted B and give rank from 1 on incremental order Exact_Rank: Give correct ranking as shown in Exact rank on Expected Output Exact_Rank_Without_a_column: Expected Output: A B Rank Rank_without_a_column Exact_Rank Exact_Rank_Without_a_column 0 a 5 1 Null 1 Null 1 b 5 2 1 1 1 2 c 5 3 2 1 1 3 d 4 4 3 2 2 4 e 4 5 4 2 2 5 f 4 6 5 2 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52215584
has title: numbering in pandas on incremental order and also without considering a column?
downvote count: 3
type: Question
upvote count: 0

http://stackoverflow.com/q/52262147
linked to: http://stackoverflow.com/q/26213199
accepted answer: http://stackoverflow.com/a/52262214
type: Question
has comment: http://stackoverflow.com/comment/91472054
has answer: http://stackoverflow.com/a/52262214
has comment: http://stackoverflow.com/comment/91472229
score: 9
tagged with: numpy
tagged with: python-2.7
downvote count: 1
has comment: http://stackoverflow.com/comment/91472104
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91472163
has comment: http://stackoverflow.com/comment/91472007
has title: Speed of np.empty vs np.zeros
upvote count: 10
tagged with: python
has comment: http://stackoverflow.com/comment/91472293
has body: I am using numpy version 1.14.3 and python 2.7.12. Referencing this question, I am finding dramatically different speeds between initializing arrays with np.zeros and np.empty. However, the output is the same. import numpy as np r = np.random.random((50, 100, 100)) z = np.zeros(r.shape) e = np.empty(r.shape) np.allclose(e, z) This returns True. However, the timing functions %timeit gives very different results: %timeit z = np.zeros(r.shape) 10000 loops, best of 3: 143 µs per loop %timeit e = np.empty(r.shape) 1000000 loops, best of 3: 1.83 µs per loop The previously accepted answer referenced above says that np.zeros was always the better choice, and that it is faster too. Why not use np.empty when it is 80 times faster than np.zeros and returns the same answer? Edit As user2285236 pointed out, flipping the order of initializing z and e will break the equality, because it overwrites on the same memory area.
type: AnsweredQuestion

http://stackoverflow.com/q/52244082
favorite count: 0
tagged with: python-3.x
has title: python3 asyncio start_unix_server permission
has comment: http://stackoverflow.com/comment/91437598
type: Question
tagged with: python-asyncio
tagged with: python
accepted answer: http://stackoverflow.com/a/52244784
upvote count: 2
has comment: http://stackoverflow.com/comment/91437787
answer count: 1
has answer: http://stackoverflow.com/a/52244784
type: AnsweredQuestion
score: 2
has body: The software that I run due to special circumstances will be running as a daemon with root privilege. The software will also have API so that normal user can access it without "sudo" everytime ( API is read-only and can only be accessed from localhost ). Then wasting a TCP port with random number TCP port that might be forgotten in the future, I prefer to use a UNIX socket, since it will be run on Linux. I'm using asyncio module to start_unix_server method, but I have trouble with Unix socket file permission since the software starts as root privilege the socket file has "srwxr-xr-x root root" permission and I cannot connect to this file unless I use "sudo". I check that start_unix_server doesn't have any option to change permission, but has sock parameters that accept socket object. So here is what I do and succeeded, but not sure whether this is intended to be done like this import socket import asyncio async def handler(reader, writer): message = data.decode() addr = writer.get_extra_info('peername') print("Received %r from %r" % (message, addr)) print("Send: %r" % message) writer.write(data) await writer.drain() print("Close the client socket") writer.close() socket_file = "/tmp/example-server.socket" if os.path.exists(socket_file): os.remove(socket_file) srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) srv.bind(socket_file) #Here we set the file permission after bind os.chmod(socket_file, 0o666) loop = asyncio.get_event_loop() #Here we pass the socket object to asyncio asyncio.ensure_future(asyncio.start_unix_server(handler, sock=s)) try: loop.run_forever() except: pass finally: loop.close() os.remove(socket_file)
downvote count: 0

http://stackoverflow.com/a/52227474
has comment: http://stackoverflow.com/comment/91405845
upvote count: 1
has comment: http://stackoverflow.com/comment/91405434
has comment: http://stackoverflow.com/comment/91405671
has comment: http://stackoverflow.com/comment/91404498
has comment: http://stackoverflow.com/comment/91405109
downvote count: 0
has body: Based on your info, seems like you need only a simple np.where (if dfs have same length) df1['New?'] = np.where(df1["Some Data"].isin(df2["some data"]), df2['other data'], 'New') Some Data New? 0 Lebron James 123 + other text I want this in df1[New?"]" 1 Lebron James 234 New For different length, mask = df2["some data"].isin(df["Some Data"]).values df.loc[mask,'New'] = df2.loc[mask, 'other data'] df.fillna('New') Explanation Basically you have a mask, and you use the same mask to filter both data frames. This yields the same number of results on both dfs given the descriptions, and you assign the filtered rows' "other data" values from df2 to the same matching rows in df "some data"
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52227248
has comment: http://stackoverflow.com/comment/91404969
has comment: http://stackoverflow.com/comment/91404453

http://stackoverflow.com/q/52113582
tagged with: python
has body: Thanks for looking into this question! :) I attempted to train an LSTM network to predict next 10-day stock prices of Google based on past 30-day stock prices. I trained the LSTM but the loss barely reduced even after 200 iterations. I suspected that the issue might be due to the feed_dict in tf Session. However, I have not identified any issue with that (perhaps due to my superficial knowledge). It seems that the optimizer refreshes every iterations in the tf Session. Would appreciate if I could seek advice on what might have gone wrong in the code, if my understanding on the usage of Optimizer has been wrong. Thanks for your help!! import pandas as pd import matplotlib.pyplot as plt import numpy as np import sys import csv import random import tensorflow as tf from tensorflow.contrib import rnn # Define data reader def read_data(fname): with open(fname) as f: data = list(csv.reader(f)) d_mat = np.array(data) d_trsp = np.transpose(d_mat) date = np.transpose(d_trsp[0]) p_open = d_trsp[1] vol = d_trsp[6] chg = d_trsp[7] chg = [float(i) for i in chg] return vol, chg vol, training_data = read_data('GOOGL.csv') training_data = training_data[0:300] print("Loading training data..") #Split data for learning ratio_train = 0.70 ratio_valid = 0.90-ratio_train ratio_test = 0.10 #fixed at 10% of dataset # Parameters learning_rate = 0.005 training_iters = 100 display_step = 1 x_size = 30 y_size = 5 n_hidden = 256 # Variables x = tf.placeholder("float", [265, x_size]) y = tf.placeholder("float", [265, y_size]) weights = { 'out': tf.Variable(tf.random_normal([n_hidden, y_size])) } biases = { 'out': tf.Variable(tf.random_normal([y_size])) } # Preprocess Data def prod_data(data): x = [] y = [] iter = len(data)-x_size-y_size for i in range(0, iter): x.append(data[i:i+x_size]) y.append(data[i+x_size+1: i+x_size+1+y_size]) return x, y a,b = prod_data(training_data) # Define RNN architecture def RNN(x, weights, biases): # Reshape x to [1, n_input] x = tf.reshape(x, [-1, x_size]) x = tf.…
has comment: http://stackoverflow.com/comment/91227684
answer count: 0
tagged with: tensorflow
type: Question
tagged with: recurrent-neural-network
has title: LSTM Loss remains the same after numerous iterations
tagged with: lstm
tagged with: optimization
score: 0
has comment: http://stackoverflow.com/comment/91179948
type: UnansweredQuestion

http://stackoverflow.com/comment/100205465
type: Comment
has text: works, but the "over" function needs a Window, like this: .over(Window.partitionBy())
comment on: http://stackoverflow.com/a/52131914
score: 0
type: AnswerComment

http://stackoverflow.com/q/52184211
favorite count: 0
has body: I am trying argparse where I wanted to get as date type with format 'YYYYMMDD'. If not provided wanted to use current date. Here is my code but I get: usage: [optional arguments] : error: too few arguments I tried both positional and optional arguments. from datetime import date class ValidateArgs(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): if values is None: print("value is None") setattr(namespace, self.dest, date.today()) else: print("value fine") setattr(namespace, self.dest, values) import argparse import datetime parser = argparse.ArgumentParser(description='xxx', usage='%(prog)s [optional arguments]') parser.add_argument('offset', help='Number of days') parser.add_argument('fromDte', action=ValidateArgs) How to tell the argparser that I am looking for date type 'datetime.date(2018, 9, 5)' How to resolve using default? I invoke as parser.parse_args('2'.split()) I am using python 2.7
tagged with: argparse
has title: Error to use date as argument and defaults in positional argument
tagged with: python
score: 2
answer count: 0
downvote count: 0
type: UnansweredQuestion
type: Question
upvote count: 2
tagged with: python-2.7

http://stackoverflow.com/comment/91477490
type: AnswerComment
has text: Well then you should wrap it within `np.abs(..)`
type: Comment
comment on: http://stackoverflow.com/a/52264668
score: 0

http://stackoverflow.com/q/52131528
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52131623
type: Question
has comment: http://stackoverflow.com/comment/91213593
upvote count: 0
has comment: http://stackoverflow.com/comment/91213621
answer count: 1
has comment: http://stackoverflow.com/comment/91213774
has body: def multpoly(d1,d2): d3=[] d1=dict(d1) d2=dict(d2) for key,value in list(d1.items()): for key2,value2 in list(d2.items()): #print(key,value) print(key2,value2) print(key,value) d1={1:1,-1:0} d2={1:2,1:1,1:0} wrong output: 1 0 1 1 1 0 -1 0 Expected: 1 2 1,1 1,0 1,1 -1,0 I am getting wrong output with this code? Can anyone help me what is wrong with this code?
downvote count: 8
has comment: http://stackoverflow.com/comment/91213846
has answer: http://stackoverflow.com/a/52131623
favorite count: 0
has comment: http://stackoverflow.com/comment/91213724
score: -8
has title: How to iterate through two dictionary objects (both key,value) using two nested for loops in python?
tagged with: python

http://stackoverflow.com/comment/91446726
type: QuestionComment
comment on: http://stackoverflow.com/q/52249282
has text: Did you look at itertools.groupby?
score: 1
type: Comment

nexus
type: Tag
tags question: http://stackoverflow.com/q/52157974
tag name: nexus

http://stackoverflow.com/comment/91313030
has text: What you ask is unclear. The assertion you made for the approaches is, at best, partial & incomplete (source?); agent-based modelling is a whole scientific topic in itself (see tag description for starters)...
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52181092

http://stackoverflow.com/comment/91425683
score: 0
type: Comment
type: QuestionComment
has text: That's an interesting question. I'll try to answer by Monday;)
comment on: http://stackoverflow.com/q/52183538

http://stackoverflow.com/a/52296866
type: Answer
has body: Here is your code with some modifications. We apply a Fourier transform, phase shift the transformed signal, and then perform the inverse Fourier transform to produce the phase shifted time domain signal. Notice that the transforms are done with rfft() and irfft(), and that the phase shift is done by simply multiplying the transformed data by cmath.rect(1.,phase). The phase shift is equivalent to multiplying the complex transformed signal by exp( i * phase ). In the graphics, in the left panel, we show the original and shifted signals. The new signal is advanced by 90 degrees. In the right panel we show the power spectrum on the left axis. In this example we have power at a single frequency. Phase is graphed on the right axis. But again, since we have power at only one frequency, the phase spectrum shows noise everywhere else. #!/usr/bin/python import matplotlib.pyplot as plt import numpy as np import cmath # Generate a model signal t0 = 1250.0 dt = 0.152 freq = (1./dt)/128 t = np.linspace( t0, t0+1024*dt, 1024, endpoint=False ) signal = np.sin( t*(2*np.pi)*freq ) ## Fourier transform of real valued signal signalFFT = np.fft.rfft(signal) ## Get Power Spectral Density signalPSD = np.abs(signalFFT) ** 2 signalPSD /= len(signalFFT)**2 ## Get Phase signalPhase = np.angle(signalFFT) ## Phase Shift the signal +90 degrees newSignalFFT = signalFFT * cmath.rect( 1., np.pi/2 ) ## Reverse Fourier transform newSignal = np.fft.irfft(newSignalFFT) ## Uncomment this line to restore the original baseline # newSignal += signalFFT[0].real/len(signal) # And now, the graphics ------------------- ## Get frequencies corresponding to signal fftFreq = np.fft.rfftfreq(len(signal), dt) plt.figure( figsize=(10, 4) ) ax1 = plt.subplot( 1, 2, 1 ) ax1.plot( t, signal, label='signal') ax1.plot( t, newSignal, label='new signal') ax1.set_ylabel( 'Signal' ) ax1.set_xlabel( 'time' ) ax1.legend() ax2 = plt.subplot( 1, 2, 2 ) ax2.plot( fftFreq, signalPSD ) ax2.set_ylabel( 'Power' ) ax2.set_xlabel( 'fre…
accepted answer of: http://stackoverflow.com/q/52179919
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/52179919
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52174031
type: Question
answer count: 2
downvote count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/52174524
tagged with: pandas-groupby
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52174078
favorite count: 0
has title: How to merge or remap columns with the same name?
has answer: http://stackoverflow.com/a/52174524
tagged with: python
type: AnsweredQuestion
score: 2
has body: I would like to merge two columns if they have the same column name. I would like the value of the duplicate column to replace the NaN value. My dataframe looks like this: PETS PETS FRUITS COUNTRY FRUITS Pig NaN Apple USA NaN Cat NaN NaN NL Banana NaN Dog NaN NaN NaN This is what I would my datafame to look like: PETS FRUITS COUNTRY Pig Apple USA Cat Banana NL Dog NaN NaN
has answer: http://stackoverflow.com/a/52174078
tagged with: dataframe

http://stackoverflow.com/q/52193726
accepted answer: http://stackoverflow.com/a/52193746
score: 0
has body: I have two models, Author and Book. I need to get all Authors who have no Books with Django's ORM. How can I do that? Here are my models: class Author(models.Model): name = models.CharField(max_length=30) age = models.IntegerField() class Book(models.Model): name = models.CharField(max_length=500) author = models.ForeignKey(Author, related_name='books') I am currently doing it with for loop, but I would prefer to do it with the ORM: for person in Author.objects.all(): if person.books.count() == 0: "something code" But it need to make update for objects. I tried this but I just get an empty QuerySet: Author.objects.select_related('books').values('id').annotate(books_count=Count('id')).filter(books_count=0)
has title: Look up objects that aren't the target of any foreign keys using Django ORM
answer count: 1
has answer: http://stackoverflow.com/a/52193746
tagged with: django
tagged with: python
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/91238126
type: Comment
comment on: http://stackoverflow.com/q/52143917
score: 0
type: QuestionComment
has text: Maybe post here if just want to improve the code? https://codereview.stackexchange.com/

http://stackoverflow.com/q/52202014
tagged with: data-visualization
tagged with: python
has answer: http://stackoverflow.com/a/66204903
answer count: 4
score: 8
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91360169
linked to: http://stackoverflow.com/q/49640311
has answer: http://stackoverflow.com/a/59971611
type: Question
has answer: http://stackoverflow.com/a/52206017
tagged with: mesh
has comment: http://stackoverflow.com/comment/91358066
accepted answer: http://stackoverflow.com/a/52206017
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91358422
has body: I'm developing a 2D plane finite element tool. One of the features is the ability to visualize the stresses on a particular object. This tool creates a quadrilateral mesh using the following data: nodes: numpy array [[x1 y1], [x2 y2], etc] -> x and y coordinates of every node in the mesh elements: numpy array [[1 2 3 4], [2 3 5 6]] -> every line of the array corresponds to the 4 points of one particular element of the mesh. I was able to implement a method that plots the mesh: import matplotlib.pyplot as plt import matplotlib.collections import matplotlib.cm as cm import numpy as np def showMeshPlot(nodes, elements): y = nodes[:,0] z = nodes[:,1] #https://stackoverflow.com/questions/49640311/matplotlib-unstructered-quadrilaterals-instead-of-triangles def quatplot(y,z, quatrangles, ax=None, **kwargs): if not ax: ax=plt.gca() yz = np.c_[y,z] verts= yz[quatrangles] pc = matplotlib.collections.PolyCollection(verts, **kwargs) ax.add_collection(pc) ax.autoscale() plt.figure() plt.gca().set_aspect('equal') quatplot(y,z, np.asarray(elements), ax=None, color="crimson", facecolor="None") if nodes: plt.plot(y,z, marker="o", ls="", color="crimson") plt.title('This is the plot for: quad') plt.xlabel('Y Axis') plt.ylabel('Z Axis') plt.show() nodes = np.array([[0,0], [0,0.5],[0,1],[0.5,0], [0.5,0.5], [0.5,1], [1,0], [1,0.5],[1,1]]) elements = np.array([[0,3,4,1],[1,4,5,2],[3,6,7,4],[4,7,8,5]]) stresses = np.array([1,2,3,4]) showMeshPlot(nodes, elements) Which produces a plot like this: Now, i have an 1D array with the stresses on the object, with the same length as the elements array. My question is how can i visualize those stresses (with a scalar bar) using matplotlib? I looked into pcolormesh, but i couldn't understand how it could work with my data. Here's an example of what i want to achieve (credits to robbievanleeuwen): Note: I couldn't replicate the above example because he uses a triangular mesh instead of quads. Thanks in advance!
has comment: http://stackoverflow.com/comment/91356888
possible better answer: http://stackoverflow.com/a/59971611
has answer: http://stackoverflow.com/a/52203447
has title: How can I plot 2d FEM results using matplotlib?
downvote count: 0
favorite count: 0
upvote count: 8

http://stackoverflow.com/a/52150215
upvote count: 1
has body: I found a workaround! Strangely the metagraph does not contain all the variables that I defined or assigns to them new names. For examples in the constructor I define the tensors that will carry the input feature vectors and the experimental values: self.x = tf.placeholder("float", [None, feat_num], name='x') self.y = tf.placeholder("float", [None], name='y') However, when I do tf.reset_default_graph() and load the metagraph, I get the following list of variables: [ &lt;tf.Variable 'Variable:0' shape=(300, 300) dtype=float32_ref&gt;, &lt;tf.Variable 'Variable_1:0' shape=(300,) dtype=float32_ref&gt;, &lt;tf.Variable 'Variable_2:0' shape=(300, 1) dtype=float32_ref&gt;, &lt;tf.Variable 'Variable_3:0' shape=(1,) dtype=float32_ref&gt; ] For the record, each input feature vector has 300 features. Anyway, when I later try to initiate training using: _, c, p = self.sess.run([self.optimizer, self.cost, self.pred], feed_dict={self.x: batch_x, self.y: batch_y, self.isTrain: True}) I get an error like: "TypeError: Cannot interpret feed_dict key as Tensor: Tensor 'x' is not an element of this graph." So, since every time I create an instance of class TF_MLPRegressor(), I define the network architecture within the constructor, I decided not to load the metagraph and it worked! I don't know why TF doesn't save all variables into the metagraph, maybe because I define explicitly the network architecture (I don't use wrappers or default layers) like in the example below: https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/4_Utils/save_restore_model.py To sum up, I save my models as described in my 1st message but to restore them I use this: saver = tf.train.Saver(max_to_keep=2) self.sess = tf.Session(config=self.config) # create a new session to load saved variables self.sess.run(tf.global_variables_initializer()) ckpt = tf.train.latest_checkpoint(self.checkpoint_dir) saver.restore(sess=self.sess, save_path=ckpt) # Restore model weights from previously saved mod…
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52136663
type: Answer

http://stackoverflow.com/q/52241961
type: Question
score: -1
has title: How can I use Python to automate an external .exe which takes multiple user inputs interactively on the Windows command line?
answer count: 1
downvote count: 1
tagged with: cmd
linked to: http://stackoverflow.com/q/8475290
favorite count: 0
has comment: http://stackoverflow.com/comment/91446138
linked to: http://stackoverflow.com/q/21522267
tagged with: stdin
type: UnansweredQuestion
has body: I have an executable that I can run interactively from the windows command line. The workflow is as follows: C:\Users\Me&gt; my_executable.exe # Running the executable from CMD Welcome! Please choose one: 0: Exit 1: Sub-task 1 2: Sub-task 2 Enter your input: 2 # I entered this interactively Sub-task 2 chosen. Please choose next option: 0: Return to previous menu 1: Connect to server 2: Disconnect from server 3: Call server API 1 4: Call server API 2 Enter your input: 1 # I entered this interactively The full workflow is complex and takes multiple passes (once through sub-task 1, then through sub-task 2 etc). I would like to automate this using Python. I have been trying to use the subprocess module to achieve this. However, I seem to fail at the .Popen stage itself. Here is a similar question on StackOverflow. I tried using the same approach using .Popen. This is what I see: C:\Users\Me&gt; python Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from subprocess import Popen, PIPE &gt;&gt;&gt; p = Popen('my-executable.exe', stdin=PIPE) Traceback (most recent call last): file "&lt;stdin&gt;", line 1 in &lt;module&gt; TypeError: unsupported operand type(s) for -:'Popen' and 'Popen' &gt;&gt;&gt; Welcome! Please choose one: 0: Exit 1: Sub-task 1 2: Sub-task 2 Enter your input: 2 # I am forced to enter this input here. 2 # Python echoes 2 before returning to prompt &gt;&gt;&gt; # Back to Python prompt Can someone help with what I am doing wrong?
tagged with: python
upvote count: 0
has answer: http://stackoverflow.com/a/52242187
tagged with: subprocess

http://stackoverflow.com/comment/91411700
type: Comment
type: QuestionComment
has text: But I can get a prediction with clf.predict(datatest). So how come it can make a prediction, but can't give me scores or probabilities? Is there nothing equivalent to a decision function?
comment on: http://stackoverflow.com/q/52124261
score: 0

http://stackoverflow.com/a/52114900
has body: You can use else. try: function a() except someError: function b() else: resume_code
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52114719
type: Answer
has comment: http://stackoverflow.com/comment/91180309
score: 2
has comment: http://stackoverflow.com/comment/91549538

http://stackoverflow.com/comment/91529653
has text: yes missed to rename the column (Subscriber=LTE_Subs)
score: 0
comment on: http://stackoverflow.com/q/52258075
type: QuestionComment
type: Comment

http://stackoverflow.com/a/59225686
upvote count: 2
answers question: http://stackoverflow.com/q/52259623
has body: Install Python3 via https://www.python.org/downloads/release/python-357/ Install PyQt5 and lxml via PIP using below command pip3 install pyqt5 lxml **Download, unzip and run the LabelImg.exe file via** https://www.dropbox.com/s/kqoxr10l3rkstqd/windows_v1.8.0.zip?dl=1
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/a/52261194
has comment: http://stackoverflow.com/comment/91477123
has comment: http://stackoverflow.com/comment/91472729
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52228582
has comment: http://stackoverflow.com/comment/91478171
has comment: http://stackoverflow.com/comment/91472370
type: Answer
accepted answer of: http://stackoverflow.com/q/52228582
downvote count: 0
has comment: http://stackoverflow.com/comment/91470190
score: 1
has body: Try this for your last loop and let me know how it turns out, some modifications may need to be made since I can't see your data. It appears you want to run the for loop on the lists together, so try this: for i, filename in zip(selectedRange, os.listdir(folderSource)): file_name = str(i[1]) + " " + i[2] + ".jpg" filename = os.path.join(folderSource, filename) file_name = os.path.join(folderDestination, file_name) shutil.copy(filename, file_name) print(done) go = renameFiles() For nested for loop structures, consider the following: loop1 = ['a','b','c','d','e'] loop2 = ['f','g','h','i','j'] for i in loop1: # iterates through a,b,c,d,e print(i) #prints a,b,c,d,e for j in loop2: # compares all j objects of loop2 to i in loop 1: ij = i + j print(ij) # this will add all j's to each i snippet output will add all j's to each iteration of i, before moving to the next iteration of i: 'af','ag','ah','ai','aj','bf','bg','bh','bi',bj'... etc zipping 2 lists together, (which is what I did in the answer) compares each element in loop1 to loop2 at the same index in both lists: for i,j in zip(loop1,loop2): ij = i + j print(ij) output: 'af','bg','ch','di','ej' The only thing you need to consider when you use the zip function for 2 lists, is that the iteration will only occur until the end of the shortest list. So if loop1 and loop2 were not equal lengths, then i+j would stop after the shorter list was complete. I hope this clarifies some of what I have done.
has comment: http://stackoverflow.com/comment/91478166

http://stackoverflow.com/comment/91517365
type: Comment
has text: Okay, so first things first, if you read stderr after the sub-process closes does it contain anything?
comment on: http://stackoverflow.com/a/52266953
type: AnswerComment
score: 0

http://stackoverflow.com/q/52262351
downvote count: 0
has body: I want to run a set of docker commands from python. I tried creating a script like below and run the script from python using paramiko ssh_client to connect to the machine where the docker is running: #!/bin/bash # Get container ID container_id="$(docker ps | grep hello | awk '{print $1}')" docker exec -it $container_id sh -c "cd /var/opt/bin/ &amp;&amp; echo $1 &amp;&amp; echo $PWD &amp;&amp; ./test.sh -q $1" But docker exec ... never gets executed. So I tried to run the below python script below, directly in the machine where the docker is running: import subprocess docker_run = "docker exec 7f34a9c1b78f /bin/bash -c \"cd /var/opt/bin/ &amp;&amp; ls -a\"".split() subprocess.call(docker_run, shell=True) I get a message: "Usage: docker COMMAND..." But I get the expected results if I run the command docker exec 7f34a9c1b78f /bin/bash -c "cd /var/opt/bin/ &amp;&amp; ls -a" directly in the machine How to run multiple docker commands from the python script? Thanks!
possible better answer: http://stackoverflow.com/a/52263631
favorite count: 0
has comment: http://stackoverflow.com/comment/91472499
has answer: http://stackoverflow.com/a/52263631
tagged with: python
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/52262542
has title: How to run the docker commands from python?
type: Question
has comment: http://stackoverflow.com/comment/91472732
score: 3
has comment: http://stackoverflow.com/comment/91472423
has comment: http://stackoverflow.com/comment/91472566
tagged with: docker
accepted answer: http://stackoverflow.com/a/52262542
answer count: 2

http://stackoverflow.com/comment/91487997
type: Comment
type: QuestionComment
has text: Probably it would be good if you posted a separate question regarding this error with a minimal reproducible code as now it is hard to diagnose.
comment on: http://stackoverflow.com/q/52241423
score: 0

http://stackoverflow.com/comment/91420187
type: QuestionComment
comment on: http://stackoverflow.com/q/52235383
has text: I have only started learning python hence I may not be able to fully understand what exactly is needed.
score: 0
type: Comment

http://stackoverflow.com/comment/91585955
score: 0
has text: @fafl I did not understand why did you refer to a bat file. My python file runs from Python-spyder, from shell and from cmd of Anaconda and Windows both. but not by using Process.start
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52263674

http://stackoverflow.com/a/52121850
answers question: http://stackoverflow.com/q/52121635
type: Answer
has comment: http://stackoverflow.com/comment/91195257
has comment: http://stackoverflow.com/comment/91201371
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91195217
has body: I think this might work: roll the axes into the correct orientation, find the index of the value of the (absolute) minimum for each of the 5x5 X,Y values and take the corresponding Z-values from arr_vals: idx = np.argmin(np.abs(np.rollaxis(arr_keys,0,3) - arr_idx[:,:,None]), axis=2) i,j = np.ogrid[:5,:5] arr_vals[idx[i,j],i,j] To test this, try the (3,2,2) case: In [15]: arr_keys Out[15]: array([[[ 0.19681533, 0.26897784], [ 0.60469711, 0.09273087]], [[ 0.04961604, 0.3460404 ], [ 0.88406912, 0.41284309]], [[ 0.46298201, 0.33809574], [ 0.99604152, 0.4836324 ]]]) In [16]: arr_vals Out[16]: array([[[ 0.88865681, 0.88287688], [ 0.3128103 , 0.24188022]], [[ 0.23947227, 0.57913325], [ 0.85768064, 0.91701097]], [[ 0.78105669, 0.84144339], [ 0.81071981, 0.69217687]]]) In [17]: arr_idx Out[17]: array([[[ 0.31352609], [ 0.75462329]], [[ 0.44445286], [ 0.97086161]]]) gives: array([[ 0.88865681, 0.57913325], [ 0.3128103 , 0.69217687]])
has comment: http://stackoverflow.com/comment/91195368
has comment: http://stackoverflow.com/comment/91195284
downvote count: 0
has comment: http://stackoverflow.com/comment/91195118

http://stackoverflow.com/a/54692723
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: I just run into the same problem. After searching through the "YouTube Data Api v3" documentation I found this: If you are using the installed app flow, authorization credentials are not stored in this sample code, so subsequent executions will prompt for reauthorization. So I guess you should instead use the "Web Server App" flow. There's no way around this.
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52167804
answers question: http://stackoverflow.com/q/52167804

http://stackoverflow.com/comment/91218868
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52134169
has text: Please post a [mcve] example of your attempt and say specifically where you're stuck

http://stackoverflow.com/comment/91226787
type: AnswerComment
has text: @Zastai. Thanks.. Corrected my answer
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52136699

http://stackoverflow.com/q/52209977
score: 7
has comment: http://stackoverflow.com/comment/91369443
tagged with: numpy
has answer: http://stackoverflow.com/a/52210580
answer count: 3
downvote count: 0
has title: Insert element into numpy array and get all rolled permutations
favorite count: 0
possible better answer: http://stackoverflow.com/a/52210580
has comment: http://stackoverflow.com/comment/91369846
linked to: http://stackoverflow.com/q/51887316
tagged with: matrix
has answer: http://stackoverflow.com/a/52210086
tagged with: python
has comment: http://stackoverflow.com/comment/91369544
has comment: http://stackoverflow.com/comment/91369456
has comment: http://stackoverflow.com/comment/91369467
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91369990
has answer: http://stackoverflow.com/a/52210116
upvote count: 7
type: Question
has body: Is there a better way to insert, one by one, elements in an array to all posible positions (n+1 positions). E.g inserting [1] to [6 7 8 9] should produce: [1 6 7 8 9] [9 1 6 7 8] [8 9 1 6 7] [7 8 9 1 6] [6 7 8 9 1] So if I insert A = [1 2 3] one by one to B = [6 7 8 9] it should produce: [1 6 7 8 9] [9 1 6 7 8] [8 9 1 6 7] [7 8 9 1 6] [6 7 8 9 1] -------------------- [2 6 7 8 9] [9 2 6 7 8] [8 9 2 6 7] [7 8 9 2 6] [6 7 8 9 2] -------------------- [3 6 7 8 9] [9 3 6 7 8] [8 9 3 6 7] [7 8 9 3 6] [6 7 8 9 3] -------------------- Currently I use numpy.roll like this: import numpy as np import timeit A = np.array([1, 2, 3, 4, 5]) B = np.array([6, 7, 8, 9]) def inject_one(Ad, Bd): for i, _ in enumerate(Ad): C = np.append(Ad[i], Bd) for _ in range(len(C) - 1): C = np.roll(C, 1) t = timeit.Timer(lambda: inject_one(A, B)) print("{:.3f}secs for 1000 iterations".format(t.timeit(number=1000))) # &gt; 0.160 secs
accepted answer: http://stackoverflow.com/a/52210116
tagged with: algorithm

http://stackoverflow.com/comment/91401947
comment on: http://stackoverflow.com/a/52226177
score: 0
type: AnswerComment
has text: @jonrsharpe: I suppose there is no iteration. Seriously, I'm not sure how repr is generated. Could you shed some light on it?
type: Comment

http://stackoverflow.com/comment/136793977
score: 0
type: AnswerComment
type: Comment
has text: ensure that your bot also has the "Attach Files" permission
comment on: http://stackoverflow.com/a/52241776

http://stackoverflow.com/q/52125183
accepted answer: http://stackoverflow.com/a/52130615
has body: I set up my Python dev environment on macOS using the following commands: brew install pyenv pyenv install 3.7.0 pyenv install 2.7.15 pyenv global 3.7.0 I also added the following to my .bash_profile: export PATH="/Users/me/.local/bin:$PATH" eval "$(pyenv init -)" Python seems to be working as expected: 01:29 $ python --version Python 3.7.0 I then installed pipenv the "pragmatic" way, since installing via Homebrew would install a whole copy of Python as well (which I didn't want, since I was using pyenv already): pip install --user pipenv Now when I try to start a new pipenv project I get the following message: 01:28 $ mkdir my-new-project &amp;&amp; cd my-new-project &amp;&amp; pipenv install Warning: Python 3.6 was not found on your system... Would you like us to install CPython 3.6.6 with pyenv? [Y/n]: I thought pipenv automatically used whatever pyenv copy of Python was available -- which is 3.7.0 in my case. Where is the prompt about installing CPython 3.6.6 coming from?
type: Question
tagged with: pipenv
has comment: http://stackoverflow.com/comment/91201544
has title: pipenv insists on installing Python 3.6
has answer: http://stackoverflow.com/a/52130615
answer count: 1
has comment: http://stackoverflow.com/comment/91209697
score: 0
tagged with: pyenv
tagged with: python
has comment: http://stackoverflow.com/comment/91212219
type: AnsweredQuestion

http://stackoverflow.com/comment/91266323
score: 1
comment on: http://stackoverflow.com/q/52157214
type: Comment
type: QuestionComment
has text: That's not right. The actual backend folder has to be listed for the subfolders to be picked up as modules.

http://stackoverflow.com/a/52197587
has comment: http://stackoverflow.com/comment/91420039
answers question: http://stackoverflow.com/q/52197428
has comment: http://stackoverflow.com/comment/91421077
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52197428
type: AcceptedAnswer
has body: One approach would be to use numba cuda atomics: $ cat t18.py import numpy as np from numba import cuda @cuda.jit('void(int32[:])') def func(counter): cuda.atomic.add(counter, 0, 1) counter = cuda.to_device(np.zeros(1, dtype=np.int32)) threadsperblock = 64 blockspergrid = 18 print blockspergrid * threadsperblock func[blockspergrid, threadsperblock](counter) print(counter.copy_to_host()) $ python t18.py 1152 [1152] $ An atomic operation performs an indivisible read-modify-write operation on the target, so threads do not interfere with each other when they update the target variable. Certainly other methods are possible, depending on your actual needs, such as a classical parallel reduction. numba provides some reduction sugar also.
has comment: http://stackoverflow.com/comment/91421004
type: Answer
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/91420904

http://stackoverflow.com/q/52160127
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/52172377
has answer: http://stackoverflow.com/a/52172377
has answer: http://stackoverflow.com/a/52164540
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91270002
score: 1
tagged with: memory
type: Question
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/52164540
favorite count: 0
has comment: http://stackoverflow.com/comment/91270182
has comment: http://stackoverflow.com/comment/91270294
has body: I'm not sure if this is a duplicate of the other PyPy memory questions, but here I'll provide a concrete example. from __future__ import division def mul_inv(a, m): """Modular multiplicative inverse, a^-1 mod m. Credit: rosettacode.org""" m0 = m x0, x1 = 0, 1 if m == 1: return 1 while a &gt; 1: assert m != 0, "a and m must be coprime" q = a // m a, m = m, a%m x0, x1 = x1 - q * x0, x0 if x1 &lt; 0: x1 += m0 return x1 M = 1000000009 L = 10**8 bin2 = [0] * L bin2[0] = 1 for n in range(L-1): bin2[n+1] = (bin2[n] * (4*n + 2) * mul_inv(n+1, M)) % M if n % 10**5 == 0: print(n, bin2[n]) print(bin2[:20]) With python 3.6, the program uses 3-4 GB at most and runs to completion (Armin Rigo's list change doesn't change this significantly). With python 2.7.13 running PyPy 5.10.0, the program reaches 8 GB (how much RAM I have) quickly and freezes. Even with gc.collect() calls the program runs out of memory when n is about 3.5 * 10^7. Where is this memory usage coming from? The only large memory usage should be initializing bin2 as a 10^8 int list. Nothing else should be increasing the memory usage, under the assumption that all the local variables in mul_inv are garbage collected.
tagged with: pypy
has title: Pypy memory usage increases when nothing new is allocated
has comment: http://stackoverflow.com/comment/91308975
tagged with: out-of-memory

http://stackoverflow.com/comment/91509127
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52251394
has text: Interesting! I will try this when I get home.
type: AnswerComment

http://stackoverflow.com/q/52153548
score: 0
has title: External database lookup in TF serving or part of the TF graph
answer count: 1
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52182820
has body: I have an tensorflow model that I'm planning to deploy using tensorflow serving for model inference. Just wondering if there is a way to add some custom logic after the service receives the request and before it goes to the tensorflow model. Specifically, I need a lookup step from an external database, that would enrich the data the application receives through the REST call. Alternatively, is that possible as part of the tensorflow graph? It sounds like an overkill to create a separate service just for that, if it can be bundled in the serving layer.
tagged with: tensorflow
type: Question
tagged with: tensorflow-serving

http://stackoverflow.com/comment/91298280
type: QuestionComment
has text: Already tried a simpler Python script like something as `with open("out.txt", "w") as f; f.write("Test")`?
comment on: http://stackoverflow.com/q/52173535
score: 1
type: Comment

http://stackoverflow.com/q/52217113
tagged with: python
has comment: http://stackoverflow.com/comment/91382924
answer count: 0
type: Question
tagged with: theano-cuda
tagged with: compilation
has body: I am trying to execute this Github repository. When I run the build.sh file, I get the following error: gcc version is :gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) nvidia-smi:NVIDIA-SMI 340.24 Driver Version: 340.24 Nvidia geforce 820 with computability is 2.1. rc/weight_acts.cu(1289): error: type name is not allowed src/weight_acts.cu(1290): error: type name is not allowed src/weight_acts.cu(1291): error: type name is not allowed src/weight_acts.cu(1292): error: type name is not allowed src/weight_acts.cu(1293): error: type name is not allowed src/weight_acts.cu(1294): error: type name is not allowed src/weight_acts.cu(1325): error: type name is not allowed src/weight_acts.cu(1325): warning: expression has no effect src/weight_acts.cu(1213): warning: expression has no effect detected during instantiation of "void conv_weight_acts_c_preload_pc_2_pt_4_f_3_r_32_c_3&lt;B_Y,B_X,pixelCache,pixelsPerThread,filtersPerThread,preloadCases,numColors,scale,checkCaseBounds&gt;(cudaTextureObject_t, cudaTextureObject_t, float *, int, int, int, int, int, int, int, int, int, int, int, float, float) [with B_Y=16, B_X=16, pixelCache=2, pixelsPerThread=4, filtersPerThread=3, preloadCases=32, numColors=3, scale=false, checkCaseBounds=false]" (2214): here src/weight_acts.cu(1289): warning: expression has no effect detected during instantiation of "void conv_weight_acts_c_preload_pc_2_pt_4_f_3_r_32_c_3&lt;B_Y,B_X,pixelCache,pixelsPerThread,filtersPerThread,preloadCases,numColors,scale,checkCaseBounds&gt;(cudaTextureObject_t, cudaTextureObject_t, float *, int, int, int, int, int, int, int, int, int, int, int, float, float) [with B_Y=16, B_X=16, pixelCache=2, pixelsPerThread=4, filtersPerThread=3, preloadCases=32, numColors=3, scale=false, checkCaseBounds=false]" (2214): here src/weight_acts.cu(1290): warning: expression has no effect detected during instantiation of "void conv_weight_acts_c_preload_pc_2_pt_4_f_3_r_32_c_3&lt;B_Y,B_X,pixelCache,pixelsPerThread,filtersPerThread,preloadC…
has comment: http://stackoverflow.com/comment/91524089
score: 0
has title: build file compilation failed in cuda on ubuntu
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91383243
has comment: http://stackoverflow.com/comment/91383456

http://stackoverflow.com/comment/91243169
has text: @Bazingaa The OP has actually formatted it very carefully. I tried to, and rapidly rolled back!
score: 0
comment on: http://stackoverflow.com/q/52146661
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91588096
has text: Hi, I know but the "DSACLS" needs a windows server, i was trying to make it stateless because the rest could be done as a lambda so if there was a way to do it without that it would be helpful, but thanks for the answer, i really appreciate it.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52215808
type: QuestionComment

http://stackoverflow.com/q/52139568
has title: python web scraping - URL not matching Chrome Inspect results
has comment: http://stackoverflow.com/comment/91228849
score: 1
has comment: http://stackoverflow.com/comment/91229044
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91231621
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52139919
tagged with: python
has answer: http://stackoverflow.com/a/52139887
has comment: http://stackoverflow.com/comment/91228871
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91228947
tagged with: web-scraping
upvote count: 1
has body: I am trying to retrieve some data from the below links, but my requests lead to different results when I change the URL, by retrieving the URL after clicking on the next page button on the bottom of the website (https://www.carmax.com/cars?location=all). Code that works for the initial URL import requests from bs4 import BeautifulSoup car_url = "https://www.carmax.com/cars?location=all" headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'} r = requests.get(car_url, headers = headers) html_doc = r.text soup = BeautifulSoup(html_doc, 'lxml') # Information that I am looking for info = soup.find_all('div', class_='vehicle-browse--result--info') When I run this same code using the next page of the website, there is no class of "class_='vehicle-browse--result--info'" in the response. Code with new URL from the next page url_test = 'https://www.carmax.com/search?location=all#BT=0&amp;Distance=all&amp;ExposedCategories=249+250+1001+1000+265+999+772&amp;ExposedDimensions=249+250+1001+1000+265+999+772&amp;Page=4&amp;PerPage=20&amp;SortKey=0&amp;StartIndex=80&amp;Zip=20877' test_request = requests.get(url_test, headers = headers) html_doc_test = test_request.text soup_test = BeautifulSoup(html_doc_test, 'lxml') # This returns a blank object, not providing me the info I need info_test = soup_test.find_all('div', class_='vehicle-browse--result--info') The new URL (which is one of the next pages when you click the next arrow on the initial URL) does not have the same results. What can I do to receive the same response for the next page? For additional detail, when I click "Inspect" when using Google Chrome on the website, I do see the same type of information as the initial URL, but for some reason that does not translate to the code.

http://stackoverflow.com/comment/91404507
type: Comment
has text: @roganjosh, it is problematic. I have created multiple environments, but it appears that I need an environment with *both* easydict and python3.
comment on: http://stackoverflow.com/q/52227492
score: 0
type: QuestionComment

http://stackoverflow.com/a/52185733
accepted answer of: http://stackoverflow.com/q/52185696
answers question: http://stackoverflow.com/q/52185696
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
has body: You should take a look at the requests library. It contains all of the info you need for authentication as well as making POST and GET requests, provided you have the documentation for the API you want to use

http://stackoverflow.com/comment/91225723
has text: I am not sure. It appears that you are looping same. Can you update your script, so I can see what’s going on?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52132145
type: Comment

http://stackoverflow.com/q/52233683
linked to: http://stackoverflow.com/q/522563
has answer: http://stackoverflow.com/a/52233730
upvote count: 2
answer count: 3
favorite count: 0
tagged with: python-3.x
tagged with: python
duplicate of: http://stackoverflow.com/q/522563
possible better answer: http://stackoverflow.com/a/52233730
has comment: http://stackoverflow.com/comment/91416339
score: 2
has answer: http://stackoverflow.com/a/52233735
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52233735
has answer: http://stackoverflow.com/a/52233733
downvote count: 0
has body: I do understand how to achieve putting letters in a list separated by commas: e.g. a = 'hello' print(list(a)) How can I achieve such an output below? ['h':0, 'e':1, 'l':2, 'l':3, 'o':4]
has title: Printing a python list with the index and items together
type: Question

http://stackoverflow.com/comment/91273308
score: 1
comment on: http://stackoverflow.com/q/52161886
type: Comment
type: QuestionComment
has text: `\xc5\x8d` is a `ō` character, not `ū`. Can you post a [mcve]?

http://stackoverflow.com/comment/91372029
has text: Do a little more research on the sheets data why this is happening. You can go through https://www.quora.com/Can-I-save-multiple-Excel-sheets-by-using-Python-Pandas-to-CSV?share=c033ca22&srid=uyDvF . Go through more sites
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52190910

http://stackoverflow.com/a/52175689
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52170419
type: Answer
has comment: http://stackoverflow.com/comment/91327570
has comment: http://stackoverflow.com/comment/91322943
has comment: http://stackoverflow.com/comment/91327201
has body: The script you wrote is creating a reference cycle in a less than obvious fashion. The non-obvious cycle is a result of all class declarations being inherently cyclic, so the simple existence of a class declaration in W means there will be some cyclic garbage. I'm not sure if this is a necessary condition of all Python interpreters, but it's definitely true of CPython's implementation (from at least 2.7 through 3.6, the interpreters I've checked). The thing that loops in your Z instance and triggers the behavior you observe is that you use v (which is a reference to a Z instance) with closure scope when you declare Form.x as part of the class declaration. The closure scope means that as long as the class Form defined by the call to W exists, the closed upon variable, v (ultimately an instance of Z) will remain alive. When you run a module with IDLE, it runs the module and dumps you to an interactive prompt after the code from the module has been executed, but Python is still running, so it doesn't perform any cleanup of the globals or run the cyclic GC immediately. The instance of Z will eventually be cleaned (at least on CPython 3.4+), but cyclic GC is normally run only after quite a number of allocations without matching deallocations (700 by default on my interpreters, though this is an implementation detail). But that collection may take an arbitrarily long time (there is a final cycle cleanup performed before the interpreter exits, but beyond that, there are no guarantees). By commenting out the line referencing v, you're no longer closing on v, so the cyclic class is no longer keeping v alive, and v is cleaned up promptly (on CPython's reference counted interpreter anyway; no guarantees on Jython, PyPy, IronPython, etc.) when the last reference disappears. If you want to force the cleanup, after running the module, you can run the following in the resulting interactive shell to force a generation 0 cleanup: &gt;&gt;&gt; import gc &gt;&gt;&gt; gc.collect(0) # O…
downvote count: 0
has comment: http://stackoverflow.com/comment/91327436
score: 1
accepted answer of: http://stackoverflow.com/q/52170419
upvote count: 1

http://stackoverflow.com/q/52242296
accepted answer: http://stackoverflow.com/a/52245187
tagged with: python
tagged with: kivy
type: AnsweredQuestion
score: 0
type: Question
has body: Requirement My sqlite3 Db contains Blob and Text data, on deleting the selected row of data from the db the txt &amp; blob data is removed from the db. I'm trying to set the widget to None so that the CoreImage widget appears blank after the delete() is called. However, the residual image is still visible. How can I go about this? The code snippet is as follows. delete(self): try: conn.execute("DELETE FROM EMPDB WHERE EMPID=?", (no)) conn.commit() # NAME OF THE IMAGE WIDGET = ATTEMPTING TO SET IT TO EMPTY/NONE self.one_image.source = " " OR "None"
has answer: http://stackoverflow.com/a/52245187
has title: How to clear Kivy Core image on button press so that the widget is empty?
tagged with: sqlite
answer count: 1

http://stackoverflow.com/comment/91426796
type: QuestionComment
score: 0
has text: Not sure if this was a bug or not, but it seemed to be there when i ran python3 instead of python.
type: Comment
comment on: http://stackoverflow.com/q/52220609

http://stackoverflow.com/q/52146321
accepted answer: http://stackoverflow.com/a/52146668
tagged with: python
has answer: http://stackoverflow.com/a/52146447
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52146668
has comment: http://stackoverflow.com/comment/91242491
score: 1
has comment: http://stackoverflow.com/comment/91242558
type: Question
has comment: http://stackoverflow.com/comment/91242816
has comment: http://stackoverflow.com/comment/91242527
possible better answer: http://stackoverflow.com/a/52146447
has comment: http://stackoverflow.com/comment/91242809
has title: Change the type of an object in python?
answer count: 2
has body: I would like to assign a type to an object via a function, something like: def set_type(obj,dest_type): [change the object to the dest_type here] return obj I need to do this because I read parameters from a file as strings and they are afterwards interpreted as integers, floats and booleans. Sure, I could write something like if dest_type=='bool': bool(obj) but is there no better way to do this? like directly giving the type to the function? Thanks!
tagged with: casting
upvote count: 1
tagged with: types
downvote count: 0
has comment: http://stackoverflow.com/comment/91242311
has comment: http://stackoverflow.com/comment/91243017
favorite count: 0

series
tag name: series
tags question: http://stackoverflow.com/q/52191628
tags question: http://stackoverflow.com/q/52218277
type: Tag
tags question: http://stackoverflow.com/q/52269786
tags question: http://stackoverflow.com/q/52151867
tags question: http://stackoverflow.com/q/52189522
tags question: http://stackoverflow.com/q/52173161
tags question: http://stackoverflow.com/q/52225770
tags question: http://stackoverflow.com/q/52267157
tags question: http://stackoverflow.com/q/52140395
tags question: http://stackoverflow.com/q/52139506
tags question: http://stackoverflow.com/q/52164516
tags question: http://stackoverflow.com/q/52210379
tags question: http://stackoverflow.com/q/52270145
tags question: http://stackoverflow.com/q/52165430
tags question: http://stackoverflow.com/q/52255324

http://stackoverflow.com/comment/91388687
has text: The same applies to `add_subplot()` where you add a subplot each time. For ex: `ax = fig.add_subplot(111)` means just a single plot with grid 1x1. `ax = fig.add_subplot(121)` would mean 1st subplot in a 1x2 grid and `ax = fig.add_subplot(122)` would mean 2nd subplot in a 1x2 grid
type: AnswerComment
comment on: http://stackoverflow.com/a/52214971
type: Comment
score: 2

http://stackoverflow.com/a/52187259
accepted answer of: http://stackoverflow.com/q/52176106
answers question: http://stackoverflow.com/q/52176106
has comment: http://stackoverflow.com/comment/91373433
has body: Root Widget - Screen The following example illustrates using Screen widget as the root widget and combined with RecycleView widget. main.py from kivy.app import App from kivy.uix.recycleview.views import RecycleDataViewBehavior from kivy.uix.recyclegridlayout import RecycleGridLayout from kivy.uix.behaviors import FocusBehavior from kivy.uix.recycleview.layout import LayoutSelectionBehavior from kivy.uix.button import Button from kivy.uix.screenmanager import Screen from kivy.lang import Builder Builder.load_string(''' #:kivy 1.11.0 &lt;Track&gt;: on_release: root.print_data(self.text) &lt;RootWidget&gt;: RecycleView: id: rv viewclass: 'Track' SelectableRecycleGridLayout: cols: 1 default_size: None, dp(56) default_size_hint: 1, None size_hint_y: None height: self.minimum_height orientation: 'vertical' multiselect: True touch_multiselect: True ''') class Track(RecycleDataViewBehavior, Button): def print_data(self, text): print("\nprint_data: text=", text) class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior, RecycleGridLayout): ''' Adds selection and focus behaviour to the view. ''' class RootWidget(Screen): def __init__(self, **kwargs): super(RootWidget, self).__init__(**kwargs) self.ids.rv.data = [{'text': str(x)} for x in range(100)] class TestApp(App): def build(self): return RootWidget() if __name__ == '__main__': TestApp().run() Root Widget - RecycleView There is no attribute, orientation: for GridLayout. Please remove it from your kv file. You need to implement the following: Snippet class Track(RecycleDataViewBehavior, Button): def print_data(self, text): print("\nprint_data: text=", text) class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior, RecycleGridLayout): ''' Adds selection and focus behaviour to the view. ''' Example main.py from kivy.app import App from kivy.uix.recycleview import RecycleView from kivy.uix.recycleview.views import RecycleDataViewBehavior from kivy.uix.recyclegridlayout import RecycleGridLayout …
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91340157
score: 0
type: Answer

http://stackoverflow.com/comment/91439843
has text: As a side note, you can use the `str.lower()` function simply as `input_text.lower()`.
comment on: http://stackoverflow.com/q/52245821
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91227384
type: Comment
type: QuestionComment
has text: try `ipython3`!
score: 0
comment on: http://stackoverflow.com/q/52138822

http://stackoverflow.com/comment/91229187
type: AnswerComment
has text: you awesome dude!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52139674

http://stackoverflow.com/a/52349163
has comment: http://stackoverflow.com/comment/91649353
has body: I was able to reproduce this locally with a mocked data source. Looks like you actually have to close the file to make sure it's flushed. f.close() # instead of f.close You are doing this in 2 places; note that f.close returns the function, but f.close() actually invokes it. One can reproduce the problem deterministically using def writeCSV(ID): f= open("%s.csv"%TableName,"a+") obj = BRANCH.query.order_by(BRANCH.ID).filter(BRANCH.ID==ID).first() string = '' # set body data for col in Columns: try: string = string + "," + getattr(obj,col).encode('utf-8') except Exception as e: print col string = string + "," + str(getattr(obj,col)) f.write(string[1:]+'\n') f.close() if ID == 0: # here we simulate what would happen if the GC decides # to release the first open handle at this point g.close() string = '' g= open("%s.csv"%TableName,"w+") # note the rename for demonstration purposes # set header for col_header in Columns: string = string + "," + col_header g.write(string[1:]+'\n') g.close branchObj = BRANCH.query.all() for item in branchObj: writeCSV(item.ID) Without calling close explicitly, you are leaving it up to the GC to decide when files should be closed, which can lead to bugs like this. See http://blog.lerner.co.il/dont-use-python-close-files-answer-depends/ Related note: consider opening the file once, and passing f into writeCSV to be used, instead of opening the file inside writeCSV. Furthermore, consider using the with syntax: with open("%s.csv"%TableName,"w+") as f: writeHeader(f) for item in branchObj: writeCSV(f, item.id) That way, you are guaranteed to be using one output stream in a serialized fashion, and with closes the file as soon as it exits.
has comment: http://stackoverflow.com/comment/91646163
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52260968
type: Answer
has comment: http://stackoverflow.com/comment/91646826
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/52260968

http://stackoverflow.com/q/52119513
tagged with: yacc
tagged with: lex
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
tagged with: parsing
has answer: http://stackoverflow.com/a/52119848
type: UnansweredQuestion
upvote count: 1
has body: So I've got a language that's a bytestring representing a list of the following header+data combos (e.g. headerdataheaderdataheaderdata...): Header 18 bytes that don't matter (Delimiter, ID, timestamp, type, etc) 4 bytes that specify the length of the data and header combined. Let's call this datalen 4 more bytes (checksum) Data datalen minus 26 bytes that can in fact contain the delimiter Tokens Just one token per byte value: b00 = r'\x00' ... bFF = r'\xFF' Grammar file -&gt; segments segments -&gt; segment segment | segment segment -&gt; delim id timestamp type group_id owner datalen checksum delim -&gt; bFF bAA id -&gt; int32 timestamp -&gt; int32 type -&gt; int32 group_id -&gt; int16 owner -&gt; int32 datalen -&gt; int32 checksum -&gt; int32 int32 -&gt; byte byte byte byte int16 -&gt; byte byte byte -&gt; &lt;oh my god one rule per value token&gt; The ploblem I know this isn't the typical context free language you'd normally work with in PLY. The length of each segment depends on a number contained within it. However it's easy to get that data as an embedded action in the 'segment' rule: def p_segment(t): ''' segment : delim id timestamp type group_id owner datalen checksum''' id = t[2] timestamp = t[3] type = t[4] group_id = t[5] owner = t[6] datalen = t[7] checksum = t[8] t[0] = (id,timestamp,type,group_id,owner,datalen,checksum) # Assume all rules for t[2:8] return the correct data type haha Now my thought was to just accumulate the extra bytes and store them somewhere with lexer.token(): def p_segment(t): ''' segment : delim id timestamp type group_id owner datalen checksum''' id = t[2] timestamp = t[3] type = t[4] group_id = t[5] owner = t[6] datalen = t[7] checksum = t[8] data = [] for i in range(datalen): data += t.lexer.token() t[0] = (id,timestamp,type,group_id,owner,datalen,checksum,data) This works to an extent--data does have the data in it, and t.lexer.lexpos is updated, however the parser loses its marbles with a syntax error right after the last b…
type: Question
tagged with: ply
score: 1
has title: Skipping a token-defined number of tokens in Python PLY

http://stackoverflow.com/q/52121682
has answer: http://stackoverflow.com/a/52121752
type: AnsweredQuestion
score: 1
favorite count: 0
type: Question
has title: Python 3 - removing elements from a list while iterating (sieve of Eratosthenes)
has answer: http://stackoverflow.com/a/52121963
upvote count: 1
tagged with: python
tagged with: primes
accepted answer: http://stackoverflow.com/a/52121752
answer count: 3
possible better answer: http://stackoverflow.com/a/52122120
has body: I am building a program to find all primes smaller than a number n using the algorithm of the sieve of Eratosthenes using python. The algorithm first creates a list of numbers from 2 to n, then iterates over the list removing the first element available and the corresponding multiples. The problem is that I don't seem to get the right result doing this way. I would also appreciate any suggestion to improve the performance. This is the algorithm: def primes(max): '''The sieve of Eratosthenes Algorithm to find all primes smaller than max''' init = time.clock() allNum = [a for a in range(2, max+1)] primes = [] for n in allNum: # remove all multiples of prime n toRemove = (a for a in range(n, max+1, n) if a in allNum) for i in toRemove: print('toRemove:', i) allNum.remove(i) # add the prime to the list primes.append(n) deltaT = time.clock() - init print('Time taken to process:', deltaT) return primes (SOLVED) This is how I changed it: while len(allNum) != 0: prime = allNum[0] # remove all multiples of prime toRemove = (a for a in range(prime, max+1, prime) if a in allNum) for i in toRemove: print('toRemove:', i) allNum.remove(i) # add the prime to the list primes.append(prime)
has answer: http://stackoverflow.com/a/52122120
has comment: http://stackoverflow.com/comment/91194668
downvote count: 0
linked to: http://stackoverflow.com/q/6260089

http://stackoverflow.com/comment/91206701
type: Comment
comment on: http://stackoverflow.com/a/52127949
type: AnswerComment
score: 0
has text: @shinobilou, ```q2.to_html(...)``` bit will give you simple html code. You can render it anywhere. I show you an example of rendering it on jupyter using ```HTML(string containing html_code)```, because I was coding the ans on jupyter.

http://stackoverflow.com/q/52149058
type: Question
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/52149099
answer count: 2
tagged with: pandas
downvote count: 0
tagged with: string
has title: Return keyword of string if found in dataframe columns
favorite count: 0
has body: I have a string. I need to find if the keywords in that string is present in my dataframe. If present, I need to return that keyword back. String: question="Joe is Available" question=question.upper() str_list=question.split() str_list Out[107]: ['JOE', 'IS', 'AVAILABLE'] Dataframe: df=pd.DataFrame({"Person1":("Ash","Joe","Harry"),"Person2":("Abe","Lisa","Katty",),"Person3":("Sam","Max","Stone")}) df=df.apply(lambda x: x.astype(str).str.upper()) Person1 Person2 Person3 ASH ABE SAM JOE LISA MAX HARRY KATTY STONE My Attempt: return_field="" for x in str_list: print(x) for i in df.iterrows(): if(df.str.contains(x)): return_field=x Gives me AttributeError: 'DataFrame' object has no attribute 'str' Expected Output Since Joe is present in the dataframe, it should return me back "Joe"
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/52149275
accepted answer: http://stackoverflow.com/a/52149275
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52149099
score: 1
upvote count: 1

http://stackoverflow.com/q/52152815
has title: Python: Add value to a list at predefined indexes
type: AnsweredQuestion
tagged with: list
score: 1
type: Question
upvote count: 2
has body: I have a list (aList) I need to create another list of the same length as aList (checkColumn) and add 1 at the positions defined in the index list (indexList), the positions not defined in the indexList should be 0 Input: aList = [70, 2, 4, 45, 7 , 55, 61, 45] indexList = [0, 5, 1] Desired Output: checkColumn = [1,1,0,0,0,1] I have been experimenting around with the following code, but I get the output as [1,1] for a in len(aList): if a == indexList[a]: checkColumn = checkColumn[:a] + [1] + checkColumn[a:] else: checkColumn = checkColumn[:a] + [0] + checkColumn[a:] I have tried with checkColumn.insert(a, 1) and I get the same result. Thanks for the help!
answer count: 2
has answer: http://stackoverflow.com/a/52153014
has comment: http://stackoverflow.com/comment/91256011
accepted answer: http://stackoverflow.com/a/52153014
has comment: http://stackoverflow.com/comment/91257162
possible better answer: http://stackoverflow.com/a/52152935
has answer: http://stackoverflow.com/a/52152935
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91257299
tagged with: python

http://stackoverflow.com/a/52659318
score: 1
has comment: http://stackoverflow.com/comment/137001831
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52246391
downvote count: 0
has body: Turned out that for my use case I can use Decimal instead of float, setting it from strings, and it does the right thing™: &gt;&gt;&gt; 'value={}'.format(Decimal('5')) 'value=5' &gt;&gt;&gt; 'value={}'.format(Decimal('5.5')) 'value=5.5'

http://stackoverflow.com/q/52157643
accepted answer: http://stackoverflow.com/a/52172959
upvote count: 1
type: Question
tagged with: if-statement
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52172959
score: 1
has comment: http://stackoverflow.com/comment/126165944
favorite count: 0
tagged with: python
has body: How do I make the if-ladder part below shorter? (The task is to find the smallest multiple that can be evenly divided by all numbers from 1-20. My code is inefficient, and, as I learned completely obsolete because you can do this problem with multiplying the primefactors. But anyway how to make this shorter?) a=20 b=0 while b&lt;1: if (a%20==0 and a%19==0 and a%18==0 and a%17==0 and a%16==0 and a%15==0 and a%14==0 and a%13==0 and a%12==0 and a%11==0 and a%10==0 and a%9==0 and a%8==0 and a%7==0 and a%6==0 and a%5==0 and a%4==0 and a%3==0 and a%2==0): b=1 else: a=a+1 print(a)
has title: Python how to shorten my code (not making it more effecient)
type: AnsweredQuestion

http://stackoverflow.com/q/52194407
tagged with: python
has title: Numpy array vectorized intersection
answer count: 0
upvote count: 1
tagged with: vectorization
type: Question
score: 1
tagged with: numpy
has comment: http://stackoverflow.com/comment/91339821
has body: I have a 3d numpy array that represents the user id obtained from my classifier with shape (NxKxM) and I would like to compute the jaccard index (len intersection /len union) in order to check the ratio of overlap during my groupkfold. I need to compute this function on the N (number of hyperparams) and M(number or iterations) axis, while K is the CV folds number. I would like to have something like: A[0][0][:] is compared with A[1:][:][:], A[0][1][:] is compared with A[1:][:][:] and A[0][2][:] is compared with A[1:][:][:] for the first level and so on iteratively. (in case of k=3) I have tried a nested for cycle but of course the code is extremely slow, so far I have this situation: for elem in range(len(total_users_splits)): for subelem in range(elem+1,len(total_users_splits)): for i in range(n_splits): for j in range(n_splits): first = b[elem][i] second = b[subelem][j] total_num = len(np.union1d(first,second)) intersect_len = len(np.intersect1d(first,second)) X.append(intersect_len/total_num) overlap = {'overlap_ratio_mean_uids':np.nanmean(X), 'overlap_ratio_std_uids':np.nanstd(X), 'overlap_ratio_max_uids':np.max(X), 'overlap_ratio_min_uids':np.min(X)} total_user_splits is a list of dimension NxM and n_splits is k. The code is really slow but I don't know how to apply np.intersect in a vectorized way
downvote count: 0
tagged with: scikit-learn
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91384721
comment on: http://stackoverflow.com/q/52217866
score: 0
type: Comment
type: QuestionComment
has text: most efficient solution for that is define heading by your self static. through out your scrapping for all the links the heading will be the same.

http://stackoverflow.com/q/52184713
score: -1
tagged with: python-2.7
answer count: 2
has comment: http://stackoverflow.com/comment/91319935
has answer: http://stackoverflow.com/a/52185123
upvote count: 0
has comment: http://stackoverflow.com/comment/91319707
has body: I'm porting odoo 11, python 2.7 to python 3. I have been edited an addon which has belongs to odoo, python code. The code is: vat = invoice.partner_id.vat or '' vat = list(filter(lambda x: x.isnumeric(), vat[:2])) + vat[2:] Error is: TypeError: can only concatenate list (not "str") to list How can I fix that, what is wrong with this code? Please help me.
favorite count: 0
has answer: http://stackoverflow.com/a/52185118
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52185123
has comment: http://stackoverflow.com/comment/91319293
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91320131
tagged with: odoo-11
accepted answer: http://stackoverflow.com/a/52185118
downvote count: 1
type: Question
tagged with: odoo
has comment: http://stackoverflow.com/comment/91319967
has title: Python3 TypeError: can only concatenate list (not "str") to list
has comment: http://stackoverflow.com/comment/91319435

http://stackoverflow.com/comment/91277500
has text: @gogaz Still not working. Replying `**bold**` now.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52163959

http://stackoverflow.com/comment/91266285
score: 0
type: Comment
type: QuestionComment
has text: Did I understand what you were trying to accomplish correctly?
comment on: http://stackoverflow.com/q/52157916

http://stackoverflow.com/comment/91339243
score: 0
type: AnswerComment
type: Comment
has text: It seems a little disingenuous to suggest that there's *no* relation between object attributes and dictionaries, considering that most objects store their attributes in a `__dict__` dict.
comment on: http://stackoverflow.com/a/52194780

http://stackoverflow.com/q/52230840
score: 1
type: Question
has comment: http://stackoverflow.com/comment/91471117
upvote count: 1
tagged with: window
has title: Record window audio with Python?
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: Is there any way to record the audio of a single window and not the whole system audio? I couldn't find any solution for this problem and am using "sounddevice" to record the system audio, but the window audio itself would be way better! It should work for Windows 10! Thanks in advance!
tagged with: audio
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/91411361

http://stackoverflow.com/comment/91430978
type: Comment
comment on: http://stackoverflow.com/a/52236595
has text: I tried access log, error log and debug log level, but there is no email log in them! Can you say what I need to add for logging django email console?
type: AnswerComment
score: 0

http://stackoverflow.com/a/52197321
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52181389
answers question: http://stackoverflow.com/q/52181389
score: 0
has body: I managed to solve this by making three changes. All code below has been changed to avoid copyright problems with my company, so sorry if I made a typo. First, I made a custom many-to-many model that allows for duplicate entries: class FooBar(models.Model): foo = models.ForeignKey( Foo, on_delete=models.SET_NULL, null=True) bar = models.ForeignKey( Bar, on_delete=models.SET_NULL, null=True) Then I added a through argument to my Foo class's ManyToMany field to use the new model: class Foo(models.Model): items = models.ManyToManyField(Foo, through='FooBar') However, just doing this causes an AttributeError: Cannot set values on a ManyToManyField which specifies an intermediary model. Use my_package.FooBar's Manager instead. This is because custom many-to-many models can't be automatically created by Django Rest Framework. So we need to implement a couple of custom serializer methods to get around that: def create(self, validated_data): instance = Foo() instance.x = validated_data['x'] instance.y = validated_data['y'] instance.save() for bar in validated_data['bars']: relation = FooBar(foo=instance, bar=bar) relation.save() return instance def update(self, instance, validated_data): instance.table = validated_data.get('x', instance.x) instance.status = validated_data.get('y', instance.y) instance.save() if 'bars' in validated_data: FooBar.objects.filter(foo=instance).delete() for bar in validated_data.get('bars', []): relation = FooBar(foo=instance, bar=bar) relation.save() return instance

http://stackoverflow.com/q/52141100
has answer: http://stackoverflow.com/a/52141133
tagged with: xlsxwriter
has body: I have 4 lists each having 33 values each and wish to print the combination in excel. Excel limits the number of rows in each sheet to 1,048,576 and the number of combinations exceeds the sheet limit by 137,345 values. How should I continue printing the result in next sheet in the same workbook? a = [100, 101, 102,...,133] b = [250, 251, 252,...,283] c = [300, 301, 302,...,333] d = [430, 431, 432,...,463] list_combined = [(p,q,r,s) for p in a for q in b for r in c for s in d] import xlsxwriter workbook = xlsxwriter.Workbook('combined.xlsx') worksheet = workbook.add_worksheet() for row, group in enumerate(list_combined): for col in range(5): worksheet.write (row, col, group[col]) workbook.close()
has comment: http://stackoverflow.com/comment/91232021
has comment: http://stackoverflow.com/comment/91258104
has answer: http://stackoverflow.com/a/52146432
type: Question
has title: Python: Print output on multiple Excel sheets
answer count: 2
has comment: http://stackoverflow.com/comment/91231932
has comment: http://stackoverflow.com/comment/91258075
score: 0
linked to: http://stackoverflow.com/q/37522394
has comment: http://stackoverflow.com/comment/91257850
has comment: http://stackoverflow.com/comment/91231982
has comment: http://stackoverflow.com/comment/91232034
has comment: http://stackoverflow.com/comment/91258094
type: UnansweredQuestion
tagged with: python
tagged with: excel

http://stackoverflow.com/q/52247146
has body: I've created a custom machine learning model using Watson Knowledge studio and deployed to an NLU service. I've also managed to access my model in python. My custom model has been designed to identify specific entity types such as (Advice, Cancellation, Awareness, and so on). What I want to do is to extract these entity types from the API JSON response and assign a number to them (e.g Advice = 1, Cancellation = 2, Awareness = 3, etc.) and then write them along with the sample text (e.g "I want to cancel my subscription with Gameloft.") to a CSV file with column headings (ID, Sentence, Entity Type). I have already managed to extract the entity types and the sample text and written them to a .txt file, however I need to write them to a CSV file. import json from watson_developer_cloud import NaturalLanguageUnderstandingV1 from watson_developer_cloud.natural_language_understanding_v1 \ import Features, EntitiesOptions, KeywordsOptions natural_language_understanding = NaturalLanguageUnderstandingV1( username='**************', password='*********', version='2018-03-16') text="I want to cancel my subscription with Gameloft." response = natural_language_understanding.analyze( text =text, features=Features( entities=EntitiesOptions( emotion=True, sentiment=True, limit=2, model="**************"), keywords=KeywordsOptions( emotion=True, sentiment=True, limit=2))) print(json.dumps(response, indent=2)) response['keywords'][0]['text'] response ['entities'][0]['type'] if response['entities'][0]['type'] == "Cancellation": print ('1') with open('C:\\Users\\Results.txt', "w") as f: for x in response['entities']: f.write(x['type'] + ' ') Please help me with the following: How can I assign numbers to my entity types? Is there a way to create a loop that loads multiple sentences/text to be analyzed by the NLU API? How can I write everything(entity types, text and the numbers assigned to the entity types) to a CSV file?
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52247194
has title: How to assign a number to a word from an API response
type: UnansweredQuestion
tagged with: python
tagged with: ibm-watson
type: Question
tagged with: nltk

http://stackoverflow.com/q/52177881
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91306641
score: 0
tagged with: screen-scraping
possible better answer: http://stackoverflow.com/a/52178445
tagged with: selenium
has comment: http://stackoverflow.com/comment/91305867
has answer: http://stackoverflow.com/a/52178445
type: Question
has title: How can I scroll a web page using selenium webdriver in python, for twitch?
has body: I want to scroll vertical using Selenium. I have read all the existing answers but non of them is working for the link https://www.twitch.tv/directory/all Kindly guide what is it about this page that makes the code driver.execute_script("window.scrollTo(0, 1080);") to have no effect at all. Here is the complete code: from time import sleep from selenium import webdriver driver = webdriver.Chrome('/home/sohaib/Desktop/chromedriver') driver.get('https://www.twitch.tv/directory/all') sleep(10) driver.execute_script("window.scrollTo(0, 1080);") driver.quit()`
has comment: http://stackoverflow.com/comment/91305942
has comment: http://stackoverflow.com/comment/91306710
answer count: 2
has answer: http://stackoverflow.com/a/52178330
has comment: http://stackoverflow.com/comment/91310979
accepted answer: http://stackoverflow.com/a/52178330
has comment: http://stackoverflow.com/comment/91306743
has comment: http://stackoverflow.com/comment/91306680
has comment: http://stackoverflow.com/comment/91307775
tagged with: vertical-scrolling
tagged with: python

http://stackoverflow.com/a/52192909
downvote count: 1
has body: Take a look at the inspect module. It's not always going to work (builtins implemented in C won't necessarily have line numbers, or even associated files, since some modules like sys are baked into the core interpreter, not distributed as separate files), but it's the closest you're going to get to what you're looking for. Updating your example to provide info on the origin of things: import inspect class PQR(AQZ): def Activity(self): obj = ABC() # How to know in which file, the function Start is defined try: _, lineno = inspect.getsourcelines(obj.Start) srcfile = inspect.getsourcefile(obj.Start) except TypeError: print("{!r} is a built-in".format(obj.Start)) else: print("{!r} comes from {!r}, line {}".format(obj.Start, srcfile, lineno)) obj.Start()
has comment: http://stackoverflow.com/comment/91338789
has comment: http://stackoverflow.com/comment/91337523
upvote count: 4
has comment: http://stackoverflow.com/comment/91336506
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/91337555
answers question: http://stackoverflow.com/q/52175050
has comment: http://stackoverflow.com/comment/91337737

http://stackoverflow.com/q/52124751
answer count: 2
has body: I have created a really big dataframe in pandas like similar to the following: 0 1 user 0 product4 product0 1 product3 product1 I want to use something, like pd.get_dummies(), in such a way that the final df would be like: product0 product1 product2 product3 product4 user 0 1 0 0 0 1 1 0 1 0 1 0 instead of getting the following from pd.get_dummies(): 0_product3 0_product4 1_product0 1_product1 user 0 0 1 1 0 1 1 0 0 1 In summary, I do not want that the rows are combined into the binary columns. Thanks a lot!
downvote count: 0
has title: How to Hot Encode with Pandas without combining rows levels
favorite count: 0
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/52127090
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52124785
score: 2
tagged with: categorization
type: Question

http://stackoverflow.com/comment/91260394
has text: Yes, they are stored in a list. Thanks.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52142311
score: 0

http://stackoverflow.com/comment/131589698
has text: When raised with raise_for_status(), e.reason contains a default message that's put there by the requests library, [source code for requests](https://github.com/psf/requests/blob/3.0/requests/models.py#L1024). user1898153's answer gets to the actual response from the exception handler.
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/52167579

http://stackoverflow.com/comment/91301954
type: Comment
has text: @Tom Let me try
score: 0
comment on: http://stackoverflow.com/a/52157743
type: AnswerComment

http://stackoverflow.com/a/52211061
type: Answer
accepted answer of: http://stackoverflow.com/q/52210944
has body: Use args argument to pass through extra arguments of the integrand: &gt;&gt;&gt; def func(x, a, b): ... return a * x**b ... &gt;&gt;&gt; quad(func, 0, 1, args=(1., 2.)) (0.33333333333333337, 3.700743415417189e-15)
answers question: http://stackoverflow.com/q/52210944
has comment: http://stackoverflow.com/comment/91372120
type: AcceptedAnswer
score: 0

http://stackoverflow.com/a/52249781
has body: Despite my bloviating in the comments above, this might suffice to get an appropriate index that is both low memory and starts from -1. pandas.RangeIndex Takes a start and stop parameters like range df = df.set_index(pd.RangeIndex(-1, len(df) - 1)) print(df.index, df.index.dtype, sep='\n') This should be very memory efficient. Despite it still being of dtype int64 (which you should want), it takes up very little memory. pd.RangeIndex(-1, 4000000).memory_usage() 84 And for i in range(1, 1000000, 100000): print(pd.RangeIndex(-1, i).memory_usage()) 84 84 84 84 84 84 84 84 84 84
answers question: http://stackoverflow.com/q/52249639
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/q/52134926
has comment: http://stackoverflow.com/comment/91223334
has comment: http://stackoverflow.com/comment/91223010
tagged with: python
has comment: http://stackoverflow.com/comment/91237000
has comment: http://stackoverflow.com/comment/91242607
type: AnsweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/52156138
tagged with: tensorflow
type: Question
upvote count: 9
has body: Is it because adam optimizer changes the learning rate by itself. I get an error saying 'Attempting to use uninitialized value Adam_1/lr' I guess there is no point in using ReduceLRonPlateau as Adam will automatically change learning rate.Anyways i have updated the codee Update: Code: from keras.optimizers import Adam model.compile(optimizer='adam',loss='mse') callback_reduce_lr=ReduceLROnPlateau(monitor='val_loss', factor=0.1, min_lr=1e-4, patience=0, verbose=1 ) model.fit(xTrain,yTrain,epochs=100,batch_size=10,validation_data=(xTest,yTest),verbose=2,callbacks=[callback_reduce_lr]) Error://Attempting to use uninitialized value Adam_1/lr I read somewhere that initializing adam doesnt work while working with ReduceLROnPlateau,,i have tried to initialize the weights too but i got the same error
has title: ReduceLROnPlateau gives error with ADAM optimizer
tagged with: deep-learning
accepted answer: http://stackoverflow.com/a/52156138
answer count: 1
score: 7
tagged with: keras
has comment: http://stackoverflow.com/comment/91224545
has comment: http://stackoverflow.com/comment/91220326
favorite count: 0

http://stackoverflow.com/comment/91371082
type: QuestionComment
has text: Also, your `__iter__` method returns `None`, when it should return `self` since you are implementing an *iterator*, although, you shouldn't be doing that to begin with. You should be implementing an *iterable*, where `__iter__` returns an iterator. Note, `self = self.parent` doesn't *have an affect on anything*, it simply reassigns the `self` local variable, and then the funciton returns `None`
comment on: http://stackoverflow.com/q/52210766
score: 0
type: Comment

http://stackoverflow.com/comment/91481516
comment on: http://stackoverflow.com/a/52266794
score: 0
has text: @SamMahle That's for `DataFrame.replace`. For `Series.str.replace`, it doesn't matter.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91324780
score: 5
has text: Three sidenotes: `range(100, 0, -1)` does not actually produce `range(0, 100, 1)` in reverse. If you meant to go from `0` through to `99` included, then from `99` back to `0`, use `range(99, -1, -1)`. `range(100)` is the shorter form for `range(0, 100, 1)`, it is good practice to use that instead. And there is no `range(0, infinity)` syntax, you'd use `for i in itertools.count():` perhaps to create an infinite counter, or `while True:` to create an endless loop.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52187275

http://stackoverflow.com/comment/91385365
type: Comment
type: QuestionComment
score: 2
has text: Possible duplicate of [Error in installing Tensorflow in mac](https://stackoverflow.com/questions/51824226/error-in-installing-tensorflow-in-mac)
comment on: http://stackoverflow.com/q/52218258

phylogeny
tags question: http://stackoverflow.com/q/52236273
tag name: phylogeny
type: Tag

http://stackoverflow.com/a/52150701
downvote count: 0
answers question: http://stackoverflow.com/q/52136997
has comment: http://stackoverflow.com/comment/91258481
upvote count: 2
has comment: http://stackoverflow.com/comment/91259015
has comment: http://stackoverflow.com/comment/91258292
type: Answer
score: 2
has body: My problem here is, that sometimes the code works but sometimes it doesn't and i don't really know why. :D It gives me '-' all the time even if an account appears in the list of online ppl. Just change the gm variable to something different from the page. (for example: 'Teriyaki' or something else) Thanks anyway Nummer_42O, u really helped me a lot. :P EDIT: I think I know where the problem is. Pasted the part of code. When I was checking the process, I found out, that this is only checking the last row. Any ideas? import sys import urllib import bs4 as bs from tkinter import * from tkinter import ttk import threading gm =('ADMINS') root = Tk(className='Status') v = StringVar() v.set('-') style = ttk.Style() style.configure("red.TLabel", foreground = "red") label = ttk.Label(root, textvariable=v, style = "red.TLabel") label.pack() #print(v.get()) def check(): link = 'https://www.daemu.cz/zebricky/online/' request = urllib.request.Request( link, headers={'User-Agent': 'Mozilla/5.0'}) source = urllib.request.urlopen(request).read() #pocet_na_webpage = re.search('je online (.+?) ', str(source)).group(1) #df_table = pd.read_html(source)[0] soup = bs.BeautifulSoup(source, "lxml") table = soup.table #filtering = df_table.filter(items=[0,1,3,6]) table_rows = table.find_all('tr') for tr in table_rows: td = tr.find_all('td') row = [i.text for i in td] #print(row) if str(gm) in str(row) and v.get() == ('-'): v.set('GM je ONLINE!') break elif str(gm) not in str(row) and v.get() == ('GM je ONLINE!'): v.set('-') #print(v.get()) def repeat(): thread = threading.Timer(10, repeat) try: check() thread.start() root.update() except KeyboardInterrupt: root.destroy() thread.cancel() pass pass repeat() root.call('wm', 'attributes', '.', '-topmost', '1') root.mainloop()

http://stackoverflow.com/a/52197178
has comment: http://stackoverflow.com/comment/96228016
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91363407
has body: I always thought dotenv is a pretty silly library and overcomplicating something that is so simple. Load your vars into a module namespace with Python's import system. import imp dotenv_vars = imp.load_source('dotenv_vars', '.env')
downvote count: 0
has comment: http://stackoverflow.com/comment/91363287
type: Answer
answers question: http://stackoverflow.com/q/52196575
has comment: http://stackoverflow.com/comment/91362876
has comment: http://stackoverflow.com/comment/91363578

http://stackoverflow.com/comment/91465798
score: 0
type: QuestionComment
type: Comment
has text: This [answer](https://stackoverflow.com/a/52030534/8069403) is quite interesting. There is also the [`cdist`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html) function in scipy
comment on: http://stackoverflow.com/q/52258933

http://stackoverflow.com/comment/91288106
type: Comment
type: QuestionComment
has text: @Bryan Oakley Can you agree with me that trying to describe my implementation in words without showing the thread management and the status bars will be more difficult and won't help you to help me ?
comment on: http://stackoverflow.com/q/52164003
score: 0

http://stackoverflow.com/q/52187199
type: Question
has body: We have a big XML for order and we have to parse it. Some of the order attributes coming as some value . We are parsing this XML through SSIS and it's having issue retrieving value of these attributes. We noticed that if we add a value, it works some value So, before parsing the XML using SSIS, is there any way we add tag on all elements as shown below using python: Current XML: BLACK BLACK Transformed XML: BLACK BLACK Thanks
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has title: Update XML with python script
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
has answer: http://stackoverflow.com/a/52187504
downvote count: 0
score: 1

http://stackoverflow.com/comment/91471303
type: Comment
has text: for abcin Application.Session.Accounts: print(abcin)
comment on: http://stackoverflow.com/a/52207308
type: AnswerComment
score: 0

http://stackoverflow.com/q/52168690
score: 5
linked to: http://stackoverflow.com/q/31278330
upvote count: 5
accepted answer: http://stackoverflow.com/a/52169455
tagged with: django-queryset
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91287680
tagged with: django
tagged with: python
has title: Django: filter queryset by multiple ID
has answer: http://stackoverflow.com/a/52169455
type: AnsweredQuestion
has body: My query is quite simple, I have a model Vendor in my Django REST app. What I want is to use a get response with a few ID and get back all the respective models with these ID. The GET url pattern could be something like this: r'^api/vendors?id=1,2,3'. What I'm thinking of right now is to use ListAPIView, and in the list method filter my queryset with all the id in the url. But I'm not sure exactly how to achieve this (filtering queryset with a list of id, I'm very new to both Python and Django), so if anyone can provide any advice on this it would be greatly appreciated.
type: Question

api
tags question: http://stackoverflow.com/q/52203280
tags question: http://stackoverflow.com/q/52249912
tags question: http://stackoverflow.com/q/52194550
tags question: http://stackoverflow.com/q/52193776
tags question: http://stackoverflow.com/q/52192350
tags question: http://stackoverflow.com/q/52190107
tags question: http://stackoverflow.com/q/52219202
tags question: http://stackoverflow.com/q/52140502
type: Tag
tags question: http://stackoverflow.com/q/52262344
tags question: http://stackoverflow.com/q/52165522
tags question: http://stackoverflow.com/q/52194511
tags question: http://stackoverflow.com/q/52227903
tag name: api
tags question: http://stackoverflow.com/q/52223936
tags question: http://stackoverflow.com/q/52116748
tags question: http://stackoverflow.com/q/52114052
tags question: http://stackoverflow.com/q/52204931
tags question: http://stackoverflow.com/q/52133268
tags question: http://stackoverflow.com/q/52163770
tags question: http://stackoverflow.com/q/52213291
tags question: http://stackoverflow.com/q/52230875
tags question: http://stackoverflow.com/q/52219025
tags question: http://stackoverflow.com/q/52226908
tags question: http://stackoverflow.com/q/52262916
tags question: http://stackoverflow.com/q/52197472
tags question: http://stackoverflow.com/q/52263782
tags question: http://stackoverflow.com/q/52246910

http://stackoverflow.com/q/52220794
has comment: http://stackoverflow.com/comment/91394489
has comment: http://stackoverflow.com/comment/91407993
tagged with: mysql-connector-python
has comment: http://stackoverflow.com/comment/91398996
has comment: http://stackoverflow.com/comment/91435735
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91408955
tagged with: python
has body: When I try to fetch 1,5 Million rows from MySQL table by Python script with MySQLdb, I receive “Out OF Memory” error on my server. After debugging I got this info. with SSCoursor or default cursor it uses only 650 MB of RAM with SSDictCursor it uses more than 2,5 GB of RAM and causes “Out of Memory” error Is that normal ??? If no, then how can I decrease Memory usage for SSDictCursor? Python version 2.7.12 try: print "About to connect to db." host = '127.0.0.1' port = int(conf['sshtunnel']['fwdport']) if rs_env == 'private': host = conf['db'][data_src]['private']['dbhost'] port = 3306 db = MySQLdb.connect( host = host, port = port, user = conf['db'][data_src][rs_env]['dbuser'], passwd = conf['db'][data_src][rs_env]['dbpass'], db = conf['db'][data_src]['db'], # cursorclass = MySQLdb.cursors.SSCursor) # use ssdictcursore for fetch rows in server side without out of memory error cursorclass = MySQLdb.cursors.SSDictCursor) except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit(1) c = db.cursor() query = "SELECT * FROM ....." c.execute(query) print "\n EXECUTED" # fetch rows one by one for prevent outh of memory error results = [] while True: row = c.fetchone() if row == None: break results.append(row) print "Fetched {0} records from DB.".format(str(len(results))) c.close() db.close() In the first case, I use SSCursor (cursorclass = MySQLdb.cursors.SSCursor) and it uses only 650MB of RAM. In the second case, I use SSDictCursor (cursorclass = MySQLdb.cursors.SSDictCursor) and it uses more than 2,5GB of RAM.
answer count: 0
has comment: http://stackoverflow.com/comment/91393216
score: 0
has comment: http://stackoverflow.com/comment/91390224
type: Question
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91392125
has comment: http://stackoverflow.com/comment/91417344
has title: Why does the SSDictCursor use up to 2,5 GB of RAM when I try to fetch 1,5 million rows, while the SSCursor uses just 650 MB of RAM?
tagged with: mysql-python

http://stackoverflow.com/q/52118472
downvote count: 1
type: AnsweredQuestion
tagged with: list
has title: Python: Create list of lists as dictionary values
score: 1
type: Question
favorite count: 0
has comment: http://stackoverflow.com/comment/91194471
has body: I have two lists that I would like to associate by index as key value pairs in a dictionary. The key list has multiple identical elements. I would like the all elements in the value list to be paired as a list of list. I am using the list.append() method, but this is not giving me the desired output. Any recommendations on the code or should I be looking at the problem in a different way? list1 = ['a', 'b', 'b', 'b', 'c'] list2 = [['1', '2', '3'], ['4', '5', '6'], [ '7', '8', '9'], ['10', '11', '12'], ['13', '14', '15']] combo = {} for i in range(len(list1)): if list1[i] in combo: combo[list1[i]].append(list2[i]) else: combo[list1[i]] = list2[i] Current output: {'a': ['1', '2', '3'], 'b': ['4', '5', '6', [ '7', '8', '9'], ['10', '11', '12']], 'c': ['13', '14', 15']} Desired output: {'a': [['1', '2', '3']], 'b': [['4', '5', '6'], [ '7', '8', '9'], ['10', '11', '12']], 'c': [['13', '14', 15']]}
answer count: 3
possible better answer: http://stackoverflow.com/a/52121598
has answer: http://stackoverflow.com/a/52118776
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52121598
upvote count: 2
has answer: http://stackoverflow.com/a/52118522
accepted answer: http://stackoverflow.com/a/52118522
tagged with: python
tagged with: dictionary

http://stackoverflow.com/a/52240507
answers question: http://stackoverflow.com/q/52240500
type: Answer
score: 1
upvote count: 1
has body: If the element already exists, you can simply overwrite it: mylist = [[100,200],[300,400]] mylilst[1][1] = 500
downvote count: 0

http://stackoverflow.com/a/52226137
answers question: http://stackoverflow.com/q/52224466
downvote count: 0
type: Answer
upvote count: 1
has body: For fixed length and format this straightforward code generates 39900 combinations: LETTERS = 'bcdfghjklmnpqrstvwxz' DIGITS = '2456789' def insdig(s, d): for i in range(5): ss = s[:i] + d + s[i:] print(ss) def aabb1(): for dig in DIGITS: for i in range(len(LETTERS)-1): for j in range(i+1, len(LETTERS)): a = LETTERS[i] b = LETTERS[j] insdig(a+a+b+b, dig) insdig(a+b+a+b, dig) insdig(b+a+a+b, dig) insdig(a+b+b+a, dig) insdig(b+a+b+a, dig) insdig(b+b+a+a, dig) aabb1()
score: 1

http://stackoverflow.com/comment/91239891
comment on: http://stackoverflow.com/a/52136129
has text: @Alex Friedman The sorting function within numba is in many cases slower than the numpy version. It may make sense to put the sorting outside the jit-compiled version.
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/91291553
comment on: http://stackoverflow.com/a/52155929
score: 0
type: AnswerComment
type: Comment
has text: It works great, thank you! Could you please help in another issue i have that i cannot get Apache run my wsgi application? i keep getting a Forbidden Error. Here is the link if you want to help me. https://stackoverflow.com/questions/50588933/python3-wsgi-module-error

http://stackoverflow.com/comment/91504482
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52263908
score: 0
has text: Just downloading a lot of files but they need to be under their own specific folders. For example, test_case_1 might have 10 files that need to be under test_case_1 and test_case_2 might have 3 files that need to be saved under test_case_2 etc.

http://stackoverflow.com/q/52228716
downvote count: 0
has body: I know that there are dozens of questions about this that mostly stem from following the official uWSGI guide. I have had troubles with permissions too but the other answers have covered them. I want to better understand how and when the Unix socket/socket file is created. FYI this is on an AWS ec2 instance running the Amazon Linux 2 AMI. The uWSGI guide instructs you to install nginx, Django and uwsgi. Then test the Django development server and nginx in isolation. Then at this section you test that uWSGI and nginx work together with a tcp/ip socket for communication. After that, still not involving the Django project at all, they describe how to use Unix sockets rather than the tcp/ip socket for communication between nginx and uWSGI. Following all of the nginx/uWSGI configuration you run the command from the home directory (at least for my particular file structure and Django project, ~/test_project): uwsgi --socket test_project/test_project.sock --wsgi-file test.py This works fine once some permission issues are dealt with. My questions are: what is test_project.sock, when is it created, and which process creates it. My best current understanding is that uWSGI creates it, but why then do we need to incorporate the Django project (here test_project) at all? Why not just create the socket outside of the Django project folder? Are we using python syntax and it's a member of some test_project object or module? I know that test_project.sock is associated with the Unix socket. I thought that it would be a real file but it doesn't seem to be. Even when I run uWSGI in the background and look in the appropriate directory it is not there. Is it so ephemeral that it only exists when a request is actually being passed from nginx to uWSGI? Furthermore, without being able to actually see the file (test_project.sock) how can I know which permissions are required to access it? I ran some tests and now suspect that it is related to the permissions for the ~/test_project/test_proj…
tagged with: django
type: Question
tagged with: nginx
has answer: http://stackoverflow.com/a/52229360
score: 1
accepted answer: http://stackoverflow.com/a/52229360
has comment: http://stackoverflow.com/comment/91408145
tagged with: uwsgi
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91407110
favorite count: 0
tagged with: sockets
tagged with: python
type: AnsweredQuestion
has title: When and how is the .sock file created for a uWSGI, nginx and Django stack

http://stackoverflow.com/a/52250409
has body: (?:by )?(\b(?!by\b)[\w, ]+\S) My final version, which also won't select strings only have by
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52250198
score: 1

http://stackoverflow.com/comment/91449260
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52234721
has text: yup, but no luck yet!

click
tags question: http://stackoverflow.com/q/52152830
tags question: http://stackoverflow.com/q/52266872
type: Tag
tags question: http://stackoverflow.com/q/52154611
tag name: click

http://stackoverflow.com/comment/91292999
type: AnswerComment
has text: The problem with that is that I do not know the level of nesting in my initial dictionary. Correct me if I am wrong. Happy to learn.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52171034

http://stackoverflow.com/q/52262835
tagged with: python
tagged with: regex
score: 0
has answer: http://stackoverflow.com/a/52263444
answer count: 1
has body: I'd like to remove all whitespaces in URLs / Email addresses. The addresses are in a "normal" string, like: "Today the weather is fine. Tomorrow, we'll see. More information: www.weather .com or info @weather.com" I'm looking for a good regex (using the re module of Python), but my versions can't handle all cases re.sub(u'(www)([ .])([a-zA-Z\-]+)([ .])([a-z]+)', '\\1.\\3.\\5')
tagged with: removing-whitespace
has comment: http://stackoverflow.com/comment/91473665
has title: Remove all whitespaces in URL/Email
accepted answer: http://stackoverflow.com/a/52263444
has comment: http://stackoverflow.com/comment/91473550
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/91233583
type: QuestionComment
comment on: http://stackoverflow.com/q/52141654
has text: CMD postgres or CMD ["sh", "-c", "postgres"]
score: 0
type: Comment

http://stackoverflow.com/a/52263605
has comment: http://stackoverflow.com/comment/91475339
has comment: http://stackoverflow.com/comment/91475653
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52263492
has body: Adding to @neverwalkaloner answer, I would recommend adding a namespaces to your urls. It helps with legibility because you can identify exactly from which app you're calling that url from. I'm going to assume your app name is main. from django.contrib import admin from django.urls import path import main.views app_name = 'main' urlpatterns = [ path('', main.views.index, name="index"), path('story/', main.views.story, name="story"), path('haxs/', main.views.haxs, name="haxs"), path('contact/', main.views.contact, name="contact"), path('admin/', admin.site.urls), ] our story Hope this helps!
upvote count: 2

http://stackoverflow.com/comment/91456624
comment on: http://stackoverflow.com/q/52169226
score: 0
type: QuestionComment
has text: @georgexsh yes I want an interactive shell, basically I want to get suggestions when I press tab key. I normally have this in my setup, including python, pdb launched from python and my shell prompt. However when I double press tab in the scenario mentioned in the question, I don't get any of this, instead, the prompt moves forward.
type: Comment

http://stackoverflow.com/q/52232066
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52232359
has title: Getting SyntaxError with pd.DataFrame(ticker: data.c)
has body: def load_tickers(ticker): fname = ( '%s.csv' % ticker.lower()) data = pd.read_csv( fname, header = None, parse_dates = ['Date'], names =['Date','Open','High','Low','c','Adj Close','Volume']) data = data.set_index('Date') x = pd.DataFrame(ticker: data.c) print(x) load_tickers('AAPL') I tried running my code but for some reason it's raising a SyntaxError: How can I fix this ?
type: Question
accepted answer: http://stackoverflow.com/a/52232359
tagged with: dataframe
score: 0
tagged with: syntax-error
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/91413917

http://stackoverflow.com/a/52192724
upvote count: 2
answers question: http://stackoverflow.com/q/52191137
has comment: http://stackoverflow.com/comment/91341712
has comment: http://stackoverflow.com/comment/91439625
type: AcceptedAnswer
has body: You can use Threading to scrape several pages in paralel as below: import requests from lxml import html import threading from urllib.parse import urljoin link = "https://www.yellowpages.com/search?search_terms=coffee&amp;geo_location_terms=Los%20Angeles%2C%20CA&amp;page={}" def get_information(url): response = requests.get(url).text tree = html.fromstring(response) for title in tree.cssselect("div.info"): name = title.cssselect("a.business-name span[itemprop=name]")[0].text try: phone = title.cssselect("div[itemprop=telephone]")[0].text except Exception: phone = "" print(f'{name} {phone}') threads = [] for url in [link.format(page) for page in range(20)]: thread = threading.Thread(target=get_information, args=(url,)) threads.append(thread) thread.start() for thread in threads: thread.join() Note that sequence of data will not be preserved. It means that if to scrape pages one by one sequence of extracted data will be: page_1_name_1 page_1_name_2 page_1_name_3 page_2_name_1 page_2_name_2 page_2_name_3 page_3_name_1 page_3_name_2 page_3_name_3 while with Threading data will be mixed: page_1_name_1 page_2_name_1 page_1_name_2 page_2_name_2 page_3_name_1 page_2_name_3 page_1_name_3 page_3_name_2 page_3_name_3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52191137
type: Answer
score: 2

http://stackoverflow.com/comment/130176808
score: 2
comment on: http://stackoverflow.com/a/52250169
type: AnswerComment
type: Comment
has text: by me it overwrites every time the dictionary:(

http://stackoverflow.com/a/52226559
has body: Here is a method for the first question: How to implement a variable coefficient? The thrust is assumed to be a step function of t only. It is obtained by interpolation of the given thrust commands at the corresponding time. The interpolation function is passed to model_engine function as an additional argument. The model is simplified to a vertical lander having a constant mass. import matplotlib.pylab as plt import numpy as np from scipy.interpolate import interp1d from scipy.integrate import odeint from scipy.constants import g def model_engine(u, t, thrust, mass): y, vy = u dydt = vy dvy_dt = 1/mass * thrust(t) - g return np.array([dydt, dvy_dt]) # Thrust definition: F_values = g*np.array([1, 1, 0.5, 0, 0, 2, 2, 1.5, 1]) # f-thrust in newtons timesteps = np.linspace(0, 10, np.size(F_values)) # timesteps used to defined the thrust thrust = interp1d(timesteps, F_values, kind='previous', fill_value='extrapolate') # Solve s0y, v0y = 102, 0 m0 = 1 t_span = np.linspace(0, 1.2*timesteps[-1], 111) U = odeint(model_engine, [s0y, v0y], t_span, args=(thrust, m0)) # Graphs plt.figure(); plt.plot(t_span, U[:, 0], label='altitude') plt.axhline(y=0, color='black', label='moon surface'); plt.xlabel('time'); plt.legend(); plt.figure(); plt.plot(t_span, thrust(t_span), label='thrust'); plt.xlabel('time'); plt.legend();
has comment: http://stackoverflow.com/comment/91457251
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52223432

http://stackoverflow.com/comment/91197231
score: 1
has text: What's your precise question? Does your code not work? If not, what error / result do you get versus what you expect?
comment on: http://stackoverflow.com/q/52122948
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91229080
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52139110
score: 0
has text: There is no solution for python 3.5.

http://stackoverflow.com/a/52260250
answers question: http://stackoverflow.com/q/52260069
has body: It isn't possible to use positional parameters to represent actual column names; column names need to be hard coded in the statement for many reasons. But, I don't see any problem with doing that in your case: INSERT INTO updates (ID, insert_datetime, egroup, job_state) VALUES (%s,%s,%s,%s) ON DUPLICATE KEY UPDATE insert_datetime = VALUES(insert_datetime), egroup = VALUES(egroup), job_state = VALUES(job_state); Or, as Python code: sql = "INSERT INTO updates (ID, insert_datetime, egroup, job_state) VALUES (%s,%s,%s,%s) ON DUPLICATE KEY UPDATE insert_datetime = VALUES(insert_datetime), egroup = VALUES(egroup), job_state = VALUES(job_state);" mycursor.executemany(sql, jobUpdatesList)
type: AcceptedAnswer
score: 8
has comment: http://stackoverflow.com/comment/135773231
type: Answer
has comment: http://stackoverflow.com/comment/91468271
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52260069
upvote count: 8

http://stackoverflow.com/a/52214822
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91383970
upvote count: 2
has body: The last pattern ([+-×÷]) matches the .’s because when the - sign is unescaped in the character set, the pattern matches characters whose character codes are in the range of 43 to 215. And it just so happens that the . has a character code of 46 (print(ord(".")) shows this). Testing this on a regex website like RegExr shows the details of the pattern: (Note where is shows that the - sign is acting as a range operator rather than a literal -) To fix this problem, simply escape the - like so, and the pattern will no longer match the .s. re.match(‘[+\-×÷]’,'...') #Note the added backslash after the +
type: Answer
has comment: http://stackoverflow.com/comment/91493661
accepted answer of: http://stackoverflow.com/q/52214768
answers question: http://stackoverflow.com/q/52214768

http://stackoverflow.com/comment/91405918
has text: You probably meant: `df[pd.notnull(df[df.columns[1]])]` though the `iloc` solution is probably better.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52228197
type: Comment

http://stackoverflow.com/comment/91408292
type: Comment
type: QuestionComment
has text: For example: https://stackoverflow.com/questions/19934248/nameerror-name-datetime-is-not-defined Only the bare minimum is available without importing modules. `io` is one such module that must be imported.
comment on: http://stackoverflow.com/q/52225467
score: 0

http://stackoverflow.com/a/70743483
has comment: http://stackoverflow.com/comment/125063126
answers question: http://stackoverflow.com/q/52201024
has comment: http://stackoverflow.com/comment/125140896
downvote count: 1
score: -1
upvote count: 0
has body: I have pretty much the same Problem i have a healthbar for my enemie but i want all enemys to have one so its a spritegroup now if i want to change an attribute of one object out of my spritegroup i dont know how to properly access it. The Problem lays in the Healthbaranimation function. I tried self.healthbar.sprites() self.healthbar.sprites and spritedict nothing really semms to work. Is there an easy way to fix this? P.s sorry for my bad code It is my first real attempt making a small game from os import path import pygame from elements.ammo import AMMO from elements.bigenemy import BIGENEMY from elements.enemy import ENEMY from elements.player import PLAYER from .base import BaseState from elements.healthbar import HEALTHBAR class Gameplay(BaseState): def __init__(self): super(Gameplay, self).__init__() self.next_state = "GAME_OVER" self.x, self.y = 100, 1030 self.playersprite = PLAYER((self.x, self.y)) self.bigenemy = pygame.sprite.GroupSingle(BIGENEMY()) self.bottomrect = pygame.Rect((0, 1030), (1920, 50)) self.enemysprite = ENEMY() self.ammosprite = AMMO() self.healthbar = pygame.sprite.Group(HEALTHBAR()) self.displayedimage = self.playersprite.image self.displayedrect = self.playersprite.rect self.highscore = self.load_data() self.points = 0 self.scoretext = f"SCORE: {self.points}" self.scoresurf = self.font.render(self.scoretext, True, "red") self.nhstext = "NEW HIGHSCORE!" self.nhssurf = self.font.render(self.nhstext, True, "red") self.ammotext = f"AMMO:{self.playersprite.ammunition}" self.ammosurf = self.font.render(self.ammotext, True, "red") self.bulletgroup = pygame.sprite.Group() self.time_active = 0 self.bigenemyexisting = True def get_event(self, event): if event.type == pygame.QUIT: self.quit = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LCTRL: self.playersprite.crouching = True elif event.key == pygame.K_SPACE: self.playersprite.jumping = True elif event.key == pygame.K_q and self.playersprite.ammunition != 0: self.playersprit…
type: Answer

http://stackoverflow.com/q/52176047
has title: Batch Process Files in Folder to Python Script Arguments
tagged with: bash
has answer: http://stackoverflow.com/a/52176274
tagged with: batch-processing
has comment: http://stackoverflow.com/comment/91302755
downvote count: 0
score: 1
has body: I'm trying to use this Python script to batch process filenames in place of the arguments. The script runs as follows: $ python /root/vrn/raw2obj.py --volume /root/vrn/output/file-name1105.raw \ --image /root/vrn/JPEGS/scaled/file-name1105.jpg \ --obj /root/workfolder/output/file-name1105.obj` The source of the script can be found here vrn/raw2obj.py. I tried to inherit a similar structure used for batch FFmpeg processes without any luck. The filenames are all the same between --volume --image and --obj, it's only the extensions that vary. The files are numbered as well if it is easier that way to have a reg expression, it goes from file-name0000 to file-name2254 in a sequence of 1. Is it possible to do a search or for i in the /root/vrn/JPEGS/scaled/ folder (using linux bash only) and use the filename without extension for the arguments above using Bash?
favorite count: 0
tagged with: linux
type: Question
tagged with: python
upvote count: 1
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91302696

http://stackoverflow.com/a/52136313
accepted answer of: http://stackoverflow.com/q/52136299
answers question: http://stackoverflow.com/q/52136299
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91222563
has body: The syntax is a bit off, you need to use round brackets (..) instead of square brackets [..] around a "capture group": url( r'^player/(?P&lt;slug&gt;[-\w\x20]+)/$', PlayerDetailView.as_view(), name='player-detail-view' ), Furthermore if I recall correctly, a slug can not contain spaces, so you might want to remove the \x20. Note that in django-2.0 and higher, the path(..) [Django-doc] function can be used, which has support for slugs like: # Django 2.0 and higher path('player/&lt;slug:slug&gt;/', PlayerDetailView.as_view(), name='player-detail-view'), Then Django replaces the slug with a builtin pattern, which makes the URL patterns more "declarative".
score: 1
upvote count: 1

http://stackoverflow.com/a/52245933
has body: It looks like there are two problems. The bars are much too wide. The default bar width is 1. In case of datetimes, this is one day. However your data points are only 100 seconds appart. Hence you would want to make the bar width similar to the distance between two data points. In this case e.g. ax.bar(x, y, width=1./24/60., ...) The formatter is not applied. Due to the use of twin axes it would be necessary to apply the formatter after having drawn to the axes. I.e. the line ax.xaxis.set_major_formatter(...) should come after the loop. In total this could look like import datetime, time import matplotlib.pyplot as plt import matplotlib.dates def draw_graph(): x = [ datetime.datetime.fromtimestamp(time.time()+ i * 100) for i in range(1,26) ] print x #x = [ i for i in range(1,26) ] ys = [ [12.8, 11.7, 11.0, 10.2, 9.7, 9.2, 8.8, 8.3, 7.9, 7.6, 8.7, 12.0, 13.8, 14.9, 16.0, 16.6, 17.2, 17.9, 18.9, 19.7, 20.3, 20.8, 20.3, 19.9, 19.5], [17.2, 16.5, 15.6, 15.1, 14.4, 14.0, 13.6, 13.3, 12.8, 12.5, 13.2, 14.0, 15.7, 17.0, 17.8, 19.0, 19.7, 20.4, 21.3, 22.1, 22.5, 22.8, 22.3, 21.8, 21.4] ,[0.0, 1407362982.0, 1376380000.0, 1244750888.0, 1281503386.0, 1345770126.0, 1233699697.0, 1281798998.0, 1204362605.0, 1292156436.0, 1317519540.0, 359873335.0, 481384505.0, 425220178.0, 436946318.0, 357935188.0, 411935743.0, 778855000.0, 569431637.0, 967452677.0, 707153362.0, 784057555.0, 0.0, 0.0, 0.0] ] lines=[] fig, ax = plt.subplots() ax.set_xlabel('x label') ax2=ax.twinx() index = 0 for y in ys: plt.ylabel('y label') plt.title('graph.title') if index == len(ys)-1: #last y axis line = ax2.bar(x, y, color='C' + str(index), width=1./24/60., alpha=0.5, label='bar') else: #all other y axis line, = ax.plot(x, y,'-',label='line1') ax.format_xdata = matplotlib.dates.DateFormatter('%Y-%m-%d') index = index + 1 lines.append(line) ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d/%m/%Y %H:%M:%S')) fig.autofmt_xdate() ax.legend(lines, [l.get_label() for l in lines]) plt.show() if __nam…
type: Answer
answers question: http://stackoverflow.com/q/52241472
score: 0

http://stackoverflow.com/comment/91186254
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52116727
has text: Unconscious bias, just assumed a dev would be a man, my bad. DavidMaze method does not work because it relies on a python script called from command line, check the other comment I made or google import from python2 to python3, or try the can_i_use_python3 thing, it will give you clues on what needs to change. Also IIRC module structure (__init__.py files and imports are slightly different). A horrible quick hack would be to change the sys path to include the files in the other virtualenv, maybe that will do the trick but I would suggest making ALL your code python3 compatible

http://stackoverflow.com/comment/91219273
type: Comment
has text: Can you also post your test cases and your expected result?
type: QuestionComment
comment on: http://stackoverflow.com/q/52134538
score: 0

http://stackoverflow.com/q/52187736
has title: Finding elements after click using Selenium
tagged with: python
downvote count: 0
has answer: http://stackoverflow.com/a/52188080
tagged with: selenium
accepted answer: http://stackoverflow.com/a/52188080
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/91325634
type: Question
type: AnsweredQuestion
has body: I can't figure this one out. I am working on this site and I have used selenium in Python to click on the first element under the class name "yellow showPopupUnder" (the main part of the screen where there are 20 yellow rows of information about houses). After I get Selenium to click on that row it opens up and shows more information. I am interested in the part where there are 'checked' and 'unchecked' boxes. Those checked boxes are in a div like so: &lt;div class="v_checked"&gt; And the unchecked boxes are in a div like so: &lt;div class="v_unchecked"&gt; I have tried reaching them in a few ways: driver.find_element_by_class_name('v_checked') driver.find_element_by_css_selector(".v_checked") driver.find_element_by_xpath("//div[@class='v_checked']") I have also tried to use the absolute xpath. All of these don't work and I get a "NoSuchElementException: no such element: Unable to locate element" Does anybody know how to retrieve the data from those boxes? Thank you!
score: 1
linked to: http://stackoverflow.com/q/7534622
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/q/52228596
score: 0
tagged with: pandas
has title: How to concatenate each row horizontally of a string array in python?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91407136
tagged with: python
duplicate of: http://stackoverflow.com/q/38549915
has body: This is a numpy string array. Column 1 Column 2 Column 3 A B C a b c A B C a b c I would like to concatenate each row horizontally and derive a new array with the same row number like the following: Column 1 ABC abc ABC abc Thanks.
answer count: 0
type: Question
tagged with: numpy
duplicate of: http://stackoverflow.com/q/42786804
has comment: http://stackoverflow.com/comment/91407147

http://stackoverflow.com/comment/91302755
score: 0
type: Comment
type: QuestionComment
has text: Thank you for responding. I should've mentioned in the post above that I'm not very familiar with python so I wouldn't be able to implement it on my own. I was hoping for some bash solution to be possible since I'm more familar with that
comment on: http://stackoverflow.com/q/52176047

http://stackoverflow.com/a/52172220
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/52172107
upvote count: 3
has body: Can use ffill g = df.alert.ne(0) df.loc[g[g].index, 'change'] = g[g].index df.ffill() alert value change 525590 0 46.374 NaN 525591 0 46.303 NaN 525592 3 46.310 525592.0 525593 0 46.300 525592.0 525594 0 46.400 525592.0 525595 3 46.300 525595.0 525596 0 46.310 525595.0 525597 1 46.303 525597.0 525598 0 46.387 525597.0 525599 0 46.400 525597.0 Notice that the NaN values rose because I just used the last 10 items. Should be fine when running the whole dataset
answers question: http://stackoverflow.com/q/52172107

http://stackoverflow.com/q/52143710
type: UnansweredQuestion
tagged with: python
has body: I write code in python3 mat=[] r,c=input().split() r=int(r) c=int(c) x=0 for i in range(r): mat.append([]) for j in range(c): x=x+1 mat[i].append(x) print(mat[i][j], end=" ") print() Input: 3 1 Expected Output: 1\n 2\n 3 My Output: 1\n 2\n 3\n how to correct it please help
has answer: http://stackoverflow.com/a/52144180
has title: matrix in python how to remove \n in last line
type: Question
upvote count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/52144135
has comment: http://stackoverflow.com/comment/91237215
has comment: http://stackoverflow.com/comment/91237252
answer count: 6
score: 0
has answer: http://stackoverflow.com/a/52143977
has answer: http://stackoverflow.com/a/52143835
has answer: http://stackoverflow.com/a/52143864
has answer: http://stackoverflow.com/a/52143845
favorite count: 0

http://stackoverflow.com/comment/91599729
type: Comment
has text: I want it to detect only the center part of it thats the screen and then crop it so that i can find defects inside that
type: AnswerComment
comment on: http://stackoverflow.com/a/52267251
score: 0

http://stackoverflow.com/a/73412445
has body: mail.oleobj.Invoke(*(64209, 0, 8, 0, From)) - This command threw the below exception :- com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'The item has been moved or deleted.', None, 0, -2147221238), None) Please look into it
answers question: http://stackoverflow.com/q/52202852
has comment: http://stackoverflow.com/comment/129735897
type: Answer
has comment: http://stackoverflow.com/comment/129753682
score: 0

matrix
tags question: http://stackoverflow.com/q/52243708
tag name: matrix
tags question: http://stackoverflow.com/q/52164376
tags question: http://stackoverflow.com/q/52239114
tags question: http://stackoverflow.com/q/52194708
tags question: http://stackoverflow.com/q/52183321
tags question: http://stackoverflow.com/q/52143556
tags question: http://stackoverflow.com/q/52153594
tags question: http://stackoverflow.com/q/52166639
tags question: http://stackoverflow.com/q/52213628
tags question: http://stackoverflow.com/q/52195716
tags question: http://stackoverflow.com/q/52187683
tags question: http://stackoverflow.com/q/52203016
tags question: http://stackoverflow.com/q/52233719
tags question: http://stackoverflow.com/q/52233506
tags question: http://stackoverflow.com/q/52196894
tags question: http://stackoverflow.com/q/52195539
tags question: http://stackoverflow.com/q/52242405
tags question: http://stackoverflow.com/q/52125078
tags question: http://stackoverflow.com/q/52246415
tags question: http://stackoverflow.com/q/52129494
type: Tag
tags question: http://stackoverflow.com/q/52214217
tags question: http://stackoverflow.com/q/52209977

http://stackoverflow.com/q/52162026
has body: I have a dataframe of the following format: Id Name_prev Weight_prev Name_now Weight_now 1 [1,3,4,5] [10,34,67,37] [1,3,5] [45,76,12] 2 [10,3,40,5] [100,134,627,347] [10,40,5] [34,56,78] 3 [1,30,4,50] [11,22,45,67] [1,30,50] [12,45,78] 4 [1,7,8,9] [32,54,76,98] [7,8,9] [34,12,32] I want to create two new variables: Union of Name_prev and Name_now : This is intersection of Name_prev and Name_now fields and can be done using set operation on the two columns, I am able to compute the same. Ratio of Name_prev and Name_now : This is ratio of values (Weight_prev and Weight_now) corresponding to common names in (Name_prev and Name_now). Expected Output: Id Union of Name_prev and Name_now Ratio of Name_prev and Name_now 1 [1,3,5] [10/45, 34/76,37/12] 2 [10,40,5] [100/34,627/56,347/78] 3 [1,30,50] [11/12,22/45,67/78] 4 [7,8,9] [54/34,76/12,98/32] I am trying to create a dictionary like structure by combining Name_prev and Weigth_prev as key, value pair and doing the same for Name_now and Weight_now and then taking ratio for common keys, but am stuck...
answer count: 1
downvote count: 0
favorite count: 0
has title: Creating a dictionary column using combination of two columns in dataframe, and then computing ratio of values of two columns with common keys
has answer: http://stackoverflow.com/a/52162330
tagged with: pandas
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: python-3.x
score: 1
accepted answer: http://stackoverflow.com/a/52162330
upvote count: 1
type: Question

http://stackoverflow.com/q/52242437
has body: An overridden method completely replaces the parent class' one: class Msg: def proc(self): # this part is common to all methods print("common part") # I would like the override to start here pass class A(Msg): def proc(self): # this should be appended below pass above print("overridden part") A().proc() Is it possible to partially replace the method, by keeping a "common" section and appending a specific one (per class)?
has comment: http://stackoverflow.com/comment/91433195
score: 2
has comment: http://stackoverflow.com/comment/91433346
tagged with: overriding
has comment: http://stackoverflow.com/comment/91433276
type: Question
has comment: http://stackoverflow.com/comment/91433339
duplicate of: http://stackoverflow.com/q/222877
downvote count: 0
has title: How to partially override (append to) a method?
linked to: http://stackoverflow.com/q/222877
favorite count: 0
tagged with: class
has comment: http://stackoverflow.com/comment/91433405
tagged with: python
has comment: http://stackoverflow.com/comment/91433372
has comment: http://stackoverflow.com/comment/91433298
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91433273
answer count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/52228940
has comment: http://stackoverflow.com/comment/91407646
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/52230013
favorite count: 0
has body: I’ve implemented this Python chat application by Saurabh Chaturvedi, to start learning about how networking works. The application is simple and makes use of the Tkinter module. I’d like to extend the app's functionality by enabling users to type emoticons in the message box and have them rendered as emoji in the message list, when they send the messages. For example, if the user types ‘:)’ in the message box, it should render as . So far, I've researched how to enable support for emoji in Tkinter applications. I came across Displaying emojis/symbols in Python using tkinter lib, but I don’t think it directly addresses my issue. I’m not sure if I’m currently going about solving this issue in the right way. If it’s of any help, I’m running Windows 10 and using Python 3. And you should be able to implement the chat app by running the two scripts (server and client) described in Saurabh’s article. (Also, a potentially related problem is that emoji aren't displayed properly in my Python 3 interpreter. For example, &gt;&gt;&gt; import emoji &gt;&gt;&gt; print(emoji.emojize(":thumbs_up:")) results in two question marks in boxes, rather than .) Any suggestions on how I could enable emoji to be rendered in the message list? EDIT: As per @abarnert's comment below, it's worth mentioning that this problem did not originate from my trying to use the emoji library to translate a user’s ‘:)’ to emoji. Rather, the original question arose because I was unsure of how to go about carrying out the rendering of ‘:)’ as in a Tkinter-based app, in the first place.
has comment: http://stackoverflow.com/comment/91408673
upvote count: 8
has title: How can I enable support for emoji in Tkinter applications?
has comment: http://stackoverflow.com/comment/91409432
has comment: http://stackoverflow.com/comment/91408366
has comment: http://stackoverflow.com/comment/91407756
has comment: http://stackoverflow.com/comment/91408754
tagged with: python
has comment: http://stackoverflow.com/comment/91409228
score: 8
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/91407960
linked to: http://stackoverflow.com/q/40222971
tagged with: emoji
type: Question
has comment: http://stackoverflow.com/comment/91407689
has comment: http://stackoverflow.com/comment/91407942
linked to: http://stackoverflow.com/q/47855762
has comment: http://stackoverflow.com/comment/91407896
has answer: http://stackoverflow.com/a/52230013

http://stackoverflow.com/comment/91469144
type: QuestionComment
comment on: http://stackoverflow.com/q/52260698
type: Comment
score: 0
has text: I am trying to get list of words of interest from one of the columns which contains long text

http://stackoverflow.com/q/52270628
favorite count: 0
possible better answer: http://stackoverflow.com/a/52271312
has answer: http://stackoverflow.com/a/52271312
tagged with: python
has answer: http://stackoverflow.com/a/52271447
tagged with: regex
linked to: http://stackoverflow.com/q/51982073
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91490793
upvote count: 3
has title: Regex: Match everything except unicode letters
has comment: http://stackoverflow.com/comment/91490166
has comment: http://stackoverflow.com/comment/91489259
has body: I have already asked a regex question regarding replacing specific patterns (Regex: Match a specific pattern, exclude if match is in a specific context). This is all done for preprocessing text data for training. Now I would like to use regex to replace anything except unicode letters in a pandas data frame. I have used https://regex101.com/ https://regexr.com/ to get the regex expression which seems to solve my problem \p{^L}+. I realised later that I have found the expression which would work in Perl (Perl Compatible Regular Expressions [PCRE]) not necessarily in Python. I have found the regex package which supports this expression too. However, pandas doesn't seem to support regex yet or I have used it the wrong way: import regex import pandas as pd df = pd.DataFrame({"text": ["Room: 25m²", "I have eaten ¼ of the cake."]}) df["text"] = df["text"].str.replace(regex.compile("\p{^L}+"), " ") # Returns a TypeError: object of type '_regex.Pattern' has no len() Therefore I have tried to find ways to use the re package. I have found an answer here. So I have used it this way: import re import pandas as pd df = pd.DataFrame({"text": ["Room: 25m²", "I have eaten ¼ of the cake."]}) df["text"] = df["text"].str.replace("[\W\d_]", " ") It does replace a lot of special characters. It doesn't replace the expression with m to the power of 2 or the expression where we have a fraction. Both characters which I wouldn't see as letters but rather numerics or special characters in unicode. So how can I deal with those special characters? Is it possible with the re package? I wouldn't like to use specific unicodes to match those cases. If possible a general solution would be appreciated.
type: Question
score: 3
linked to: http://stackoverflow.com/q/6314614
has comment: http://stackoverflow.com/comment/91489835
has comment: http://stackoverflow.com/comment/91489285
accepted answer: http://stackoverflow.com/a/52271447
has comment: http://stackoverflow.com/comment/91489146
has comment: http://stackoverflow.com/comment/91489148
answer count: 2
tagged with: pandas
downvote count: 0
tagged with: unicode

http://stackoverflow.com/comment/91417782
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52204820
score: 0
has text: Yes, requests looks really great :) Anyway I rewrote my script and now it's "working". There's only one problem, script is too slow :( Is there any way of making it faster? Now it's scraping 1 profile per second. When I want to scrape milions of records it tooks forever. :X

http://stackoverflow.com/comment/91472481
has text: Sorry that was a typo. I pasted the same urls.py file twice. I've tried what @blhsing suggested, but now I'm getting a namespace recognition error.
type: Comment
comment on: http://stackoverflow.com/a/52252217
score: 0
type: AnswerComment

http://stackoverflow.com/a/60938641
score: 0
type: Answer
has body: This might help you out: sudo echo "deb http://archive.ubuntu.com/ubuntu trusty main universe" | sudo tee /etc/apt/sources.list.d/wily-copies.list sudo apt-get update sudo apt-get install python-wxgtk2.8
answers question: http://stackoverflow.com/q/52199666

http://stackoverflow.com/comment/127899891
type: Comment
has text: If you don't need to store index you may want to: `reset_index(drop=True)`
comment on: http://stackoverflow.com/a/66549608
type: AnswerComment
score: 1

http://stackoverflow.com/comment/91441324
has text: @aikipooh, I see, well for elegance I don't think anything beats formatted string literals (as per my update).
type: AnswerComment
comment on: http://stackoverflow.com/a/52246428
score: 0
type: Comment

http://stackoverflow.com/a/52231700
accepted answer of: http://stackoverflow.com/q/52231642
has comment: http://stackoverflow.com/comment/91413216
has body: There are a couple issues here. 1) You are overwriting the cells list in each iteration of your loop. 2) A cell is either markdown or code, it isn't clear why you have this dictionary with keys that appear to be markdown and values that appear to be code. Are you making 6 cells total or 3? If you want six cells--the dict key followed by the dict value--try this: nb['cells'] = [] for k, v in d.items(): nb['cells'].extend([nbf.v4.new_markdown_cell(k), nbf.v4.new_code_cell(v) ]) This will add a markdown cell and a code cell in each iteration of the loop. If you just want the code cells, then you can try this: nb['cells'] = [] for v in d.values(): nb['cells'].append(nbf.v4.new_code_cell(v))
answers question: http://stackoverflow.com/q/52231642
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91412962
has comment: http://stackoverflow.com/comment/91413161

http://stackoverflow.com/a/52115154
answers question: http://stackoverflow.com/q/52115115
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91180790
has comment: http://stackoverflow.com/comment/91180817
has body: I think is possible use DataFrame constructor before assign: df = pd.DataFrame(columns=['colA', 'colB', 'colC']) df"colB","colC" = pd.DataFrame(data) Or if want add empty columns: data = np.ones((100,2)) df1 = pd.DataFrame(data, columns=["colB","colC"]).reindex(columns=['colA', 'colB', 'colC']) print (df1.head()) colA colB colC 0 NaN 1.0 1.0 1 NaN 1.0 1.0 2 NaN 1.0 1.0 3 NaN 1.0 1.0 4 NaN 1.0 1.0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52115115

http://stackoverflow.com/comment/91220426
score: 0
comment on: http://stackoverflow.com/a/52135006
type: Comment
has text: @SyafiqurRahman lst = output.slip("\n\n")
type: AnswerComment

http://stackoverflow.com/q/52228979
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0
score: 1
type: Question
tagged with: plotly-dash
upvote count: 1
tagged with: dashboard
has body: I'm new to dash dashboards, but have a few things working already and it looks promising. But I'm struggling to get one of my graphs updating with a callback. A similar procedure works for a simple line graph, but wind rose created from this example is problematic https://plot.ly/python/wind-rose-charts/ . However, plotting this rose directly, works. import numpy as np import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.graph_objs as go trace1 = go.Area( r=[77.5, 72.5, 70.0, 45.0, 22.5, 42.5, 40.0, 62.5], t=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W'], name='11-14 m/s', marker=dict(color='rgb(106,81,163)')) trace2 = go.Area( r=[57.49999999999999, 50.0, 45.0, 35.0, 20.0, 22.5, 37.5, 55.00000000000001], t=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W'], name='8-11 m/s', marker=dict(color='rgb(158,154,200)')) trace3 = go.Area( r=[40.0, 30.0, 30.0, 35.0, 7.5, 7.5, 32.5, 40.0], t=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W'], name='5-8 m/s', marker=dict(color='rgb(203,201,226)')) trace4 = go.Area( r=[20.0, 7.5, 15.0, 22.5, 2.5, 2.5, 12.5, 22.5], t=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W'], name='&lt; 5 m/s', marker=dict(color='rgb(242,240,247)')) wind_data_test = [trace1, trace2, trace3, trace4] app = dash.Dash() app.layout = html.Div(children=[ html.Div([dcc.RadioItems( id='show-period', options=[{'label': i, 'value': i} for i in ['day','week']], value='all', labelStyle={'display': 'inline-block'})], style=dict(width='50%')), dcc.Graph(id='ontoroctov-groph'), dcc.Graph( id = 'wind-rose-static', figure = go.Figure(data=wind_data_test, layout=go.Layout(orientation=270, barmode='stack'))), dcc.Graph(id = 'wind-rose-dynamic') ]) @app.callback( dash.dependencies.Output('ontoroctov-groph', 'figure'), [dash.dependencies.Input('show-period', 'value')] ) def update_figure(period_limit): return { 'data': [ {'x': np.arange(…
has title: Why doesn't this wind rose update, while line or bar graph is fine?
favorite count: 0

http://stackoverflow.com/comment/91461182
has text: In fact, the `BaseHTTPRequestHandler` implementation doesn't have any `__init__` method.
comment on: http://stackoverflow.com/q/52256931
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91442143
score: 0
type: Comment
type: QuestionComment
has text: Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions.
comment on: http://stackoverflow.com/q/52238877

google-app-engine
tags question: http://stackoverflow.com/q/52162526
tag name: google-app-engine
type: Tag
tags question: http://stackoverflow.com/q/52174600
tags question: http://stackoverflow.com/q/52224900
tags question: http://stackoverflow.com/q/52151602
tags question: http://stackoverflow.com/q/52168559
tags question: http://stackoverflow.com/q/52183664
tags question: http://stackoverflow.com/q/52249076
tags question: http://stackoverflow.com/q/52196856
tags question: http://stackoverflow.com/q/52174695
tags question: http://stackoverflow.com/q/52251406
tags question: http://stackoverflow.com/q/52241556
tags question: http://stackoverflow.com/q/52186851
tags question: http://stackoverflow.com/q/52169523

http://stackoverflow.com/comment/91471105
comment on: http://stackoverflow.com/a/52207984
has text: i tried call('my_function', my_argument) but didnt work
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91295094
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52171861
has text: I am facing the given error when tried your approach **print(user_details.roles_set.all()) AttributeError: 'User' object has no attribute 'roles_set'**
type: AnswerComment

http://stackoverflow.com/a/52213459
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52213416
has comment: http://stackoverflow.com/comment/91376418
has body: Using pd.DataFrame.loc and Boolean indexing: df.loc[df['b'].eq('dog'), 'b'] = colors print(df) index a b 0 1 pika black 1 2 halo cat 2 3 polo green 3 4 boat man 4 5 moan tan 5 6 nope yellow
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52213416

http://stackoverflow.com/q/52191056
score: 0
has title: Is it good idea to repartition 50 million records data in dataframe? If yes then someone please tell me the appropriate way of doing this
tagged with: python
has answer: http://stackoverflow.com/a/52200967
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52194219
tagged with: database
has body: We are going to handle Big Data (~50 million records) in our organization. We are partitioning data on the basis of date and other some parameters, but data is not equally partitioned. Can we do repartition on it for good performance?
tagged with: dataframe
type: Question
answer count: 2
tagged with: hadoop2
tagged with: pyspark

http://stackoverflow.com/a/52195676
has body: You could use a list comprehension: [list(map(int, list(bin(2**10 + (2**4 - 1) * 2**expo)[3:]))) for expo in range(6, -1, -1)] output: [[1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1]]
answers question: http://stackoverflow.com/q/52195539
score: 0
type: Answer

http://stackoverflow.com/a/52217608
has comment: http://stackoverflow.com/comment/91384022
score: 0
answers question: http://stackoverflow.com/q/52217512
has body: rsync -r fits in your use case and it's a single line command. rsync -r source destination or the options you need according to your specific case. So, you don't need a python script for that, but you can still write it and let it use the command above. Moreover, if you want the Python script to do it in an automatic way, you may check the event scheduler module.
type: Answer
has comment: http://stackoverflow.com/comment/91384136

http://stackoverflow.com/q/52127722
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
has answer: http://stackoverflow.com/a/58900251
linked to: http://stackoverflow.com/q/23480498
accepted answer: http://stackoverflow.com/a/52127843
possible better answer: http://stackoverflow.com/a/61051553
has title: Multiprocessing.Pool.Map Does Not Do Anything
has answer: http://stackoverflow.com/a/61051553
answer count: 3
has comment: http://stackoverflow.com/comment/122722819
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91206029
tagged with: python
has answer: http://stackoverflow.com/a/52127843
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91206004
upvote count: 3
has comment: http://stackoverflow.com/comment/91205932
has body: I was trying out multiprocessing because I was trying to imitate an internet and how it's nodes work. I am fine with the basic functionality so I looked on the documentation and used the most basic example on the 3.7.0 documentation, the version I am using now. To my surprise, it didn't work. I am using a Mac OS High Sierra, version 10.13.6, if it has to do with anything. Here is the code for clarity: from multiprocessing import Pool def f(x): return x*x if __name__ == '__main__': with Pool(5) as p: print(p.map(f, [1, 2, 3])) I was wondering why it didn't work, as it didn't show anything, and would want the working version, thank you. For Those Who Doubt It
downvote count: 1

http://stackoverflow.com/a/52140430
has body: Depending on the complexity you could either use tkinter which is a package for complex GUIs or something from the gaming community like pygames. You have user input and graphical output so libraries made for games will do what you want but provide way more stuff then you need. This site might help you: Drawing Libarys Also the answere draw-on-python-tkinter-canvas-using-mouse-and-obtain-points-to-a-list might help you.
score: 0
answers question: http://stackoverflow.com/q/52140339
type: Answer

http://stackoverflow.com/a/52136376
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52136306
score: 1
upvote count: 1
has body: Use: #specify columns for converting to dict diff_cols = df.columns.difference(['ln','name']) #create list of dictionaries L = df[diff_cols].to_dict(orient='records') #remove columns converted to list, add it to new column and convert to json out = (df.reset_index() .drop(diff_cols, axis=1) .assign(availability=pd.Series(L)) .to_json(orient='records')) print (out) [{ "index": 0, "ln": 26443, "name": "Product 1", "availability": { "7,26": "G", "7,27": "G", "7,28": "G" } }, { "index": 1, "ln": 27953, "name": "Product 2", "availability": { "7,26": "G", "7,27": "G", "7,28": "G" } }]
accepted answer of: http://stackoverflow.com/q/52136306

http://stackoverflow.com/comment/91454800
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52253563
has text: I tried very basic level code,i.e, first I find the non-zero elements in the series and store it q. After that i'am unable to move forward for getting the desired output.

http://stackoverflow.com/q/52139201
tagged with: ubuntu
tagged with: flask
score: 0
answer count: 1
has title: Cant access my flask python program on a different server
has answer: http://stackoverflow.com/a/52140487
type: UnansweredQuestion
tagged with: python
has body: So I asked a few days ago how to run a program from a browser on a different server and someone told me about Flask and I tought I should`ve gave it a try And that s what I did: I wrote the program from flask import Flask, render_template, request app = Flask(__name__) @app.route('/addnew', methods=['GET', 'POST']) def send(): if request.method == 'POST': name = request.form['name'] return render_template('see.html', name=name) return render_template('index.html') if __name__ == "__main__": app.run(host='0.0.0.0') I made up the most basic form in html so i can at least try the code Pls work First name: I run it from the console (activating venv and all that), but when i go to 'link/addnew' it tells me the page does not exist In the putty console tells me it runs on 0.0.0.0 I tryed to put the host on 127.0.0.1:5000 but it doesnt also doesnt work I am really a noobie in this so I try to copy and understand as much as possible, but i dont understand where the problem stands, please help
has comment: http://stackoverflow.com/comment/91229029
type: Question
tagged with: server
has comment: http://stackoverflow.com/comment/91230648
has comment: http://stackoverflow.com/comment/91229248

http://stackoverflow.com/a/52271070
type: Answer
answers question: http://stackoverflow.com/q/52270868
has body: It's because the site uses xhr and you need to use headless browser for that or directly try their public api.
score: 0

http://stackoverflow.com/a/52148623
upvote count: 12
downvote count: 0
has comment: http://stackoverflow.com/comment/91247164
has body: In short rb+ does not create the file from scratch wb+ does create the file from scratch there are no differences aside that.
score: 12
has comment: http://stackoverflow.com/comment/91247049
has comment: http://stackoverflow.com/comment/133570727
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91247461
answers question: http://stackoverflow.com/q/52148524
type: Answer
accepted answer of: http://stackoverflow.com/q/52148524
has comment: http://stackoverflow.com/comment/91247012

http://stackoverflow.com/q/52151827
tagged with: grouping
tagged with: python
has answer: http://stackoverflow.com/a/52151990
score: 1
has title: How to filter in a Pandas groupby object for 1 value and use it to calculate a new column?
upvote count: 1
has body: I'm currently working with a DataFrame (df) like this: df = pd.DataFrame({'fc_group': ['A', 'A', 'A','B', 'B', 'B', 'B', 'A', 'A', 'B','B'], 'dt': ['2015-05-08', '2015-05-08', '2015-05-08', '2015-05-08', '2015-05-08', '2015-05-08', '2015-05-08', '2015-05-09', '2015-05-09', '2015-05-09', '2015-05-09'], 'day': [0,1,2,0,1,2,3,1,2,0,1], 'value' : [50,150,200,60,170,220,378,140,240,700,1700]}) fc_group dt day value 0 A 2015-05-08 0 50 1 A 2015-05-08 1 150 2 A 2015-05-08 2 200 3 B 2015-05-08 0 60 4 B 2015-05-08 1 170 5 B 2015-05-08 2 220 6 B 2015-05-08 3 378 7 A 2015-05-09 1 140 8 A 2015-05-09 2 240 9 B 2015-05-09 0 700 10 B 2015-05-09 1 1700 I want to group this by "fc_group" and "dt" and create a new column named "new_column" that is calculated by df[value] / df[df[day] == 0][value] or np.nan if there is no day 0 row in a group. The result should look like this (I've highlighted the resulting groups) fc_group dt day value new_column 0 A 2015-05-08 0 50 1.00 1 A 2015-05-08 1 150 3.00 2 A 2015-05-08 2 200 4.00 3 B 2015-05-08 0 60 1.00 4 B 2015-05-08 1 170 2.83 5 B 2015-05-08 2 220 3.67 6 B 2015-05-08 3 378 6.30 7 A 2015-05-09 1 140 NaN 8 A 2015-05-09 2 240 NaN 9 B 2015-05-09 0 700 1.00 10 B 2015-05-09 1 1700 2.43 Is there a sleek pythonic way to achieve this? Either a custom function called by .apply or even in a lambda function? I have tried several approaches but none seem to work (e.g. with lambda functions I fail to get the one specific value of day 0, with customs functions and apply I get "incompatible index" errors) The only working solution I found is to create a groupby object, then manually iterate over each group using a for-loop, perform the column creation, then recombine all subgroups. This is quite slow and seems highly inefficient. Thank you for your help :)
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/52151990
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/91207223
has text: @ThomasJohannesmeyer Isn't "-1" the last index of a list? input looks like this `2018-09-01 12:41:31, 0`
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52128294

http://stackoverflow.com/comment/91288359
type: Comment
score: 0
has text: ok, you have to use either fields or exclude but you can't use both. Just use the ```exclude = ( 'user',)``` that's it.
type: QuestionComment
comment on: http://stackoverflow.com/q/52167706

http://stackoverflow.com/q/52236640
upvote count: 1
type: Question
has title: Setting the Threshold for a Perceptron
has comment: http://stackoverflow.com/comment/91429095
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has comment: http://stackoverflow.com/comment/91425647
tagged with: perceptron
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91422078
has body: How can I set the threshold for a single layer perceptron? I have import numpy as np import sklearn from sklearn.linear_model import Perceptron xs = np.array([ # x1 x2 0, 0, #m1 0, 1, 1, 0, 1, 1 ]).reshape(4, 2) ys = np.array([1, 1, 0, 1]).reshape(4,) ppn = Perceptron(max_iter=10, eta0=0.2, random_state=0) ppn.fit(xs, ys) What I wanna do is to train the ppn weights, with initial weights=(0,0), eta=0.2, threshold=0,5 Eg. for m1, initial: ys=1: net= w1*x1+w2*x2 = 0*1+0*1=0 f(net) = 1, if net&gt;=threshold else 0, f(0) = 0 # because, 0 &lt; 0.5 error = 0.2*(1-0) = 0.2 weight_update_w1 = 0+0.2*1 The learning should stop, if once for all m's no weight update is performed. How can I set the threshold for ppn to 0.5?
answer count: 0
score: 1

http://stackoverflow.com/comment/91248755
has text: Is here the danger of false positives present, as mentioned here? https://stackoverflow.com/questions/52148942/better-regex-implementation-than-for-looping-whole-file#comment91248561_52149044
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52149278

http://stackoverflow.com/q/52146460
favorite count: 0
has comment: http://stackoverflow.com/comment/91250598
linked to: http://stackoverflow.com/q/39922986
has answer: http://stackoverflow.com/a/52150182
type: Question
has comment: http://stackoverflow.com/comment/91251880
has title: Nested loops and indexing pandas dataframe using iterrows
tagged with: python
has comment: http://stackoverflow.com/comment/91242560
duplicate of: http://stackoverflow.com/q/39922986
accepted answer: http://stackoverflow.com/a/52150182
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/91250117
upvote count: 1
has comment: http://stackoverflow.com/comment/91242631
answer count: 1
has comment: http://stackoverflow.com/comment/91250088
has comment: http://stackoverflow.com/comment/91250243
has comment: http://stackoverflow.com/comment/91250475
has comment: http://stackoverflow.com/comment/91250738
tagged with: nested-loops
has body: I am trying to perform a nested loop thorugh a dataframe and I am really really new in using python. Somehow looking through the google I found many examples but the final one which I need. I used iterrows to loop over the dataframe and index on the date using only data which has the same date. That works. Now I want the nested loop but don't know how that works with iterrows? The code looks like the folloiwng: import pandas as pd df = pd.read_csv('C:/Files_Employees.csv', encoding='cp1252', sep=';', index_col=0).dropna() for current_date in df.index.unique(): print('calculating date: ' +str(current_date)) for index, row in df.iterrows(): if index == current_date: print(row['Person']) I did it via a nested loop but here I am not sure how i could do the indexing as showed above and somehow the expected results are wrong. The code looks like the following: import pandas as pd df = pd.read_csv('C:/Files_Employees.csv', encoding='cp1252', sep=';', index_col=0).dropna() df2 = pd.DataFrame([]) for i in range(0, len(df)): for j in range(i+1, len(df)): if df.iloc[i]['Working Group'] == df.iloc[j]['Working Group']: working_hours = df.iloc[i]['Working Hours'] + df.iloc[j]['Working Hours'] print(df.iloc[i]['Working Group'], working_hours) If an example is needed I can include one. The example file looks like the following: working_date Working Group Person Working Hours Country 2017-07-14 1 Mike 59 USA 2017-07-14 2 Molly 60 USA 2017-07-14 3 Dennis 45 USA 2017-07-14 4 Pablo 45 USA 2017-07-14 1 Jeff 42 USA 2017-07-14 2 Emily 55 USA 2017-07-14 3 Sophia 46 USA 2017-07-14 4 Alice 41 USA 2017-07-14 1 Ethan 57 USA 2017-07-14 2 Alexander 59 USA 2017-07-14 3 Edward 41 USA 2017-07-14 4 Daniel 46 USA 2017-07-15 1 Mike 59 USA 2017-07-15 2 Molly 59 USA 2017-07-15 3 Dennis 61 USA 2017-07-15 4 Pablo 58 USA 2017-07-15 1 Jeff 58 USA 2017-07-15 2 Emily 51 USA 2017-07-15 3 Sophia 65 USA 2017-07-15 4 Alice 53 USA 2017-07-15 1 Ethan 49 USA 2017-07-15 2 Alexander 61 USA 2017-07-15 3 Edward 56 USA 2…
tagged with: dataframe
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91250687
downvote count: 0
score: 1

http://stackoverflow.com/comment/91484733
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52263324
has text: You are not right about `compile` and instance of `Q`, please see the sqlbuilder doc. And yes, `compile` returns a tuple with sql and array of params, In question I provided this tuple for compiling insert statement, and there is the problem - sql in this tuple is not correct for sqlite, but I dont know why. I make an update for question and provides compiling and executing select statement - and compiling select statement is work
type: AnswerComment

http://stackoverflow.com/a/52211776
accepted answer of: http://stackoverflow.com/q/52211665
has comment: http://stackoverflow.com/comment/91395392
has comment: http://stackoverflow.com/comment/91375200
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91379163
has comment: http://stackoverflow.com/comment/91386437
downvote count: 0
answers question: http://stackoverflow.com/q/52211665
has body: There are several reasons for a NaN loss and why models diverge. Most common ones I've seen are: Your learning rate is too high. If this is the case, the loss increases and then diverges to infinity. You are getting a division by zero error. If this is the case, you can add a small number like 1e-8 to your output probability. You have bad inputs. If this is the case, make sure that you do not feed your model with NaNs. i.e. use assert not np.any(np.isnan(x)) on the input data. Your labels are not in the same domain of your objective function. If this is the case, check the range of your labels and make sure they match. If none of the above helps, try to check the activation function, the optimizer, the loss function, the size and the shape of the network. Finally, though less likely, there might be a bug with the framework you are using. Check the repo of the framework if there are others having the same issue.
type: Answer
has comment: http://stackoverflow.com/comment/91374493
has comment: http://stackoverflow.com/comment/91396079
has comment: http://stackoverflow.com/comment/91383534
score: 5
upvote count: 5

http://stackoverflow.com/comment/91270477
score: 1
type: AnswerComment
has text: The answers to [this question](https://stackoverflow.com/q/24944863/5085211) has some thoughts that could be used to get the minimal exponent. Depending on where you get your data, you may be able to solve this upstream though?
type: Comment
comment on: http://stackoverflow.com/a/52136129

http://stackoverflow.com/q/52206697
favorite count: 0
has body: I would like to convert the first 50 items in a large pandas dataframe into a list, that for each index in the dataframe the list would have the value. And even if the dataframe doesn't have any values in that index, I would like the list to have the value 0. For example the pandas dataframe which looks like this: ID Count 0 20 1 50 2 60 4 90 5 20 . 49 65 . 9999999 60054 would be converted to the following list, with only the first 50 elements of the dataframe being relevant: [20, 50, 60, 0, 90, 20......,65] Note that at index=3 , the value in the list is 0, because the ID was not found in the pandas dataframe.
has comment: http://stackoverflow.com/comment/91362710
has title: Efficiently converting a large pandas dataframe to a list
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52206851
has comment: http://stackoverflow.com/comment/91362645
upvote count: 3
type: Question
score: 3
tagged with: dataframe
answer count: 2
has answer: http://stackoverflow.com/a/52206911
tagged with: pandas
downvote count: 0

http://stackoverflow.com/comment/135468125
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/72819415
has text: This is the only solution that counted the number of items correctly. Data format is as rafaelc described.

http://stackoverflow.com/comment/91623759
type: QuestionComment
comment on: http://stackoverflow.com/q/52200730
has text: It seems that these bindings are used only in full graph serialization. Can't find any ready to use function, try `mdstr += ('_:' + subject if isinstance(subject, rdflib.BNode) else gs.namespace_manager.normalizeUri(subject)) + '\n'`.
score: 1
type: Comment

recurrent-neural-network
tags question: http://stackoverflow.com/q/52113582
tags question: http://stackoverflow.com/q/52202432
tags question: http://stackoverflow.com/q/52142035
tags question: http://stackoverflow.com/q/52180502
tags question: http://stackoverflow.com/q/52182185
tags question: http://stackoverflow.com/q/52138290
tags question: http://stackoverflow.com/q/52196554
tags question: http://stackoverflow.com/q/52253962
type: Tag
tags question: http://stackoverflow.com/q/52164882
tags question: http://stackoverflow.com/q/52251674
tags question: http://stackoverflow.com/q/52117900
tags question: http://stackoverflow.com/q/52168247
tags question: http://stackoverflow.com/q/52265795
tags question: http://stackoverflow.com/q/52189093
tags question: http://stackoverflow.com/q/52170404
tags question: http://stackoverflow.com/q/52235235
tag name: recurrent-neural-network
tags question: http://stackoverflow.com/q/52241632

http://stackoverflow.com/comment/91444124
comment on: http://stackoverflow.com/q/52248061
score: 0
type: Comment
type: QuestionComment
has text: Go to File → Settings → Project Settings → Project Interpreter and check if discord.py is under there. Also look at the what interpreter is being user. If not there try using `pip install discord.py` rather than `pip install discord`

http://stackoverflow.com/comment/91442887
score: 2
comment on: http://stackoverflow.com/a/52247415
type: AnswerComment
has text: I'm gonna have to follow this up :) having this functionality as part of the `str` accessor has blown my mind a bit
type: Comment

http://stackoverflow.com/comment/91188766
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52118889
has text: To illustrate that the exact same line can reappear, and should only be ignored if the two similar lines appears twice in a row

http://stackoverflow.com/a/52113863
upvote count: 1
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52113696
has body: foo = {'key1':'value1', 'key2':'value2'} def bar(key, value): print key, value [bar(key, value) for key,value in foo.items()]
score: 0

http://stackoverflow.com/q/52227540
has body: I'm new to python and pandas but here's what I want to do. I want to read through all the csv files in a directory and retrieve one cell of data from the file and update a count on a dictionary, with the retrieve value being a key in the dictionary. I have to do this for ~6000 csv files. How can I do this quickly? stats = {'A':0, 'B':0, 'C':0, 'D':0} for file in f: df = pandas.read_csv(file) type = df["type"].head(1)[0] stats[type]+=1 The order in which I read the files don't matter. I was hoping to do this concurrently, sharing the dictionary. Unless there is a better approach to what I'm trying to achieve.
type: Question
upvote count: 2
downvote count: 0
answer count: 1
tagged with: counter
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/91404592
favorite count: 0
has title: Read all csv files quickly and update shared dictionary
has comment: http://stackoverflow.com/comment/91404713
has answer: http://stackoverflow.com/a/52227782
accepted answer: http://stackoverflow.com/a/52227782
tagged with: python
tagged with: dictionary
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/52235041
has body: You can convert tensor to numpy by eval() directly. features = tf.reshape(features, [NR_FEATURES, 1]) # convert tensor to numpy with tf.Session() as sess: features = features.eval() # Your data shape needs to be adjusted relative to your model input. features = features.reshape(-1,NR_FEATURES,1) label = next['next_nr'] label = np.array([label]) yield (features, label)
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52216747
score: 1
answers question: http://stackoverflow.com/q/52216747
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91259433
has text: @RafaelC df.values is giving the same output
comment on: http://stackoverflow.com/q/52154509
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91210653
type: Comment
has text: It is inside the function, So when you all the function, It will reset the value of addition to 0. If you don't add this,whenever you call this function next time, it will start with it's previous value(in this case, 25) stored in it, and will provide a wrong answer.
comment on: http://stackoverflow.com/a/52129670
type: AnswerComment
score: 0

http://stackoverflow.com/q/52138057
has comment: http://stackoverflow.com/comment/91225844
has comment: http://stackoverflow.com/comment/91227459
has comment: http://stackoverflow.com/comment/91226895
type: UnansweredQuestion
has body: Was following an Object Detection tutorial: https://www.youtube.com/watch?v=Rgpfk6eYxJA Set up Tensorflow-gpu 1.9.0 Cuda 9.0 Cudnn 7 When I run the train.py I recieve an error that says: https://i.sstatic.net/FQfH2.jpg When I used Tensorflow-gpu version 1.5.0 (Just like in the video) I got an error that Said: " non_max_suppression() got an unexpected keyword argument 'score_threshold' " Upon research I got to know that i have to use Tensorflow 1.9 or above to avoid this error. I've tried implementing everything in order for like 3 times now and this error remains.
tagged with: python
answer count: 0
tagged with: detection
has comment: http://stackoverflow.com/comment/91225859
tagged with: tensorflow
type: Question
tagged with: object
has title: Python - Entry Point Not Found
has comment: http://stackoverflow.com/comment/91227915
score: 0
has comment: http://stackoverflow.com/comment/91226442

http://stackoverflow.com/comment/91211878
score: 0
has text: If the parameters to the function are calculated from the slice, then you could tell numpy to do that for each slice.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52130442

http://stackoverflow.com/comment/91339509
type: AnswerComment
comment on: http://stackoverflow.com/a/52194944
type: Comment
has text: It won't work:) Notice `product`'s signature: `itertools.product(*iterables, repeat=1)`, your `3` will be considered as `iterables`.
score: 1

http://stackoverflow.com/comment/91329670
comment on: http://stackoverflow.com/a/52189868
type: AnswerComment
score: 0
has text: @J.C.Rocamonde Although, the explanation why Pycharm cannot statically check that this is valid still holds.
type: Comment

http://stackoverflow.com/q/52200328
score: -1
answer count: 1
favorite count: 0
type: UnansweredQuestion
has title: Signal Comparison with python
tagged with: python
has body: From a recorded time based Panda dataset, I need to compare various signals to a reference signal. Around the reference signal I define sliding soft limits and constant hard limits. Soft limits are allowed to be crossed if it's for less time than the allowed excursion time.For a visual explanation, please see image below. Does any existing python library perform this type of data analysis? I did a thorough search, but I couldn't find anything. Thanks.
tagged with: analysis
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52200495
upvote count: 0
tagged with: signals

http://stackoverflow.com/a/52143773
type: Answer
has body: Based on the English interpretation of your code, it looks like you want something like this: for val in ["a", "b", "c"]: if val in x: print(x) print(val) break # stop checking once the first match is found Olivier Melançon's answer achieves the same thing, so the choice between that and this would just be a matter of style. If you want all the matches, you could use the set intersection operator (&amp;): matches = {"a", "b", "c"} &amp; set(x) print(matches)
score: 0
answers question: http://stackoverflow.com/q/52143318

http://stackoverflow.com/q/52119287
upvote count: 1
type: Question
has body: I am building a text editor with linguistics functionalities. I am using the Kivy framework for the first time but I am liking it a lot (it is a middle ground between Tkinter and QT in power-productivity ratio). I was able to build most of what I need already, except this: how can I format individual words/letters inside a TextInput widget? Simple example: the editor has spell-check abilities (it checks if a word exist in a DB), how can I highlight a word if it does not exist, by changing the color to red, or adding a red background shadow, but only in that single word, the rest of the text continues black? It is easy to do this to all the text (editing foreground_color property), but from what I read in the documentation the TextInput widget is poor when it comes to manipulating text (I can get cursor info and position, but can't manipulate - TKinter for instance is better in this, it allows using personalized hidden tags and styles). There is the kivy.core.text.markup widget, that adds BBCODE functionality, but only to labels, can't integrate with TextInput. An interesting thing is the CodeInput widget, but it only works with Pygments, for code syntax highlight, can't use it for target words in a DB in a spell-checker. Any ideas? I was thinking on drawing red rectangles under words with Canvas, but I don't know how to get the right position and size, and would need to disable background colors or images in the TextInput for that. Since CodeInput can highlight code syntax I know it is possible, but no idea how since there is no documentation for such a thing. Thanks
answer count: 1
tagged with: user-interface
downvote count: 0
score: 1
has title: Style single words inside TextInput widget
favorite count: 0
has answer: http://stackoverflow.com/a/52119483
tagged with: python
tagged with: kivy
type: UnansweredQuestion

http://stackoverflow.com/a/55308323
downvote count: 0
has body: Why not just use the original MinMaxScaler API in a following way: reshape X numpy array to one-column array, Scale, Reshape results back to the shape of X array import numpy as np X = np.array([[-1, 2], [-0.5, 6]]) scaler = MinMaxScaler() X_one_column = X.reshape([-1,1]) result_one_column = scaler.fit_transform(X_one_column) result = result_one_column.reshape(X.shape) print(result) Output [[ 0. 0.42857143] [ 0.07142857 1. ]]
score: 5
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/52226200

http://stackoverflow.com/comment/91192407
has text: This requirement was not necessary. I was trying things to find sequences. I can work with just the sequences.
type: AnswerComment
comment on: http://stackoverflow.com/a/52116844
score: 0
type: Comment

http://stackoverflow.com/q/52123196
has title: Why do I get an error "name 'play' is not defined" when I think it is?
accepted answer: http://stackoverflow.com/a/52123213
upvote count: 0
tagged with: nameerror
type: AnsweredQuestion
score: -1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52123213
type: Question
tagged with: python
answer count: 1
downvote count: 1
has body: Full error: line 10, in &lt;module&gt; colour = play() NameError: name 'play' is not defined I can't seem to find a reason for this issue anywhere on here. I am trying to assign the returned string to the variable colour but it is refusing to recognise the function "play". import random Funds = 10 Bet = "Red" betsequence = [0,0,0,0,0,0,0,0,0,0,0,0,0,0] counter = -1 totalcount = 0 while(Funds &gt; 0): counter = counter + 1 colour = play() if colour == Bet: Funds = Funds+(betsequence[counter]*2) counter = -1 else: Funds = Funds-betsequence[counter] print(colour) totalcount = totalcount def play(): random.seed(a=None, version=2) rannum = random.uniform(0,1) result = rannum*14 if (result &gt; 1) and (result &lt; 8): return "Red" elif result &lt; 1: return "Green" else: return "Black"

http://stackoverflow.com/comment/91455490
comment on: http://stackoverflow.com/q/52253791
type: Comment
has text: can you please post the full stack trace ?
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91301472
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52175264
has text: You're right, end and start should never be the same, updated. And you're also right in that I'm not using the right method - because I don't know the right method. Hoping there is something that does the trick.
score: 0

http://stackoverflow.com/a/52270746
score: 0
type: Answer
has body: absolutely in your case you would do system("mysqld_safe -u root -proot -e 'update mysql.user set password=PASSWORD(%s) where User=\"root\"'" % rootpassword) where the \" is treated as a part of the string rather than the string enclosing.
answers question: http://stackoverflow.com/q/52270632

http://stackoverflow.com/comment/91520794
type: QuestionComment
comment on: http://stackoverflow.com/q/52269056
has text: the problem im having is annotating the peaks, but in a way where i wont have to state the x and y for the annotation, the code will detect all peaks and there after annotate the peak values accordingly
score: 0
type: Comment

http://stackoverflow.com/q/52183664
upvote count: 1
has body: I send a POST request from a GAE Flask service to other GAE Flask service try: service_url = 'http://localhost:4040/getservice' headers = { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache', 'Auth-Key': AUTH_KEY, 'Customer': str(CUSTOMER) } s = Session() req = requests.Request('POST', service_url, data=conf, headers=headers) readytogo = req.prepare() #del readytogo.headers['Content-Lenght'] #del readytogo.headers['Host'] module = s.send(readytogo) except Exception as e: print('error') print(e) return e But i have this error: Stripped prohibited headers from URLFetch request: ['Host', 'Content-Length'] If I delete that header i have this error in console: error 'content-lenght' and this error in page: An internal error occurred: 'exceptions.KeyError' object is not callable See logs for full stacktrace. The header Content-Lenght and Host are not supported from GAE! How can I send a POST request from GAE to other GAE endpoint???
tagged with: urllib
type: Question
has answer: http://stackoverflow.com/a/52186591
tagged with: http-headers
tagged with: flask
answer count: 1
has title: Post request through GAE headers issue
downvote count: 0
score: 1
favorite count: 0
tagged with: google-app-engine
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/52252732
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91471591
has comment: http://stackoverflow.com/comment/91453200
has title: How to solve ReverseNoMatch error django?
has comment: http://stackoverflow.com/comment/91453444
answer count: 0
tagged with: url
has comment: http://stackoverflow.com/comment/91453915
has body: urls.py from django.urls import path from . import views app_name = 'infos' urlpatterns = [ path('', views.home_page, name='index_view'), path('members/', views.list_members, name='list_members'), path('members/&lt;int:id&gt;/', views.view_member, name='view_member'), path('members/&lt;int:id&gt;/photos/', views.show_photos, name='show_photos'), ] views.py def show_photos(request, id): member = BandMembers.objects.get(pk=id) member_id = member.pk print(member_id) photos = Photos.objects.get(band_member=member) return render(request, 'infos/photos.html', { 'photos': photos, 'member': member_id}) html template photos.html {% extends 'base.html' %} {% block title %} Στοιχεία {% endblock %} {% block body %} &lt;div class="container"&gt; {{ form.as_p }} &lt;a href="{% url 'infos:show_photos' id %}" class="btn btn-primary"&gt; Φωτογραφίες &lt;/a&gt; &lt;/div&gt; {% endblock %} I get a NoReserveMatch error. What am i doing wrong? I've been searching for hours and hours at Stackoverflow, Youtube,... and it seems as if i'm doing it right. But surely I DON'T !!!!!! Where is my mistake ??????? Thank you guys .
type: Question
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91452841
has comment: http://stackoverflow.com/comment/91453062
has comment: http://stackoverflow.com/comment/91453425
score: 0

http://stackoverflow.com/a/52217674
has body: Here is yet another solution: df['res'] = df.fillna('').sum(1).replace('', np.nan) The result is x y z res col a1 a NaN NaN a a2 NaN b NaN b a3 NaN c NaN c a4 NaN NaN d d a5 NaN e NaN e a6 f NaN NaN f a7 g NaN NaN g a8 NaN NaN NaN NaN
answers question: http://stackoverflow.com/q/52217180
accepted answer of: http://stackoverflow.com/q/52217180
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91383991
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91384002

http://stackoverflow.com/a/52609167
answers question: http://stackoverflow.com/q/52253962
has body: I found a solution: I create the variables for the initial state for both batchsize=64 and batchsize=1. At training I use the first one to initialize the RNN. At Predict time, I use the second one. It works as both those variables will be serialized and restored by the estimator code so it will not complain. The drawback is that the query batch size (in my case, 1) bust be known at training time (when it create both variables).
score: 0
type: Answer

http://stackoverflow.com/q/52206679
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
has body: Basic info: Odoo version : 10.0 module name : simcard model name : simcard.simcard Aim : to add a Sync button in header of the tree view and link it to a python function. My template file (template.xml) : <?xml version="1.0" encoding="UTF-8"?> <t t-extend="ListView.buttons"> <t t-jquery="button.o_list_button_add" t-operation="replace"> <t t-if="widget.model=='simcard.simcard'"> Sync </t> </t> </t> My javascript file(tree_view_button.js): odoo.define('simcard.tree_view_button', function (require){"use strict"; var ListView = instance.web.ListView; ListView.include({ render_buttons: function() { // GET BUTTON REFERENCE this._super.apply(this, arguments) if (this.$buttons) { var btn = this.$buttons.find('.sync_button') } // PERFORM THE ACTION btn.on('click', this.proxy('do_sync')) }, do_sync: function() { new instance.web.Model('simcard.simcard') .call('my_function', [[]]) .done(function(result) { alert('done') }) } }); } My python file function(models.py) : def my_function(self): print 'fooooooooooooooo' My view file (view.xml): <?xml version="1.0" encoding="utf-8"?> My manifest file : # -*- coding: utf-8 -*- { 'name': "simcard", 'summary': """ Store them""", 'description': """ Store them""", # Categories can be used to filter modules in modules listing # Check https://github.com/odoo/odoo/blob/master/odoo/addons/base/module/module_data.xml # for the full list 'category': 'Uncategorized', 'version': '0.1', # any module necessary for this one to work correctly 'depends': ['base'], # always loaded 'data': [ # 'security/ir.model.access.csv', 'views/views.xml', 'views/templates.xml', ], 'qweb': ['static/xml/tree_view_button.xml'], # only loaded in demonstration mode 'demo': [ 'demo/demo.xml', ], 'installable': True, 'auto_install': False, 'application': True, } Sync button appears in the tree view header but i am not able to call my function when i click on that button. Is there anything i am missing??
tagged with: treeview
has title: Odoo: Custom button in the header of odoo tree view doesnt trigger python function
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52207984
tagged with: odoo
score: 1
accepted answer: http://stackoverflow.com/a/52207984
downvote count: 0
answer count: 1
tagged with: javascript
favorite count: 0
tagged with: python

http://stackoverflow.com/q/52176353
score: 0
answer count: 1
tagged with: python
has body: I already have my saved checkpoints, and I can use them to make predictions. However, I just want to take a look into my trained variables and know what exact values they are. I am now using print_tensors_in_checkpoint_file from tensorflow.python.tools.inspect_checkpoint. I am also using sys.stdout to store the output into a txt file. My current code looks like this: from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file import sys def peekckpt(filePath): print_tensors_in_checkpoint_file(filePath,None,True) sys.stdout = open("tmp.txt",'w') peekckpt("/save/model.ckpt-10000") However, it won't display all the details. In tmp.txt, some variables are represented in the form of ellipsis (maybe because there are too many of them), for example: tensor_name: fully_connected_1/weights [[ 0.01625621 -0.01740162 0.04686484 ... -0.02088195 -0.02621443 0.00247668] [-0.00319242 -0.04545522 0.01150012 ... 0.00360141 -0.00241386 -0.04921322] [ 0.04347562 0.00918857 0.00323885 ... 0.01275046 -0.06735339 0.02492226] So, is there any way I can get rid of this ellipsis issue and let print_tensors_in_checkpoint_file() print all the variables?
has title: How to check all the values of trained variables in my tensorflow neural network?
tagged with: tensorflow
has answer: http://stackoverflow.com/a/52176466
accepted answer: http://stackoverflow.com/a/52176466
type: AnsweredQuestion
type: Question

http://stackoverflow.com/q/52268509
tagged with: python
has body: I have the model Period as below: class Period(models.Model): number = models.PositiveIntegerField(primary_key=True) start_time = models.TimeField() end_time = models.TimeField() How can I add constraints to make Period.start_time &lt; Period.end_time and Period models have the order like this? Period 1: 7:00-7:50; Period 2: 7:50-8:40; ... The field number express the order of the period instance. My approach is adding methods to check if it is valid . However, I want to know that there is any database way to do this.
has comment: http://stackoverflow.com/comment/91484583
upvote count: 3
type: UnansweredQuestion
tagged with: django
linked to: http://stackoverflow.com/q/12639031
score: 3
has comment: http://stackoverflow.com/comment/91484550
has comment: http://stackoverflow.com/comment/91484713
tagged with: django-models
has answer: http://stackoverflow.com/a/52268621
type: Question
answer count: 2
downvote count: 0
has title: Adding Django models constraints?
favorite count: 0
has answer: http://stackoverflow.com/a/52268675

http://stackoverflow.com/q/52226345
tagged with: scipy
has title: Function docstrings not on the web/pdf api reference scipy.stats?
has comment: http://stackoverflow.com/comment/91402253
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52227174
type: Question
score: 0
has body: Am I misunderstanding how to use SciPy documentation? I'm finding that I get much less-detailed information about stats.gamma.fit from the SciPy API Reference webpage/pdf, at least for scipy.stats, than I do from doing stats.gamma.fit? on a python console. Particularly I was unable to find out how the return value is structured from the web/pdf API Reference, even though it describes itself as The exact API of all functions and classes, as given by the docstrings. The API documents expected types and allowed features for all functions, and all parameters available for the algorithms. I also think there's a contradiction between the specification described by the web/pdf API Reference and the console docstring. Specifically, the web/pdf Reference says that the fit method produces a default value for the parameters floc and fscale. But the docstring from the console says, kwds : floats, optional Starting values for the location and scale parameters; no default. Am I reading these right?
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/91402767
has answer: http://stackoverflow.com/a/52227174

http://stackoverflow.com/comment/91303945
has text: Show what you've tried with more familiar tools.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52176797

http://stackoverflow.com/comment/91475653
type: Comment
comment on: http://stackoverflow.com/a/52263605
has text: Thats odd, you shouldnt have had a problem. This is something I personally do all the time because it has a cleaner feel. Definitely worth looking into. Ill provide a link! https://docs.djangoproject.com/en/2.1/topics/http/urls/#url-namespaces
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91387905
comment on: http://stackoverflow.com/q/52218599
type: Comment
type: QuestionComment
has text: Can you add the output of `airflow list_dags` and the exact `airflow pause` command you are running?
score: 0

http://stackoverflow.com/q/52228956
has comment: http://stackoverflow.com/comment/91414635
tagged with: http://stackoverflow.com/tag/r
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: heatmap
has body: I'm trying to re-create an image I have seen, basically needs to be identical. If anyone could point to in the right direction that would be great. It represents density of mutations across a chromosome (scale is Million base pairs) Chromosome SNP density map I have the data for this in a format like this Chromosome Chromosome_position Number_of_SNPs Chr1\t100000\t345\n Chr1\t200000\t265\n etc. Any advice would be greatly appreciated Thanks in advance Ryan
has comment: http://stackoverflow.com/comment/91411373
has answer: http://stackoverflow.com/a/52230947
type: Question
has title: multi 1d heatmap plot re-creation
tagged with: matplotlib

http://stackoverflow.com/q/52228001
downvote count: 2
tagged with: python
has title: Basic timer in Python 3.7
has comment: http://stackoverflow.com/comment/91405755
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91405657
score: 0
has comment: http://stackoverflow.com/comment/91405809
type: Question
has comment: http://stackoverflow.com/comment/91405463
has comment: http://stackoverflow.com/comment/91405823
has answer: http://stackoverflow.com/a/52228050
possible better answer: http://stackoverflow.com/a/52228167
has comment: http://stackoverflow.com/comment/91405822
has answer: http://stackoverflow.com/a/52228167
has body: Due to my poor knowledge of Stack Overflow, Python and general writing skills I didn't specify the fact that I am using the pygame module. I'm very sorry for my lack of understanding and will aim to improve. Started learning Python about 2-3 days ago. Recently encountered an issue with my implementation of a timer. I was using time.sleep(10), but later found that this actually pauses the code for 10 seconds, whereas I need it to count 10 seconds. Is there a way I could achieve this? Many thanks in advance. EDIT: I understand now that the term 'timer' is probably not best suited. What I'm actually trying to do is create a cooldown of 10 seconds.
tagged with: python-3.7
answer count: 3
has answer: http://stackoverflow.com/a/52228153
tagged with: pygame
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52228050
has comment: http://stackoverflow.com/comment/91405479
has comment: http://stackoverflow.com/comment/91405726
has comment: http://stackoverflow.com/comment/91406736
linked to: http://stackoverflow.com/q/30720665
has comment: http://stackoverflow.com/comment/91406135
upvote count: 2

http://stackoverflow.com/q/52250038
has title: How to loop over a list of lists
tagged with: for-loop
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52250053
has answer: http://stackoverflow.com/a/52250081
has comment: http://stackoverflow.com/comment/91448192
has comment: http://stackoverflow.com/comment/91448198
has answer: http://stackoverflow.com/a/52251520
favorite count: 0
has answer: http://stackoverflow.com/a/52251627
has comment: http://stackoverflow.com/comment/124444803
type: Question
has comment: http://stackoverflow.com/comment/91448267
has body: Recently I have come up with using a for loop to reform a list. First, I did this: list1 = [[1],[2],[3]] list2 = [] for x in list1: list2.append(x) print(list2) And the output was: [[1], [2], [3]] Then, I tried： list2 = [] for x in list1: list2.append(x[0]) And the output was: [1, 2, 3] Could someone please explain to me what x[0] does in this for loop? I thought this index would mean only taking the first element in a list.
tagged with: python
has comment: http://stackoverflow.com/comment/91448203
tagged with: list
score: 0
has answer: http://stackoverflow.com/a/52250103
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/52266781
answers question: http://stackoverflow.com/q/52262584
accepted answer of: http://stackoverflow.com/q/52262584
type: AcceptedAnswer
type: Answer
score: 0
has body: I've already figured it out just needed to add time in the element.click.sleep(2)

http://stackoverflow.com/a/78534690
answers question: http://stackoverflow.com/q/52251582
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/138536851
has comment: http://stackoverflow.com/comment/138462488
score: 7
upvote count: 8
has body: I had the same problem, but previous answers did not help. In the end, for me it was a matplotlib version problem. Here is how I solved it: pip install matplotlib==3.7.3 The reason is that this command is deprecated. If you want to use a more rescent version of matplotlib you can use: import matplotlib matplotlib.colormaps.get_cmap('prism')

http://stackoverflow.com/q/52253962
type: UnansweredQuestion
tagged with: python
tagged with: recurrent-neural-network
tagged with: tensorflow
type: Question
has body: I am working on a Tensorflow estimator using RNN (GRUCell). I use zero_state to initialize the first state, it requires a fixed size. My problem is that I want to be able to use the estimator to predict with a single sample (batchsize=1). When it load the serialized estimator, it complain that the size of the batch I use for prediction does not match the training batch size. If I reconstruct the estimator with a different batch size, I cannot load what has been serialized. Is there an elegant way to use zero_state in an estimator? I saw some solutions using a variable to store batch size, but using feed_dict method. I don't find how to make it work in the context of an estimator. Here is the core of my simple test RNN in the estimator: cells = [ tf.nn.rnn_cell.GRUCell(self.getNSize()) for _ in range(self.getNLayers())] multicell = tf.nn.rnn_cell.MultiRNNCell(cells, state_is_tuple=False) H_init = tf.Variable( multicell.zero_state( batchsize, dtype=tf.float32 ), trainable=False) H = tf.Variable( H_init ) Yr, state = tf.nn.dynamic_rnn(multicell, Xo, dtype=tf.float32, initial_state=H) Would someone have a clue on that? EDIT: Ok, I try various things on this problem. I now try to filter the variables I load from the checkpoint to remove 'H', which is used as internal state of the recurrent cells. For prediction, I can leave it with all 0 values. So far, I did that: First I define a hook: class RestoreHook(tf.train.SessionRunHook): def __init__(self, init_fn): self.init_fn = init_fn def after_create_session(self, session, coord=None): print("---------------&gt;After create session.") self.init_fn(session) Then in my model_fn: if mode == tf.estimator.ModeKeys.PREDICT: logits = tf.nn.softmax(logits) # Do not restore H as it's batch size might be different. vlist = tf.contrib.framework.get_variables_to_restore() vlist = [ x for x in vlist if x.name.split(':')[0] != 'architecture/H'] init_fn = tf.contrib.framework.assign_from_checkpoint_fn(tf.train.latest_checkpoint(self.mode…
answer count: 2
has answer: http://stackoverflow.com/a/52310422
has title: Tensorflow: how to use RNN initial state in an estimator with different batch size for training and testing?
score: 0
has answer: http://stackoverflow.com/a/52609167

http://stackoverflow.com/comment/91217889
comment on: http://stackoverflow.com/a/52133460
type: Comment
has text: @davidjhp Right. I don't have any further advice for you as I'm unfamiliar with the implementation outside of Pandas. Maybe this answer (and question) will lead you somewhere: https://stackoverflow.com/a/17861221
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91268935
has text: But when I save two instances of the same class to memory, shouldn't their hash values be the same? Because their contents are the same.
comment on: http://stackoverflow.com/a/52152202
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91283699
has text: It would be great if I could sort it by the file name. I just did not know how to do that
comment on: http://stackoverflow.com/q/52166051
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91335631
comment on: http://stackoverflow.com/q/52192934
score: 0
has text: You're not using python3. The last line should throw a TypeError.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52164403
has answer: http://stackoverflow.com/a/52165680
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/39721924
tagged with: python
has comment: http://stackoverflow.com/comment/91279472
tagged with: subprocess
has comment: http://stackoverflow.com/comment/117768190
upvote count: 1
has answer: http://stackoverflow.com/a/52170978
has body: I am looking for a way to create some sort of terminal "clone" in Python 3.6 using subprocess. The clone should behave just like the real terminal. The goal is to have a python script simulating a shell which behaves as much as the normal shell as possible. Including commands like cd or variable declarations. My target system is Linux with gnome shell, but my problems are probably cross OS relate. At first I din't think that was too hard as you can easily run terminal commands using subprocess but I encountered some problems. What I don't want to do: #!/usr/bin/env python import subprocess while True: command = input(" >>> ").rstrip('\n') if command == 'quit': break subprocess.run(command, shell=True) There would be a very easy way to run commands one after each other. The problem with that is, that this will start a new process for every command. So if I do the following commands it doesn't work as I want to: >>> ls stackoverflow_subprocess.py >>> cd .. >>> ls stackoverflow_subprocess.py Because we start a new process every time, commands like cd do not have any effect. That's why I want to run all commands in the same process. First Attempt: #!/usr/bin/env python from subprocess import PIPE, Popen pipe = Popen("/bin/bash", stdin=PIPE, stdout=PIPE, stderr=PIPE) quit_command = "quit" while True: command = input(" >>> ") if command == quit_command: break command = str.encode(command + "\n") out, err = pipe.communicate(command) print(out,err) This was my first attempt at solving my problem. This is what i got: >>> echo hi b'hi\n' b'' >>> echo hello Traceback (most recent call last): File "/home/user/Python/Stackoverflow/subprocess.py", line 11, in <module> out, err = pipe.communicate(command) File "/usr/lib/python3.6/subprocess.py", line 818, in communicate raise ValueError("Cannot send input after starting communication") ValueError: Cannot send input after starting communication Process finished with exit code 1 So I can't just write multiple commands like this. Sec…
has comment: http://stackoverflow.com/comment/91279031
type: Question
has title: Interactively run multiple commands from input() with subprocess
linked to: http://stackoverflow.com/q/19880190
has comment: http://stackoverflow.com/comment/91279269
has comment: http://stackoverflow.com/comment/91278896
answer count: 2
has comment: http://stackoverflow.com/comment/91290286
downvote count: 0
score: 1
favorite count: 0

checkbox
tag name: checkbox
tags question: http://stackoverflow.com/q/52181835
type: Tag

http://stackoverflow.com/a/52179680
downvote count: 1
has body: You can adjust the values after the merge: result = pd.merge(left, right, how='outer', on='date') result['FileStamp_y'] = np.where(result['FileStamp_x'].isnull(), result['FileStamp_y'], np.nan) Result: FileStamp_x date FileStamp_y 0 T101 20180101 NaN 1 T102 20180102 NaN 2 T103 20180103 NaN 3 T104 20180104 NaN 4 NaN 20180105 T502
score: 0
answers question: http://stackoverflow.com/q/52179520
type: Answer
upvote count: 1

http://stackoverflow.com/comment/91326277
type: Comment
has text: @Bazingaa I could not understand the result. What does the X value `[-2. 2. 2.]` really mean? Isn't all the three values of `X` supposed to be equal? Also what does passing an array in `guess` really mean? I am trying to understand various arguments of `minimize`.
score: 0
comment on: http://stackoverflow.com/q/52188012
type: QuestionComment

http://stackoverflow.com/q/52135580
has answer: http://stackoverflow.com/a/52135634
accepted answer: http://stackoverflow.com/a/52135634
answer count: 1
has comment: http://stackoverflow.com/comment/91221028
favorite count: 0
tagged with: datetime
tagged with: python
has body: A user will input, for example 7d 5m 4w or 7min or 6h etc. as a string, but how do I convert that into a datetime object which I will use for a timer. I have tried using time = datetime.datetime.strptime(str, "%M %H %d %m") but that gives me a spesific time, not a length. If a user inputs "35min" or "35m" time should be the time right now + 1min
downvote count: 4
type: AnsweredQuestion
has title: How to get relative time from a string?
type: Question
upvote count: 2
score: -2

http://stackoverflow.com/comment/91912639
type: AnswerComment
has text: This was fixed in release v0.6.15 on Sep 24, 2018.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52315841

http://stackoverflow.com/q/52177460
tagged with: css-selectors
has body: How to click on "get routes" on "https://maps.mapmyindia.com/direction" by selenium using Python? Thanks for your help! What I tried? I followed this "python selenium click on button", but this does not click. from selenium import webdriver #from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait #from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Firefox(executable_path=r'C:\Users\User\Desktop\pyCode\geckodriver-v0.21.0-win64\geckodriver.exe') driver.get("https://maps.mapmyindia.com/direction") startLocation = driver.find_element_by_id("auto_start") startLocation.send_keys("28.4592,77.0727") endLocation = driver.find_element_by_id("auto_end") endLocation.send_keys("28.4590,77.0725") driver.find_element_by_css_selector('div.col-xs-6.pull-right.text-right').click()
possible better answer: http://stackoverflow.com/a/52177956
has title: How to click on element with text as "GET ROUTES" within the url https://maps.mapmyindia.com/direction using Selenium and Python?
has answer: http://stackoverflow.com/a/52177956
tagged with: display
type: Question
has comment: http://stackoverflow.com/comment/91305158
type: AnsweredQuestion
tagged with: python
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52177525
tagged with: selenium
linked to: http://stackoverflow.com/q/21350605
accepted answer: http://stackoverflow.com/a/52177525
linked to: http://stackoverflow.com/q/44668998
tagged with: webdriver

http://stackoverflow.com/q/52156752
has body: I am currently working on a binomial classification algorithm with a highly skewed data (90% negative/10% positive), using tf.estimator.DNNClassifier. As all models that I train converge to label all samples as negatives, I need to implement a weighted loss function. I looked at many different questions here and many of them are enlightning. However, I could not get a practical end-to-end answer on how actually implement the functions. This and this threads were the best. My problem is: I want to use tf.nn.weighted_cross_entropy_with_logits(), but I don't know where I should insert it in my code. I have a function to construct the Feature Colums: def construct_feature_columns(input_features): return set([tf.feature_column.numeric_column(my_feature) for my_feature in input_features]) A function that defines the tf.estimator.DNNClassifier and also other parameters, like optimizer and input function: def train_nn_classifier_model( learning_rate, steps, batch_size, hidden_units, training_examples, training_targets, validation_examples, validation_targets): dnn_classifier = tf.estimator.DNNClassifier( feature_columns=construct_feature_columns(training_examples), hidden_units=hidden_units, optimizer=my_optimizer) The training function: dnn_classifier.train(input_fn=training_input_fn, steps=steps_per_period) The predict function, to calculate the error while training: training_probabilities = dnn_classifier.predict(input_fn=predict_training_input_fn) The Optimizer: my_optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0) Input functions (for training input, predicting training inputs and validation inputs): training_input_fn = lambda: my_input_fn( training_examples, training_targets['True/False'], batch_size=batch_size) Where should I insert tf.nn.weighted_cross_entropy_with_logits, so my model calculates the losses using this function? Also, how do I call the targets (A Tens…
accepted answer: http://stackoverflow.com/a/52159577
linked to: http://stackoverflow.com/q/49813386
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
tagged with: classification
tagged with: machine-learning
tagged with: python
has title: Where does Tensorflow Weighted Cross Entropy loss function goes in the DNN Classifier Estimator function?
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52159577
tagged with: loss-function
linked to: http://stackoverflow.com/q/47034888
tagged with: tensorflow
type: Question

http://stackoverflow.com/a/52266954
answers question: http://stackoverflow.com/q/52265073
has comment: http://stackoverflow.com/comment/91507631
has body: Your enemy sprite takes a unit step toward the player at each iteration. Eventually, it's perfectly coincident with the player, and self.dist is a perfect 0. Your coordinates are integers, so it's not hard to get the math to come out exactly. In the previous version, were the coordinates floats? That could easily explain the difference.
downvote count: 0
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/91481832
upvote count: 1

http://stackoverflow.com/a/52191045
type: Answer
has body: It looks like a threading issue. Since your thread is using the camera, you probably cannot read from it in your main thread. Try not starting the thread, since it doesn't seem it's being used otherwise, and it is not stated in your goal. If instead you want to get frames continously and just save them when the button is clicked, you'll have to write a slot that is connected to the signal you're emitting in the thread, then put in some logic to save when the button is clicked. Also, It looks like you have a infinite loop in click_picture, and the reading syntax in that method should look like: flag, frame = cap.read(). If you're interested in a project using a similar approach, check this out (disclaimer, I'm one of the authors.): https://github.com/natedileas/ImageRIT/blob/master/Server/qt_CameraWidget.py
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52190498
downvote count: 0

http://stackoverflow.com/q/52147085
accepted answer: http://stackoverflow.com/a/52153342
tagged with: python
favorite count: 0
upvote count: 1
tagged with: tensorflow
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91264900
has answer: http://stackoverflow.com/a/52153342
has title: Why tf manipulations are working only in the arbitrary function?
has comment: http://stackoverflow.com/comment/91245628
type: Question
answer count: 1
downvote count: 0
has body: When I build a series of tensors, the manipulation functions of tensorflow, such as tf.transpose(~) or tf.split(~) returns an error. Code window = 60 len_feat= 15 X = tf.placeholder(tf.float32, shape=[None, window, len_feat] X = tf.transpose(X, (1,0,2)) tf.Session().run(X, feed_dict={X: x}) #x has a shape (100, 60, 15) Error "shape (100, 60, 15) can't be reshaped into (60, ?, 15)" However, if I build an arbitrary function such as: X = tf.placeholder(tf.float32, shape=[None, window, len_feat]) def fun(X): X = tf.transpose(X, (1,0,2)) ... it works well. What makes this difference?

http://stackoverflow.com/q/52237275
has comment: http://stackoverflow.com/comment/91423116
upvote count: 1
has answer: http://stackoverflow.com/a/52237469
type: Question
has answer: http://stackoverflow.com/a/52237380
score: -1
has comment: http://stackoverflow.com/comment/91428822
answer count: 2
has comment: http://stackoverflow.com/comment/91428806
favorite count: 0
has title: How to remove space being printed in else statement
type: UnansweredQuestion
has body: I have this code which returns days, hours, minutes, and seconds from a input. The issue is, when there is 0 of some value it should print nothing. I put in the else statement to do "", however it still occupies a space in the output which I do not want.
tagged with: python
has comment: http://stackoverflow.com/comment/91423117
downvote count: 2

http://stackoverflow.com/comment/91431478
comment on: http://stackoverflow.com/q/52241117
score: 0
has text: @StephenRauch No worries. Thanks for attempting to help anyway.
type: QuestionComment
type: Comment

docker
tags question: http://stackoverflow.com/q/52155191
type: Tag
tags question: http://stackoverflow.com/q/52172970
tags question: http://stackoverflow.com/q/52141654
tags question: http://stackoverflow.com/q/52180512
tags question: http://stackoverflow.com/q/52127228
tags question: http://stackoverflow.com/q/52127979
tags question: http://stackoverflow.com/q/52213338
tags question: http://stackoverflow.com/q/52259241
tags question: http://stackoverflow.com/q/52193937
tags question: http://stackoverflow.com/q/52173447
tags question: http://stackoverflow.com/q/52198908
tags question: http://stackoverflow.com/q/52130203
tag name: docker
tags question: http://stackoverflow.com/q/52194998
tags question: http://stackoverflow.com/q/52187522
tags question: http://stackoverflow.com/q/52153076
tags question: http://stackoverflow.com/q/52158466
tags question: http://stackoverflow.com/q/52229522
tags question: http://stackoverflow.com/q/52195378
tags question: http://stackoverflow.com/q/52206801
tags question: http://stackoverflow.com/q/52262351
tags question: http://stackoverflow.com/q/52119004
tags question: http://stackoverflow.com/q/52230346

http://stackoverflow.com/q/52241188
score: 1
has comment: http://stackoverflow.com/comment/91431022
type: Question
has body: SCOPES_SHEETS = 'https://www.googleapis.com/auth/spreadsheets' Gives read/write permissions ^ def main(): service_sheets = get_google_service('sheets', 'v4', 'token_sheets.json', SCOPES_SHEETS) with open('services.pkl', 'wb') as f: pickle.dump(service_sheets, f) with open('services.pkl', 'rb') as f: service_sheets = pickle.load(f) with open('serviceCopy.pkl', 'wb') as f: pickle.dump(service_sheets, f) def get_google_service(type, version, token, scope): store = file.Storage(token) creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', scope) creds = tools.run_flow(flow, store) return build(type, version, http=creds.authorize(Http())) I have a program that I want to run as a service in the background. It involves reading/writing things in a google sheet. For this I have to create a google service but I don't want to have to do it every time the code runs so I'm trying to store the service object in a file instead. For some reason the file service.pkl is different from serviceCopy.pkl. I've tried changing the encoding for pickle.load(file, encoding='utf8') but I keep getting files that don't match. To my understanding they should be exactly the same. I think the issue is with loading the saved file but I'm not sure what's causing it. I'm using python 3.6.
tagged with: google-api-client
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91431234
tagged with: python-3.x
answer count: 0
tagged with: google-api
type: UnansweredQuestion
tagged with: pickle
upvote count: 1
tagged with: python
has title: Python Pickle.load() not loading correctly

http://stackoverflow.com/q/52193475
has comment: http://stackoverflow.com/comment/91369212
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91336741
tagged with: python
has title: What happens to the new Python Tuple when it is added to itself
type: Question
has comment: http://stackoverflow.com/comment/91337091
has answer: http://stackoverflow.com/a/52193512
score: 0
has body: I have a beginner question on Python. If I have a python tuple: x = ('a', 'b', 'c') and then x + x would give me: ('a', 'b', 'c', 'a', 'b', 'c') Question: What happens to the new Python Tuple when it is added to itself x + x? I can reference the tuple x but what about the new tuple that is x + x, how would you reference? Does it become a unreferenced memory, meaning no pointer can reference it? Thank you, G.
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/52165945
score: 1
accepted answer of: http://stackoverflow.com/q/52165896
has comment: http://stackoverflow.com/comment/91281377
answers question: http://stackoverflow.com/q/52165896
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: The left side of the assignment is not allowed as you list has length 0. Either fix it to: df_array = [None, None, None, None] or use df_array.append(self.data[int(length/4), :]) ... instead.
type: Answer

http://stackoverflow.com/comment/91411845
comment on: http://stackoverflow.com/q/52223302
score: 0
has text: .I checked the code, and run it, and no error appeared , but just can not get the data, such as company, contact , number etc. but if i run the code one by one on jupyter notebook, it is ok.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52208550
answers question: http://stackoverflow.com/q/52208128
has body: The issue isn’t your syntax; it’s that you’re trying to do something illegal. You can’t create new local variables with exec. (The reason the same code outside a function works is that in general you can create a new global variable with exec, but it’s still a bad idea.) But you also don’t need to do that. In Python, everything is an object, including classes. So, you just need the get the class from the name. Then you can create an instance of that class, and store it in a local variable, by just using the same normal syntax you’d use for instantiating a class statically and storing it in a local variable. The right way to do this is to store a dictionary mapping names to class objects. If you want to get clever, you can write a decorator that registers classes with that dictionary, but if that sounds like Greek to you, just do it explicitly: classes = {'Spam': Spam, 'Eggs': Eggs} If you have dozens of these, you can avoid the repetition with a comprehension like this: from your_module import Spam, Eggs classes = {cls.__name__: cls for cls in (Spam, Eggs)} … but at that point you’re probably better off learning how to write the decorator. Either way, you can fill your combo box with the keys of that dictionary instead of repeating yourself in the combo['values'] line. And then, to create an instance, you just do this: cls = classes[comboExample.get()] instance = cls() (Obviously you can collapse that into a single line, but I thought it would be easier to understand if we keep the two parts separate.) If you really want to do this in a hacky way, you can. Every class that you’ve created in this module is already stored in a dictionary by name—the module’s global namespace. That’s the same place you were trying to find it implicitly with exec, but you can find it explicitly by just looking it up in globals(). However, the global namespace also has the names of all of your functions, imported modules, top-level constants and variables, etc., so this is usually a bad …
upvote count: 3
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52208128
score: 3
has comment: http://stackoverflow.com/comment/91366996
downvote count: 0

http://stackoverflow.com/comment/91332362
score: 1
comment on: http://stackoverflow.com/q/52188407
has text: @FilipHappy I edited the original question to include it. sorry about that!
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91249132
type: Comment
type: QuestionComment
has text: There's is not thread safe way (web applications need to be thread safe) to do that.
comment on: http://stackoverflow.com/q/52149588
score: 0

http://stackoverflow.com/comment/91218616
has text: You use `self` for class methods.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52133861
score: 0

http://stackoverflow.com/a/52171861
score: 0
has comment: http://stackoverflow.com/comment/91295094
has comment: http://stackoverflow.com/comment/91295672
type: Answer
has comment: http://stackoverflow.com/comment/91295494
has comment: http://stackoverflow.com/comment/91295384
has comment: http://stackoverflow.com/comment/91295950
answers question: http://stackoverflow.com/q/52169137
has body: When accessing a specific model instance (and not the model's manager) you access related items with modelname_set instead of modelname. For example: &gt;&gt;&gt; user_detail.roles_set.remove(my_role) &gt;&gt;&gt; user_detail.roles_set.all() &lt;QuerySet []&gt; Docs: https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_many/

http://stackoverflow.com/q/52163808
tagged with: joblib
has body: I have a program that uses a lot of memory (150gb of vectors indexed with nmslib) and I have trouble to parallelize the execution of the code. My machine has 40 cores and my attempts to parallelize it have been not successful so far. the programm first loads the vectors and then prepares some data based on the vectors (this part is fine and performance is good, because most of the workload is done by nmslib which is multithreaded by itself). Now the trouble starts when I postprocess the data that has been loaded into RAM by nmslib. I am iterating over a list that has 500 entries, each representing the data of one file. The code I use to process this data and that I try to execute in parallel is the following routine: def tib_result_turn_to_file(data): fileindex = data[0] main_bucket = data[1] result_string = "" print("Now processing: " + fileindex[0]) print(abs(fileindex[1]-fileindex[2])) #print(len(results)) c = fileindex[1] c1 = 0 while c &lt; fileindex[2]: if main_bucket == "tengyur1": tibwords = tibwords_tengyur1 if main_bucket == "tengyur2": tibwords = tibwords_tengyur2 if main_bucket == "kangyur": tibwords = tibwords_kangyur result_string += "\n" + main_bucket + "#" + fileindex[0] + " " + str(c) for result in data[2][c1]: bucket = result[2] if bucket == "tengyur1": tibwords = tibwords_tengyur1 if bucket == "tengyur2": tibwords = tibwords_tengyur2 if bucket == "kangyur": tibwords = tibwords_kangyur bucket = result[2] result_position = result[1] result_score = result[0] # we don't want results that score too low or that are identical with the source: if result_score &lt; 0.03 and (result_position &lt; c- 20 or result_position &gt; c + 20): result_string += "\t" + bucket + "#" + tibwords[result_position][0] + "#" + str(result_position) c += 1 c1 += 1 with open("/mnt/output_parallel/" + fileindex[0][:-4] + "_parallel_index.org", "w") as text_file: text_file.write(result_string) the lists starting with tibwords are huge lists of each 50 million entries. They are de…
tagged with: out-of-memory
type: UnansweredQuestion
tagged with: python
tagged with: parallel-processing
has title: Speed up a routine inside a process with high memory usage by using parallel processing in python
has answer: http://stackoverflow.com/a/52177587
type: Question
score: 0
answer count: 1

http://stackoverflow.com/comment/91674596
type: QuestionComment
has text: @xdurch0 thanks for your input, it seems you are right. I found this paper, which cleared out most of my questions "Is Joint Training Better for Deep Auto-Encoders?" https://arxiv.org/pdf/1405.1380.pdf
score: 2
comment on: http://stackoverflow.com/q/52221103
type: Comment

http://stackoverflow.com/comment/91302768
type: Comment
type: QuestionComment
has text: The [docs](https://docs.djangoproject.com/en/2.1/ref/settings/#media-root) state that this must be an "absolute filesystem path to the directory that will hold user-uploaded files" - you have provided a relative path. Try changing it to an absolute path?
comment on: http://stackoverflow.com/q/52175987
score: 0

http://stackoverflow.com/a/64838681
type: Answer
has body: You can find below another validation method that may help in case someone wants to build models using GPU. First thing we need to create device to use either GPU or CPU. Start with importing torch modules. import torch import torch.nn as nn from torch.utils.data import DataLoader And then create device: device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") We will use this device on our datas. We can calculate the accuracy of our model with the method below. def check_accuracy(test_loader: DataLoader, model: nn.Module, device): num_correct = 0 total = 0 model.eval() with torch.no_grad(): for data, labels in test_loader: data = data.to(device=device) labels = labels.to(device=device) predictions = model(data) num_correct += (predictions == labels).sum() total += labels.size(0) print(f"Test Accuracy of the model: {float(num_correct)/float(total)*100:.2f}")
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/52176178
score: 4

http://stackoverflow.com/q/52250678
score: 0
answer count: 1
has body: I want to use the pretrained resnet_50 in my model and I want to specify GPU:1 for all the ops in resnet. But I don't know how to do it. Can anyone help me? here is my code: slim = tf.contrib.slim with slim.arg_scope(nets.resnet_v1.resnet_arg_scope()): features, _ = nets.resnet_v1.resnet_v1_50(inputs, num_classes=None) and I try slim = tf.contrib.slim with slim.arg_scope(nets.resnet_v1.resnet_arg_scope()): with tf.device("/gpu:1"): features, _ = nets.resnet_v1.resnet_v1_50(inputs, num_classes=None) It doesn' work. I find a function named VariableDeviceChooser, but I don't know how to use it. Help me please~
type: UnansweredQuestion
tagged with: python
has title: How to do device placement for some model in tensorflow.contrib.slim
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/52253952

http://stackoverflow.com/q/52194592
score: 0
has title: Tesseract OCR: Detect non-white background
type: UnansweredQuestion
tagged with: python
tagged with: ocr
answer count: 0
type: Question
tagged with: tesseract
has comment: http://stackoverflow.com/comment/91344391
has body: I am writing python to detect the digits on non-white background with following code: import pytesseract, re from PIL import Image pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract OCR\\tesseract.exe' text = pytesseract.image_to_string(Image.open("image3.jpg")) print (text) However, nothing is detected....how to make it work? Thanks. digits on non-white background
has comment: http://stackoverflow.com/comment/91338896

http://stackoverflow.com/q/52157937
has answer: http://stackoverflow.com/a/52158075
downvote count: 0
has answer: http://stackoverflow.com/a/52158058
favorite count: 0
has comment: http://stackoverflow.com/comment/91267165
has title: Raise an exception if a specific key exists in a dictionary, but return successfully if it does not exist
tagged with: exception
tagged with: python
score: 11
tagged with: dictionary
upvote count: 11
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52158075
has body: Suppose I have the following function: def test(): ... if x['error']: raise This would raise an exception regardless if x['error'] is defined or not. Instead if I try this, it doesn't throw any exception: def test(): ... try: if x['error']: raise except: return How can I test for a specific value and return an exception if it is defined, and to return successfully if it is not defined?
type: Question
has answer: http://stackoverflow.com/a/52158026
has comment: http://stackoverflow.com/comment/91267198
accepted answer: http://stackoverflow.com/a/52158026
has comment: http://stackoverflow.com/comment/91266851
answer count: 3

http://stackoverflow.com/comment/91395439
has text: What is `WHERE (s, s2, s3, s4) = '...'` supposed to accomplish? Do you mean something like `WHERE s = '...' OR s1 = '...' OR s2 = '...'`…?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52214332

alexa-skills-kit
tag name: alexa-skills-kit
type: Tag
tags question: http://stackoverflow.com/q/52116896

http://stackoverflow.com/comment/91269050
has text: I meant the reading library. The writing library is essentially irrelevant here. Your test script is, I'm sure, a faithful enough representation.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52159531
type: Comment

http://stackoverflow.com/a/52185056
answers question: http://stackoverflow.com/q/52184885
score: 1
downvote count: 0
has body: You can do this using broadcasting: np.sum( (x[None, :] ** (1 / n_values[:, None])) * (y[None, :] / tot_value), axis=1 ) ** n_values
type: Answer
upvote count: 1

django-filebrowser
type: Tag
tag name: django-filebrowser
tags question: http://stackoverflow.com/q/52208582

http://stackoverflow.com/q/52165896
has answer: http://stackoverflow.com/a/52165953
has body: I am trying to execute the following code: def calculate_squared_dist_sliced_data(self, data, output, proc_numb): for k in range(1, self.calc_border): print("Calculating",k, "of", self.calc_border, "\n", (self.calc_border - k), "to go!") kmeans = KMeansClusterer.KMeansClusterer(k, data) print("inertia in round", k, ": ", kmeans.calc_custom_params(data, k).inertia_) output.put( proc_numb, (kmeans.calc_custom_params(self.data, k).inertia_)) def calculate_squared_dist_mp(self): length = np.shape(self.data)[0] df_array = [] df_array[0] = self.data[int(length/4), :] df_array[1] = self.data[int((length/4)+1):int(length/2), :] df_array[2] = self.data[int((length/2)+1):int(3*length/4), :] df_array[3] = self.data[int((3*length/4)+1):int(length/4), :] output = mp.Queue() processes = [mp.Process(target=self.calculate_squared_dist_sliced_data, args=(df_array[x], output, x)) for x in range(4)] for p in processes: p.start() for p in processes: p.join() results = [output.get() for p in processes] When executing df_array[0] = self.data[int(length/4), :], I get the following error: IndexError: list assignment index out of range The variable lentgh has the value 20195 (which is correct). I want to do the method calculate_squared_dist_sliced_data by multiprocessing, so I need to split the array data that is passed to this class. Here is an example of how this numpy array looks: [[ 0. 0. 0.02072968 ..., -0.07872599 -0.10147049 -0.44589 ] [ 0. -0.11091352 0.11208243 ..., 0.08164318 -0.02754813 -0.44921876] [ 0. -0.10642599 0.0028097 ..., 0.1185457 -0.22482443 -0.25121125] ..., [ 0. 0. 0. ..., -0.03617197 0.00921685 0. ] [ 0. 0. 0. ..., -0.08241634 -0.05494423 -0.10988845] [ 0. 0. 0. ..., -0.03010139 -0.0925091 -0.02145017]] Now I want to split this hole array into four equal pieces to give each one to a process. However, when selecting the rows I get the exception mentioned above. Can someone help me? Maybe for a more theroretical approach of what I want to do: A B C D 1 2 3 4 5 6 7 8 9…
type: Question
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/52165953
has answer: http://stackoverflow.com/a/52165945
accepted answer: http://stackoverflow.com/a/52165945
tagged with: python-3.x
has title: Python numpy array split index out of range
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/52121283
type: Question
has answer: http://stackoverflow.com/a/52122431
tagged with: python
score: 1
has body: I have a dataframe something like this +---+---------+--------------------+ | id| name| actor| +---+---------+--------------------+ | 0| [123]| tom| | 1| [321]| brad| +---+---------+--------------------+ FYI. 'name' - StringType() But I would like to get something like this +---+---------+--------------------+ | id| name| actor| +---+---------+--------------------+ | 0| 123| tom| | 1| 321| brad| +---+---------+--------------------+ I am trying to extract the values between the square bracket and cast it to IntegerType. I tried using split function with regular expression. But, its not working.
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/52122434
has title: How to extract column value within square brackets in pyspark?
has answer: http://stackoverflow.com/a/52121580
downvote count: 0
tagged with: pyspark
type: UnansweredQuestion
favorite count: 0

http://stackoverflow.com/comment/91372503
comment on: http://stackoverflow.com/q/52211220
type: QuestionComment
has text: Is it able to print in a position on a GUI?
score: 0
type: Comment

http://stackoverflow.com/comment/91432857
comment on: http://stackoverflow.com/q/52242162
score: 0
type: Comment
type: QuestionComment
has text: I tried commenting out m2m and made migration, but got error-- django.db.utils.ProgrammingError: column "p_id_id" of relation "appname_t" does not exist. I checked in my current DB, every T has a unique P. 1 T can only have 1 P. but 1P can have multiple T's.

http://stackoverflow.com/q/52145497
tagged with: sqlite
answer count: 1
has comment: http://stackoverflow.com/comment/91240764
tagged with: python-3.x
has title: How can I let the id be auto generated in my database?
tagged with: python
has comment: http://stackoverflow.com/comment/91240827
has body: Here is my code: import sqlite3 def insert(fields=(), values=()): connection = sqlite3.connect('database.db') # g.db is the database connection cur = connection.cursor() query = 'INSERT INTO this_database (%s) VALUES (%s)' % ( ', '.join(fields), ', '.join(['?'] * len(values)) ) cur.execute(query, values) connection.commit() id = cur.lastrowid cur.close() print (id) test example: insert(fields = ("id", "file_name", "url", "time", "type", "description"), values = (2, "file1", "wwww.test.com", "1", "photo", "my first database test")) I don't want to give the id manually. I want it to add it+1 automatically. How can I do that?
type: Question
has answer: http://stackoverflow.com/a/52145841
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/7905859
has comment: http://stackoverflow.com/comment/91240727
accepted answer: http://stackoverflow.com/a/52145841
has comment: http://stackoverflow.com/comment/91240779
has comment: http://stackoverflow.com/comment/91240753
score: 0

http://stackoverflow.com/a/52259565
has comment: http://stackoverflow.com/comment/91468079
has comment: http://stackoverflow.com/comment/91468579
has comment: http://stackoverflow.com/comment/91468548
has comment: http://stackoverflow.com/comment/91468272
has body: One line comments are done using the # while multiline comments are done using the triple-quote """ Text here and here""" the -- comment is used in sqlite with python. Do you have that comment inside a query that is also written inside a string/triple-quote comment? Like: """ SELECT * FROM TABLE --WHERE N = X""" UPDATE 1: Here you can see and example of comment inside the query done in a python code query = """ SELECT * FROM TABLE --WHERE N = X""" By putting -- inside the query, before WHERE I've made everything that follows ignored. So when the query is executed I will only execute the first line of the query.
answers question: http://stackoverflow.com/q/52259337
score: 2
downvote count: 0
type: Answer
upvote count: 2

http://stackoverflow.com/comment/91452332
has text: Now if you want to write 100% correct xpath then you have to save the response and write xpath according to that response body. you could refer to this https://medium.com/@yashpokar/scrape-any-website-in-the-internet-without-using-splash-or-selenium-68a6c9733369
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52245262
type: Comment

http://stackoverflow.com/comment/91288939
type: Comment
has text: Philip : I'm not that stupid Don't worry about it 1) This page will be in deep web. 2) All the content on that page is invisible.
type: QuestionComment
comment on: http://stackoverflow.com/q/52168988
score: 0

http://stackoverflow.com/comment/91186485
type: Comment
type: QuestionComment
score: 0
has text: my header is as follows: `user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0' headers = { 'User-Agent' : user_agent, 'Content-Type': 'text/html'}`
comment on: http://stackoverflow.com/q/52117204

http://stackoverflow.com/comment/91279031
comment on: http://stackoverflow.com/q/52164403
has text: @Sharku Without read it just returns a `_io.BufferReader` Object. I'm Using Python 3.6
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91239858
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/52144909
has text: Did you try it with `os.walk(u'.')`?

http://stackoverflow.com/a/52175814
type: Answer
has body: You need to distinguish between classes and instances. Once you have defined TimeCounter as a class, you can create one or many instances of it. This is done below in the assignment tc = TimeCounter(), which creates a fresh instance of TimeCounter and assigns it to the variable tc. When methods (functions) are called on instances of a class, the instance is passed to the method as a parameter, traditionally called self. So when the code below calls tc.startTime(), the self parameter in startTime will refer to the tc instance. Also, when startTime sets self.start_time_of_the_script, it is creating a new property of the tc instance - which is then read again in endTime. import time import datetime class TimeCounter: # Parentheses not necessary def startTime(self): # Note self parameter self.start_time_of_the_script = time.time() # Set a property of the instance def endTime(self): # Note self parameter end_time_of_the_script = time.time() # This is a local variable process_time_in_seconds = end_time_of_the_script - self.start_time_of_the_script print(datetime.timedelta(seconds=process_time_in_seconds)) def main(): tc = TimeCounter() # Create a fresh instance of TimeCounter and assign to tc tc.startTime() # Call method startTime on the tc instance tc.endTime() main()
upvote count: 1
has comment: http://stackoverflow.com/comment/91332572
score: 1
accepted answer of: http://stackoverflow.com/q/52175598
answers question: http://stackoverflow.com/q/52175598
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52118075
tagged with: python
has title: Vigenere Cipher syntax errors
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91188283
type: Question
has body: I am supposed to make a program that behaves likes this this: $Python vigenere.py Type a message: The crow flies at midnight! Encryption key: boom Uvs fsck rmwse bh auebwsih! Using the Vigenere Cipher I am to use a helper function and import it into this function, which I know works import string alphabet_pos = "abcdefghijklmnopqrstuvwxyz" def alphabet_position(letter): pos = alphabet_pos.index(letter.lower()) return pos def rotate(letter, rot): pos = alphabet_position(letter) new_pos = (pos + rot) % 26 new_char = alphabet_pos[new_pos] return new_char After that I began encrypting the Vigenere portion of it from helpers import alphabet_position, rotate from caesar import encrypt def encrypt(text,key): #Declare variable cipher = '' #Compute length l = len(key) #Assign value idx = 0 #Loop for i in text: #if condition satisfies if i.isalpha(): #Call method cipher += rotate_character(i,alphabet_position(key[idx])) #Update to next idx = (idx+1)%1 #Otherwise else: #Increment cipher += i #Return return cipher #Define main def main(): When I run this, it will ask me to type a message, but returns saying there are syntax errors in line 51, in &lt;module&gt; main() and line 38, in main text = input("Type a message: /n")) File "&lt;string&gt;", line 1
tagged with: vigenere
has comment: http://stackoverflow.com/comment/91188165
answer count: 1
has comment: http://stackoverflow.com/comment/91187281
score: 0
has answer: http://stackoverflow.com/a/52118586
has comment: http://stackoverflow.com/comment/91187151

http://stackoverflow.com/q/52154875
tagged with: python
tagged with: emoji
tagged with: nlp
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/91260490
has answer: http://stackoverflow.com/a/52154963
has comment: http://stackoverflow.com/comment/91260054
type: Question
has body: Is there a way to translate unicode emojis to an appropriate ascii emoticon in Python? I know the emoji library which can be used to convert unicode emojis to something like :crying_face:. But what I would need is to convert it to :'( Is there an elegant way to do this without having to translate every possible emoji manually? Another option would be to convert the ascii emojis also to their textual representation, i.e. :'( should become :crying_face:. My intermediate goal is to find a way to transform ascii and unicode emojis to a common representation. My final goal would be to replace emoticons (no matter if unicode or ascii) by the emotion they represent (if they do not represent an emotion, remove them)
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91260018
tagged with: unicode
favorite count: 0
type: UnansweredQuestion
tagged with: emoticons
has title: Translate unicode emojis to ascii emojis in Python

http://stackoverflow.com/comment/91506571
type: Comment
score: 0
has text: you always want to close the file at the end. or you use `with open('file_name.txt', 'w+') as fp` which handles the closing by himself, or if you use `fp = open('file_name.txt', 'w+')`, at the end you must call `fp.close()`
type: AnswerComment
comment on: http://stackoverflow.com/a/52258468

http://stackoverflow.com/comment/121477811
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52263169
score: 1
has text: @OneCricketeer Does this line: `for msg in consumer:` will infinitely consumes messages as written [here](https://kafka-python.readthedocs.io/en/master/usage.html#:~:text=for%20message%20in%20consumer%3A) ? If not whether wrapping this under a while True loop will work?

http://stackoverflow.com/a/52149810
score: 0
has body: A simple problem as the one you have posted, makes the language definition non regular... what this means is that there's no regex that can match a text matching some regular subexpression and be able to match the same exact string as you matched before (that is a context dependance, and as such, cannot be parsed ---demonstration available at many places--- by a regular expression/finite automaton) But all is not lost. Many of the libraries allow you to make grouping available, and so, you can create a group, and then refer to it (meaning the same string matched before) in the right part of the same regular expression. Mathematically, this is not a regular language, and the expression to match it isn't also a regular expression, but the thing works, as it was implemented in the early versions of unix. HB(...)\1* Here, a group of ther wilcard characters (any except a newline) '.' is matched, and then any sequence of 0 or more (as per the * operator) can be attached to it. This will match things like HBABCABCABCABCABCABC or HBBBABBABBABBABBA but not HBBBABBABBABB (not complete the sequence of three letters BBA) See demo The subexpression in parenthesis can be a valid regular expression. Once it is matched, it is saved to compose the rest of the regular expression, by replacing the \1 group with the matched one. You can achieve even more complicated things than that, the only requirement is that, to use a group in a regular expression, it must refer to something that has been previously matched in that same regular expression (this means that the group reference must be after the closing parenthesis that delimits that group number)
type: Answer
answers question: http://stackoverflow.com/q/52123103

http://stackoverflow.com/comment/91331229
type: Comment
type: QuestionComment
has text: @jpp You are correct, that post helped. Thanks
comment on: http://stackoverflow.com/q/52122876
score: 0

http://stackoverflow.com/comment/91299430
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52160978
has text: The difference between two Gamma distributions is not a Gamma it self - it is quite complicated. Please take a look at https://stats.stackexchange.com/questions/48378/difference-of-gamma-random-variables

http://stackoverflow.com/a/52212217
has body: word2vec in h2o-3 uses hogwild implementation - the model parameters are updated concurrently from multiple threads and it is not possible to guarantee the reproducibility in this implementation. How big is your text corpus? At the cost of a slowdown of the model training you could get reproducible result with limiting the algo to use just a single thread (h2o start-up parameter -nthread).
type: Answer
accepted answer of: http://stackoverflow.com/q/52210521
upvote count: 1
type: AcceptedAnswer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52210521

http://stackoverflow.com/comment/91328576
type: Comment
has text: There is so much wrong with this code, `If` instead of `if`, no colons, indentation. You need to go back to a tutorial and try again.
score: 2
comment on: http://stackoverflow.com/q/52189421
type: QuestionComment

http://stackoverflow.com/a/52261470
accepted answer of: http://stackoverflow.com/q/52209534
type: Answer
answers question: http://stackoverflow.com/q/52209534
upvote count: 3
has body: Thanks so much to @FelipeLema in the comments for this awesome answer! I've combined his suggestion into the previously written code to simulate natural mouse release events: from __future__ import print_function import numpy as np from mayavi import mlab from tvtk.api import tvtk ################### ### mayavi section: fig1 = mlab.figure(1) mlab.test_contour3d() mlab.title('click me') click_on = 0 def press_callback(vtk_obj, event): global click_on click_on = 1 print('pressed') def release_callback(vtk_obj, event): global click_on if click_on == 1: print('released') click_on = 0 fig1.scene.interactor.add_observer('LeftButtonPressEvent', press_callback) #fig1.scene.interactor.add_observer('LeftButtonReleaseEvent', release_callback) #doesn't work fig1.scene.interactor.add_observer('EndInteractionEvent', release_callback) #solution!! (with above setup) mlab.show()
score: 3
type: AcceptedAnswer
downvote count: 0

tkinter
tags question: http://stackoverflow.com/q/52130574
tags question: http://stackoverflow.com/q/52268570
tags question: http://stackoverflow.com/q/52208128
tags question: http://stackoverflow.com/q/52170130
tags question: http://stackoverflow.com/q/52136961
tags question: http://stackoverflow.com/q/52249421
tags question: http://stackoverflow.com/q/52267945
tags question: http://stackoverflow.com/q/52199258
tags question: http://stackoverflow.com/q/52190799
tags question: http://stackoverflow.com/q/52192333
tags question: http://stackoverflow.com/q/52136997
tags question: http://stackoverflow.com/q/52186640
tags question: http://stackoverflow.com/q/52207241
tags question: http://stackoverflow.com/q/52144361
tags question: http://stackoverflow.com/q/52183548
tags question: http://stackoverflow.com/q/52239062
tags question: http://stackoverflow.com/q/52128586
tags question: http://stackoverflow.com/q/52237533
tags question: http://stackoverflow.com/q/52145586
tags question: http://stackoverflow.com/q/52161747
tag name: tkinter
tags question: http://stackoverflow.com/q/52250213
tags question: http://stackoverflow.com/q/52234917
tags question: http://stackoverflow.com/q/52135974
tags question: http://stackoverflow.com/q/52221036
tags question: http://stackoverflow.com/q/52199454
tags question: http://stackoverflow.com/q/52263611
tags question: http://stackoverflow.com/q/52182578
tags question: http://stackoverflow.com/q/52124880
tags question: http://stackoverflow.com/q/52249092
tags question: http://stackoverflow.com/q/52138300
tags question: http://stackoverflow.com/q/52137214
tags question: http://stackoverflow.com/q/52181835
tags question: http://stackoverflow.com/q/52262705
tags question: http://stackoverflow.com/q/52210391
tags question: http://stackoverflow.com/q/52141577
tags question: http://stackoverflow.com/q/52170490
tags question: http://stackoverflow.com/q/52159749
tags question: http://stackoverflow.com/q/52149149
tags question: http://stackoverflow.com/q/52193777
tags question: http://stackoverflow.com/q/52212740
tags question: http://stackoverflow.com/q/52242756
tags question: http://stackoverflow.com/q/52228940
tags question: http://stackoverflow.com/q/52128928
tags question: http://stackoverflow.com/q/52192244
tags question: http://stackoverflow.com/q/52248402
tags question: http://stackoverflow.com/q/52248617
tags question: http://stackoverflow.com/q/52140115
tags question: http://stackoverflow.com/q/52175943
tags question: http://stackoverflow.com/q/52243906
tags question: http://stackoverflow.com/q/52240652
tags question: http://stackoverflow.com/q/52187616
tags question: http://stackoverflow.com/q/52178795
tags question: http://stackoverflow.com/q/52114259
tags question: http://stackoverflow.com/q/52158095
tags question: http://stackoverflow.com/q/52183500
tags question: http://stackoverflow.com/q/52243121
tags question: http://stackoverflow.com/q/52145232
tags question: http://stackoverflow.com/q/52226798
tags question: http://stackoverflow.com/q/52195649
tags question: http://stackoverflow.com/q/52142349
tags question: http://stackoverflow.com/q/52266674
tags question: http://stackoverflow.com/q/52138349
tags question: http://stackoverflow.com/q/52246437
tags question: http://stackoverflow.com/q/52246412
tags question: http://stackoverflow.com/q/52250125
tags question: http://stackoverflow.com/q/52201562
tags question: http://stackoverflow.com/q/52231692
tags question: http://stackoverflow.com/q/52198795
tags question: http://stackoverflow.com/q/52156160
tags question: http://stackoverflow.com/q/52164923
tags question: http://stackoverflow.com/q/52140176
tags question: http://stackoverflow.com/q/52233723
tags question: http://stackoverflow.com/q/52206465
tags question: http://stackoverflow.com/q/52122193
tags question: http://stackoverflow.com/q/52168751
tags question: http://stackoverflow.com/q/52122008
tags question: http://stackoverflow.com/q/52179223
tags question: http://stackoverflow.com/q/52121950
tags question: http://stackoverflow.com/q/52187592

http://stackoverflow.com/a/52144806
answers question: http://stackoverflow.com/q/52144245
type: Answer
has body: If you just want to save the high dimensional array in a file, then you better save it as a pickle file import numpy as np import pickle m_array = np.arange(24).reshape(4,2,3) # save as pickle file with open('filename.pickle', 'wb') as handle: pickle.dump(m_array , handle, protocol=pickle.HIGHEST_PROTOCOL) # read pickle file with open('filename.pickle', 'rb') as handle: b = pickle.load(handle) But if you want to save it as CSV file, use pandas library. You can find more details here
score: 0

http://stackoverflow.com/a/52120269
downvote count: 0
type: Answer
has body: You can put as many paths as you want to the library parameter into the section [defaults], you need just to put a colon between each path (documentation) [defaults] ... library = /foo/bar:/foo/baz
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52120179

http://stackoverflow.com/comment/91183085
type: Comment
comment on: http://stackoverflow.com/a/52116159
has text: @DongHyeokKim Just like I did in my answer.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91281835
has text: If i print dialect i have <class 'csv.Sniffer.sniff.<locals>.dialect'>
comment on: http://stackoverflow.com/a/52165924
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52209782
has body: You need to acquire the application default credentials for your project and set them as an environmental variable: Go to the Create service account key page in the GCP Console. From the Service account drop-down list, select New service account. Enter a name into the Service account name field. From the Role drop-down list, select Project > Owner. Click Create. A JSON file that contains your key downloads to your computer. Then, set an environmental variable which will provide the application credentials to your application when it runs locally: $ export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52208585
score: 1
downvote count: 0

python-datetime
tag name: python-datetime
tags question: http://stackoverflow.com/q/52257883
tags question: http://stackoverflow.com/q/52226280
tags question: http://stackoverflow.com/q/52210375
type: Tag
tags question: http://stackoverflow.com/q/52217506

http://stackoverflow.com/q/52213455
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/52214169
type: AnsweredQuestion
score: 1
tagged with: selenium
has title: Python - Questions on selenium dropbox with no option and agreement checkbox for web crawling
tagged with: web-crawler
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91377508
has body: I am trying to crawl this website. I need to: Choose one of the options for Techniques Check "I have read and agree to the following disclaimer" Click on Search button Crawl to extract web-addresses I have a few lines of code so far after a number of tries. To do parts 1 - 3, I do: browser.find_element_by_xpath("//select[@name='Techniques']/option[text()='Diversified Technique']").click() checkbox = browser.find_element_by_id("dnn_ctr5517_Clients_Custom_ctl00_cbAgree") if not checkbox.is_selected(): checkbox.click() buttons = browser.find_elements_by_xpath("//*[contains(text(), 'Search')]") if not checkbox.is_selected(): checkbox.click() This is not working. It does not give me any error but does not produce results either. Note: for Techniques, the options are li instead of options like below for "Microamperage Neural Stimulation": Microamperage Neural Stimulation How can I get those three options set and get results back? Thank you.
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52214169
tagged with: python-3.x
upvote count: 2
tagged with: python

http://stackoverflow.com/comment/91262708
type: QuestionComment
has text: Surely any PRNG will do for this. See for example: https://stackoverflow.com/questions/9023660/how-to-generate-a-repeatable-random-number-sequence the second answer down has a good solurtion
comment on: http://stackoverflow.com/q/52156031
score: 0
type: Comment

http://stackoverflow.com/a/52113683
has body: To get the header you can simply read the first line of the file using .readline() method on your file. In your case It would look something like this : f = open(filename) header = f.readline() last_col_name = header.split(',')[-1] #returns 'data from monte carlo simulation' Also if you want to look into a more versatile way storing data you can check out the pandas library.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91177991
score: 4
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/52113401
downvote count: 0
answers question: http://stackoverflow.com/q/52113401

http://stackoverflow.com/a/52239482
answers question: http://stackoverflow.com/q/52239344
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91447762
accepted answer of: http://stackoverflow.com/q/52239344
score: 5
type: AcceptedAnswer
upvote count: 6
has body: To deploy a production server, you need to set 3 things deactivate the DEBUG configuration: DEBUG = False This disable all extra function for development. define a static root directory in the settings file: STATIC_ROOT = '/this/is/a/path/to/statics' This, indicate where all the static files should be saved. run the command to collect all static files: python manage.py collectstatic This saves all statics files in the directory configured by STATIC_ROOT The official documentation for deployment: https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/#static-root-and-static-url
has comment: http://stackoverflow.com/comment/91431220

http://stackoverflow.com/a/52570022
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/52270145
has body: A solution is possible without map / apply + lambda. You can assign a list directly to a series. A list comprehension is often more efficient since pd.Series.apply is not vectorised: df = pd.DataFrame({'s': pd.Series([1, 2, 3, np.nan])}) df['t'] = [f'this is a string {i}' for i in df['s']] print(df) s t 0 1.0 this is a string 1.0 1 2.0 this is a string 2.0 2 3.0 this is a string 3.0 3 NaN this is a string nan
type: Answer

http://stackoverflow.com/q/52181161
answer count: 2
accepted answer: http://stackoverflow.com/a/52181415
downvote count: 0
has comment: http://stackoverflow.com/comment/91312279
favorite count: 0
has body: My function is executed with threads: def getdata(self, page, ...): tries = 10 for n in range(tries): try: ... datarALL = [] url = 'http://website/...'.format(...) responsedata = requests.get(url, data=data, headers=self.hed, verify=False) responsedata.raise_for_status() if responsedata.status_code == 200: # 200 for successful call ... if ... break except (ChunkedEncodingError, requests.exceptions.HTTPError) as e: print ("page #{0} run #{1} failed. Returned status code {2}. Reason: {3}. Msg: {4}. Retry.".format(page, n, responsedata.status_code, responsedata.reason, sys.exc_info()[0])) if n == tries - 1: print ("page {0} could not be imported. Max retried reached.".format(page)) os._exit(1) #One thread max retried - close all threads and return datarALL as follows: with ThreadPoolExecutor(max_workers=num_of_workers) as executor: futh = [(executor.submit(self.getdata, page,...)) for page in pages] for data in as_completed(futh): datarALL.extend(data.result()) print ("Finished generateing data.") return datarALL Sometimes I get unexpected exceptions like: ConnectionResetError: [Errno 104] Connection reset by peer which shuts down my program. I want to change my code so that no matter which exception happens the thread will allways retry untill the if n == tries - 1: is met. I don't want my thread to shut down due to random exception. I read the request exceptions info page but I don't see how I can catch all the exceptions without manually listing all of them. Is there a generic way to do this? Basicly I want something like: except (ALL EXCEPTIONS from Requests) as e: print ("page #{0} run #{1} failed. Returned status code {2}. Reason: {3}. Msg: {4}. Retry.".format(page, n, responsedata.status_code, responsedata.reason, sys.exc_info()[0])) if n == tries - 1: print ("page {0} could not be imported. Max retried reached.".format(page)) os._exit(1) #One thread max retried - close all threads and return datarALL How can I do that? EDIT: using except Exception as e: print (…
upvote count: 2
has comment: http://stackoverflow.com/comment/91312318
possible better answer: http://stackoverflow.com/a/64877125
has comment: http://stackoverflow.com/comment/91312569
has answer: http://stackoverflow.com/a/64877125
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91312750
has answer: http://stackoverflow.com/a/52181415
tagged with: python-requests
has comment: http://stackoverflow.com/comment/91312464
has comment: http://stackoverflow.com/comment/91312667
has comment: http://stackoverflow.com/comment/91312342
type: Question
has comment: http://stackoverflow.com/comment/91312254
has comment: http://stackoverflow.com/comment/91312384
has title: handling exceptions from python requests

http://stackoverflow.com/q/52122876
has comment: http://stackoverflow.com/comment/91197213
favorite count: 0
has comment: http://stackoverflow.com/comment/91197717
tagged with: python
tagged with: python-3.x
tagged with: list
accepted answer: http://stackoverflow.com/a/52122915
has comment: http://stackoverflow.com/comment/91331172
downvote count: 3
score: -3
type: AnsweredQuestion
has title: Pythonic way performing split on all elements of a list
has comment: http://stackoverflow.com/comment/91197063
type: Question
has body: I want to end up with a list that contains the first elements of a split on all items of a list. That is. input_list = [‘A1 - Some Text’, ‘A2 - Other Text’] should result as output_list = [‘A1’, ‘A2’]. What is the most Pythonic (clever) way of doing this? Extra points for not needing multiple list variables. UPDATE: Updating with my initial attempt: input_list = [‘A1 - Some Text’, ‘A2 - Other Text’] output_list = [] for element in input_list: output_list.append(element.split(' - ')[0]))
tagged with: split
upvote count: 0
linked to: http://stackoverflow.com/q/6696027
has answer: http://stackoverflow.com/a/52122915
answer count: 1
has comment: http://stackoverflow.com/comment/91331229

http://stackoverflow.com/a/69514930
upvote count: 9
type: Answer
has comment: http://stackoverflow.com/comment/138913146
score: 8
has comment: http://stackoverflow.com/comment/134475148
has comment: http://stackoverflow.com/comment/129493680
has comment: http://stackoverflow.com/comment/129500536
downvote count: 1
answers question: http://stackoverflow.com/q/52232177
has body: I have a production-hardened technique to prevent both these errors: RuntimeError: Timeout context manager should be used inside a task, RuntimeError: This event loop is already running The idea is to have a dedicated background thread that plays the event-loop, like in a traditional UI setting, however here it's not for UI messages but for API messages (i.e. requests). We start that thread once (upon import of the module, but wherever really). Furthermore, we only call asyncio_run instead of asyncio.run and asyncio_gather instead of asyncio.gather. Here you go: import asyncio import threading from typing import Awaitable, TypeVar T = TypeVar("T") def _start_background_loop(loop): asyncio.set_event_loop(loop) loop.run_forever() _LOOP = asyncio.new_event_loop() _LOOP_THREAD = threading.Thread( target=_start_background_loop, args=(_LOOP,), daemon=True ) _LOOP_THREAD.start() def asyncio_run(coro: Awaitable[T], timeout=30) -> T: """ Runs the coroutine in an event loop running on a background thread, and blocks the current thread until it returns a result. This plays well with gevent, since it can yield on the Future result call. :param coro: A coroutine, typically an async method :param timeout: How many seconds we should wait for a result before raising an error """ return asyncio.run_coroutine_threadsafe(coro, _LOOP).result(timeout=timeout) def asyncio_gather(*futures, return_exceptions=False) -> list: """ A version of asyncio.gather that runs on the internal event loop """ async def gather(): return await asyncio.gather(*futures, return_exceptions=return_exceptions) return asyncio.run_coroutine_threadsafe(gather(), loop=_LOOP).result()

http://stackoverflow.com/q/52241126
has comment: http://stackoverflow.com/comment/91430899
has title: i want to take input from users as a list but i get an error
score: -1
accepted answer: http://stackoverflow.com/a/52241220
has comment: http://stackoverflow.com/comment/91430853
has answer: http://stackoverflow.com/a/52241168
answer count: 3
favorite count: 0
tagged with: input
tagged with: python
has answer: http://stackoverflow.com/a/52241220
has body: lst = int( input("Enter list values : ")) def count(lst): even = 0 odd = 0 for i in lst: if i%2 ==0: even+=1 else: odd+=1 return even,odd print(even,odd) even,odd = count(lst) print("Even : () Odd : () :".format(even,odd))
possible better answer: http://stackoverflow.com/a/52241156
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52241156
downvote count: 1
type: Question
upvote count: 0

http://stackoverflow.com/a/52149551
score: -1
answers question: http://stackoverflow.com/q/52148131
has comment: http://stackoverflow.com/comment/91256853
downvote count: 1
type: Answer
upvote count: 0
has comment: http://stackoverflow.com/comment/91249415
has body: Create folder, name it static copy CSS,JS to that NOT HTML it should remain in the templates directory and Change the STATIC_URL = '/templates/' to STATIC_URL = '/static/'. This is how Django manages the static files(CSS,JS,IMAGES). Check this out for more information https://docs.djangoproject.com/en/2.1/howto/static-files/

http://stackoverflow.com/a/52230780
accepted answer of: http://stackoverflow.com/q/52229876
answers question: http://stackoverflow.com/q/52229876
type: Answer
score: 3
has body: Okay guys I finally figured out wtf to do! In Python, I sent the data as an octet stream using the requests library as a "PUT". I did this by reading as binary like so: data = open(path_to_watch+filename, "rb").read() and then sending the data using the requests library like this: response= requests.request("PUT", URL, data=data, headers={'Content-Type': 'application/octet-stream'}) So far so good? On the Node JS side I used the "stream" library built into node along with filesystem. var fs = require('fs'); var stream = require('stream'); app.put("/", function (req, res) { var wstream = fs.createWriteStream("output.bin"); req.on('data', function(data){ wstream.write(data); }) req.on('end', () =&gt;{ wstream.end(); }) res.status(200).send({ message: 'File recieved' }); }; Hope someone else doesn't have to spend 7 hours debugging like I did :P
upvote count: 3
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/52137861
has body: Here you go: In [4]: a Out[4]: array([[11, 12, 13, 14], [15, 16, 17, 18], [19, 20, 21, 22]]) In [5]: a[0] Out[5]: array([11, 12, 13, 14]) In [6]: a[1] Out[6]: array([15, 16, 17, 18]) In [7]: a[2] Out[7]: array([19, 20, 21, 22]) In [9]: a[0].reshape(2,2).T Out[9]: array([[11, 13], [12, 14]]) In [13]: for i in a: ...: print(i.reshape(2,2).T) ...: ...: [[11 13] [12 14]] [[15 17] [16 18]] [[19 21] [20 22]]
score: 0
answers question: http://stackoverflow.com/q/52137832
type: Answer
has comment: http://stackoverflow.com/comment/91225485

http://stackoverflow.com/comment/91269408
score: 0
has text: http://www.ffmpeg-archive.org/Extracting-I-P-B-frames-from-a-mpg-video-td4668751.html
comment on: http://stackoverflow.com/q/52158553
type: Comment
type: QuestionComment

subprocess
tags question: http://stackoverflow.com/q/52119241
tag name: subprocess
tags question: http://stackoverflow.com/q/52235799
tags question: http://stackoverflow.com/q/52156700
tags question: http://stackoverflow.com/q/52145830
tags question: http://stackoverflow.com/q/52151881
tags question: http://stackoverflow.com/q/52268570
tags question: http://stackoverflow.com/q/52120227
tags question: http://stackoverflow.com/q/52268778
tags question: http://stackoverflow.com/q/52245068
tags question: http://stackoverflow.com/q/52243509
tags question: http://stackoverflow.com/q/52116952
tags question: http://stackoverflow.com/q/52151016
tags question: http://stackoverflow.com/q/52164403
type: Tag
tags question: http://stackoverflow.com/q/52271243
tags question: http://stackoverflow.com/q/52231021
tags question: http://stackoverflow.com/q/52169226
tags question: http://stackoverflow.com/q/52241961
tags question: http://stackoverflow.com/q/52121686
tags question: http://stackoverflow.com/q/52191797

http://stackoverflow.com/comment/91442115
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52244588
has text: Try to use CSS path, which is faster than Xpath.

http://stackoverflow.com/comment/91203120
type: Comment
has text: Works fine for me. Would you mind updating your question with the input data (not a dropbox link since those go dead eventually) and also what your desired output is? Troughs and peaks have multiple definitions, and knowing exactly what you want will be helpful.
type: AnswerComment
comment on: http://stackoverflow.com/a/52125419
score: 0

http://stackoverflow.com/q/52173064
has body: Im new to Python, so I execute this code: test1 = np.array([95, 91, 104, 93, 85, 107, 97, 90, 86, 93, 86, 90, 88, 89, 94, 96, 89, 99, 104, 101, 84, 84, 94, 87, 99, 85, 83, 107, 102, 80, 89, 88, 93, 101, 87, 100, 82, 90, 106, 81, 95]) plt.hist(test1) plt.show() And get this image: After I normalize data and check the plot again: plt.gcf().clear() test2 = preprocessing.normalize([test1]) plt.hist(test2) plt.show() The new plot has different shape and on the histagram I see that every number represents once, which looks strange for me comparing to first plot. So I expect smth similat to first plot, but with range from 0 to 1. Where am I mistaking?
type: AnsweredQuestion
has title: plt.hist showing the strange plot after preprocessing.normalize
type: Question
has answer: http://stackoverflow.com/a/52173261
answer count: 1
downvote count: 0
tagged with: histogram
score: 1
tagged with: scikit-learn
tagged with: normalize
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/52173261
upvote count: 1

http://stackoverflow.com/comment/91299685
type: Comment
type: QuestionComment
has text: Why do you need the headers? What are you aiming to sort the data into?
score: 1
comment on: http://stackoverflow.com/q/52174371

http://stackoverflow.com/q/52197656
downvote count: 1
has title: Algorithm of searching for a pair of integers in a list
has body: I'm quite new to algorithm and I encountered a question to which my approach does not works properly. Here's the precondition: You are given a list L=[(a1,b1),…,(an,bn)] of n pairs of integers. For any two pairs (ai,bi)∈L and (aj,bj)∈L such that 1≤i≤j≤n , we have (at least) one of three cases: ai=aj and bi=bj ai &lt; aj bi &lt; bj For example, the list L=[(1,2),(1,1)] would not be valid. An example of a valid list is: L = [(0,1), (1, 0), (0, 1), (1, 1), (1, 2), (3, 1), (3, 1), (2, 2), (2, 3), (3, 2), (2, 3), (4, 3), (3, 4), (4, 4), (4, 5), (5, 5)] The question is: Write a recursive function that applies the divide-and-conquer paradigm to search if a given pair of values (x, y) is in L. The following is my python code which doesn't work as expected: def pair_search(l, p): found = False calls = 1 if len(l) == 0: return found, calls if len(l) == 1: if l[0] == p: found = True return found, calls mid = len(l) // 2 if p == l[mid]: found = True return found, calls elif (l[mid][0] == p[0] and l[mid][1] == p[1]) or l[mid][0] &lt; p[0] or l[mid][1] &lt; p[1]: f, c = pair_search(l[mid + 1:], p) else: f, c = pair_search(l[:mid], p) found = f or found calls += c return found, calls
type: AnsweredQuestion
tagged with: list
tagged with: algorithm
score: 1
has comment: http://stackoverflow.com/comment/91344723
type: Question
has answer: http://stackoverflow.com/a/52198401
tagged with: divide-and-conquer
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52198401
favorite count: 0
upvote count: 2

http://stackoverflow.com/comment/91391148
type: AnswerComment
has text: Sorry cant upvote cause my reputation is too low. Anyways thanks for your input on this.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52220373

http://stackoverflow.com/a/52252780
answers question: http://stackoverflow.com/q/52252449
has comment: http://stackoverflow.com/comment/91453535
has comment: http://stackoverflow.com/comment/91453409
has comment: http://stackoverflow.com/comment/91453198
type: Answer
has body: If want to use python3, use pip3 instead of pip: pip3 install numpy You can try these too in terminal: rm -Rf env virtualenv -p python3 env source env/bin/activate python3 -m pip install --upgrade pip pip3 install numpy Also make sure that the first line of your script is #!/usr/bin/python3 Don't write anything, even comments, before this.
upvote count: 1
has comment: http://stackoverflow.com/comment/91453223
score: 1
downvote count: 0

http://stackoverflow.com/comment/91639684
type: QuestionComment
has text: What scope is your `my()` function in? What class? Where is it getting `self` from? Judging by the error, the function is being passed a context as the first parameter, which tells me that the context into `self`, and then erroring when it isn't also passed a `ctx`
comment on: http://stackoverflow.com/q/52176124
score: 0
type: Comment

http://stackoverflow.com/a/52250604
answers question: http://stackoverflow.com/q/52250564
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52250564
type: Answer
score: 3
downvote count: 0
has body: It looks like you want to have a dictionary where every fourth element in listA is a member of listB. You can do this using python's list slicing, and using a generator function: s = len(listB) output = {listB[i]: listA[i::s] for i in range(s)} This should be fairly straightforward. The fancy list slicing thing is listA[i::s], which takes every sth element of listA, starting from the ith element.
type: AcceptedAnswer

http://stackoverflow.com/comment/91246226
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52148234
has text: "Not the dirty way"? This is far dirtier than the OP's solution. You can't make code better by making it less DRY.
type: AnswerComment

nextion
tags question: http://stackoverflow.com/q/52124677
type: Tag
tag name: nextion

http://stackoverflow.com/comment/91459309
comment on: http://stackoverflow.com/q/52255642
score: 0
has text: @JJJ, but I did try the ones that seemed most likely to work. I tried many different ways before asking this question. I asked this question because none of the solutions in any of the questions I entered solved my problem, except the one I just marked. Please understand, no hate
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91523704
comment on: http://stackoverflow.com/q/52262430
has text: The solution is in here. https://stackoverflow.com/questions/52156388/how-do-i-select-items-from-a-drop-down-box-in-selenium-using-python/52157900#52157900
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52179857
favorite count: 0
tagged with: tensorflow-datasets
has body: I have a bunch of JSON array files (AVRO to be accurate) and each of them yield multiple samples for training a Keras Model. Using ideas from @GPhilo and from @jsimsa, I was able to come up with this to parallelize my input pipeline. Unable to figure out how to design the generator(n) to divide the work of processing files. The code fails inside parse_file(f) as the function expects a string file path and not a Tensor, N = num_cores = 2 files_to_process = ["f1.avro", "f2.avro", "f3.avro"] shuffle_size = prefetch_buffer = 1000 batch_size = 512 def generator(n): size = math.ceil(len(files_to_process) / N) start_index = n * size end_index = start_index + size def gen(): # for f in files_to_process[start_index:end_index]: for f in tf.slice(files_to_process, start_index, size): yield f return gen def dataset(n): return tf.data.Dataset.from_generator(generator(n), (tf.string,)) def process_file(f): examples_x, examples_y = parse_file(f) return examples_x, examples_y ds = tf.data.Dataset.range(N) ds = ds.apply(tf.contrib.data.parallel_interleave(dataset, cycle_length=N)) ds = ds.map(process_file, num_parallel_calls=N) ds = ds.prefetch(prefetch_buffer) ds = ds.flat_map(lambda *x: tf.data.Dataset.from_tensor_slices(x)) ds = ds.batch(batch_size).shuffle(shuffle_size) ... myTfKerasModel.fit( ds.make_one_iterator(), NUM_TRAIN_SAMPLES // batch_size ) What is the correct way to design generator(n) here Is this an optimized way to design my input pipeline using parallel_interleave and flat_map
tagged with: python
has comment: http://stackoverflow.com/comment/91311543
type: AnsweredQuestion
score: 7
upvote count: 7
has answer: http://stackoverflow.com/a/52185891
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/47411383
linked to: http://stackoverflow.com/q/47086599
downvote count: 0
tagged with: keras
answer count: 1
accepted answer: http://stackoverflow.com/a/52185891
has title: Parallelize tf.from_generator using tf.contrib.data.parallel_interleave
has comment: http://stackoverflow.com/comment/91310273

http://stackoverflow.com/comment/91462956
comment on: http://stackoverflow.com/a/52257181
type: AnswerComment
has text: Okay well. I couldn't figure out how to install 3.6, and I felt like 3,5 will suffice. Now that you told me I needed it, I figured out how to install it, and now it works. I'm sorry for wasting your time...
score: 0
type: Comment

http://stackoverflow.com/a/52118531
has comment: http://stackoverflow.com/comment/91191510
type: Answer
answers question: http://stackoverflow.com/q/52118382
score: 0
has comment: http://stackoverflow.com/comment/91189974
has body: You could try this - lst = [re.sub('[=" ]$', '', i) for i in re.findall('(http.?://[^\s]+)', text)] You can just add more characters that you want to replace in your sub according to your requirements

http://stackoverflow.com/q/52145782
has body: I'm using OLS with respect to two dataframes: gab = ols(formula= 'only_volume ~ all_but_volume', data=data_p ).fit() where, only_volume = data_p.iloc[:,0] #Only first colum all_but_volume = data_p.iloc[:, 1:data_p.shape[1]] #All but first column When I try to extract something, say parameter or pvals, I get something like this: In [3]: gab.params Out[3]: Intercept 2.687598e+06 all_but_volume[0] 5.500544e+01 all_but_volume[1] 2.696902e+02 all_but_volume[2] 3.389568e+04 all_but_volume[3] -2.385838e+04 all_but_volume[4] 5.419860e+02 all_but_volume[5] 3.815161e+02 all_but_volume[6] -2.281344e+04 all_but_volume[7] 1.794128e+04 ... all_but_volume[22] 1.374321e+00 Since gab.params provides with 23 values in LHS and all_but_volume has 23 columns, I was hoping if there was a way to get a list/zip of params with column names, instead of params with all_but_volume[i] Like, TMC 9.801195e+01 TAC 2.214464e+02 ... What I've tried: removing all_but_volume and simply using data_p.iloc[:, 1:data_p.shape[1]] Didn't work: ... data_p.iloc[:, 1:data_p.shape[1]][21] 2.918531e+04 data_p.iloc[:, 1:data_p.shape[1]][22] 1.395342e+00 Edit: Sample Data: data_p.iloc[1:5,:] Out[31]: Volume A B C\ 1 569886.171878 759.089217 272.446022 4.163908 2 561695.886128 701.165406 330.301260 4.136530 3 627221.486089 377.746089 656.838394 4.130720 4 625181.750625 361.489041 670.575110 4.134467 D E F G H I \ 1 1.000842 12993.06 3371.28 236.90 4.92 6.13 2 0.981514 13005.44 3378.69 236.94 4.92 6.13 3 0.836920 13017.22 3384.47 236.98 4.93 6.13 4 0.810541 13028.56 3388.85 237.01 4.94 6.13 J K L M N \ 1 ... 0 0 0 0 0 2 ... 0 0 0 0 0 3 ... 0 0 0 0 0 4 ... 0 0 0 0 0 O P Q R S 1 0 0 0 1 9202.171648 2 0 0 0 0 4381.373520 3 0 0 0 0 -13982.443554 4 0 0 0 0 -22878.843149 only_volume is the first column 'volume' all_but_volume is all columns except 'volume'
type: Question
has title: Getting list of column names and coeff in ols.param
score: 3
has answer: http://stackoverflow.com/a/52146409
accepted answer: http://stackoverflow.com/a/52146409
tagged with: pandas
tagged with: least-squares
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91241888
favorite count: 0
has comment: http://stackoverflow.com/comment/91275229
tagged with: python
has comment: http://stackoverflow.com/comment/91275214
has comment: http://stackoverflow.com/comment/91242243
type: AnsweredQuestion
tagged with: linear-regression
upvote count: 3

http://stackoverflow.com/comment/91236029
type: Comment
has text: I suspect imwrite expects a uint8 on range 0-255. That's what I'd try first. Provided `ab.min()` is about -1 and `ab.max()` is about 1, try `ab = ((ab-ab.min())/2.0*255.0).astype('uint8')`. You may need an axis parameter in the `min`. I don't have python on this computer to check right now. To debug, also try beforehand to replicate your previous additive blending result using masking and broadcasting. These principles are the way to do it fast.
comment on: http://stackoverflow.com/a/52143032
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91284759
comment on: http://stackoverflow.com/a/52149227
has text: Can you provide an example where the solution is wrong without `{"bland": True}`?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91497127
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52264891
has text: yeap I get it. It took me for a while to understand where when wrong.
type: Comment

http://stackoverflow.com/q/52251406
linked to: http://stackoverflow.com/q/52249076
type: Question
tagged with: visual-studio-code
has title: Appengine VSCode can't debug Python main.py
has comment: http://stackoverflow.com/comment/91584863
score: 3
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: google-app-engine
tagged with: python
has body: I'm trying to get VSCode debugging a Google Appengine script. I followed the specific instructions on the VSCode web site for Pythong Appengine Debugging where I start the build process. Then I attach the debugger to the remote session. Whenever I attach, I get these errors. The call stack and the debug sidebar remain blank. The error: Executing task in folder project-impact: python /Users/admin/bin/google_appengine/dev_appserver.py --python_startup_script=/Users/admin/project-impact/pydev_startup.py --automatic_restart=no --datastore_path=/Users/admin/project-impact-devfiles/project-impact.rbm --max_module_instances=default:1 /Users/admin/project-impact/out/app.yaml INFO 2018-09-09 06:53:41,905 devappserver2.py:120] Skipping SDK update check. INFO 2018-09-09 06:53:42,393 api_server.py:274] Starting API server at: http://localhost:63926 INFO 2018-09-09 06:53:42,508 dispatcher.py:270] Starting module "default" running at: http://localhost:8080 INFO 2018-09-09 06:53:42,510 admin_server.py:152] Starting admin server at: http://localhost:8000 /Users/admin/google-cloud-sdk/platform/google_appengine /Users/admin/google-cloud-sdk/platform/google_appengine/lib/concurrent /Users/admin/google-cloud-sdk/platform/google_appengine/lib/cherrypy /Users/admin/google-cloud-sdk/platform/google_appengine/lib/fancy_urllib /Users/admin/google-cloud-sdk/platform/google_appengine/lib/ipaddr /Users/admin/google-cloud-sdk/platform/google_appengine/lib/protorpc-1.0 /Users/admin/google-cloud-sdk/platform/google_appengine/lib/yaml-3.10 /Users/admin/google-cloud-sdk/platform/google_appengine /Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7 /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages /Library/Frameworks/Python.framework/V…
answer count: 0
upvote count: 3

redis
tags question: http://stackoverflow.com/q/52198908
tags question: http://stackoverflow.com/q/52248966
tags question: http://stackoverflow.com/q/52176053
tags question: http://stackoverflow.com/q/52164846
tags question: http://stackoverflow.com/q/52168852
type: Tag
tag name: redis

http://stackoverflow.com/comment/91290359
score: 0
type: Comment
type: QuestionComment
has text: Can you guarantee that there's exactly one dict with the `"Value"` key in it in each item's `Tags`?
comment on: http://stackoverflow.com/q/52169903

http://stackoverflow.com/a/52123795
answers question: http://stackoverflow.com/q/52123778
has comment: http://stackoverflow.com/comment/91198811
score: 1
upvote count: 1
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91198847
has body: IIUC, you can do this rather than iterating through your frame with iterrows: df = df[df.email.str.endswith('.com')] which returns: &gt;&gt;&gt; df email 0 abc@gmail.com 1 cde@gmail.com 3 sldkslk@sss.com Or, for larger dataframes, it's sometimes faster to not use the str methods provided by pandas, but just to do it in a plain list comprehension with python's built in string methods: df = dfi.endswith('.com') for i in df.email

http://stackoverflow.com/a/52130980
type: Answer
accepted answer of: http://stackoverflow.com/q/52130902
score: 3
answers question: http://stackoverflow.com/q/52130902
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91212676
has comment: http://stackoverflow.com/comment/91212369
has body: Here was my old solution to the problem def minion_game(string): vowels = {'A','E','I','O','U'} kevin = 0 stuart = 0 for i in range(len(string)): if string[i] in vowels: kevin += len(string) - i else: stuart += len(string) - i if kevin == stuart: print("Draw") elif kevin &gt; stuart: print("Kevin " + str(kevin)) else: print("Stuart " + str(stuart)) The trick is to realize you don't need to try every combination. Once you see the vowel or consonant you can be sure that there is the length of the current string sub strings left, so you can just add that many points So for example, given the word Banana, we see a B and we immediately know that {B, BA, BAN, BANA, BANAN, BANANA} are all going to give points to Stuart. No need to keep checking

http://stackoverflow.com/a/52177345
type: Answer
answers question: http://stackoverflow.com/q/52175881
has comment: http://stackoverflow.com/comment/91477305
score: 0
has body: For the python downloaded form the official webpage you should be able to remove it from you applications on macOS. If you are on windows I found this reference. If you are trying to remove a version via anaconda use the conda remove -n command. More details here. To upgrade you can use conda upgrade python for the most recent version available. To see what is available you can do a conda search

http://stackoverflow.com/comment/91431396
has text: It works! Thank you so much!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52237342
type: Comment

http://stackoverflow.com/comment/91485162
score: 1
comment on: http://stackoverflow.com/a/52268802
type: AnswerComment
type: Comment
has text: The first option is shorter and straightforward, but I do want dict_one updated 'in-place' as your second option does. Your code works, and I appreciate your help.

http://stackoverflow.com/comment/91307362
type: Comment
has text: Can you reproduce this consistently across multiple runs? If so, I would also head over to the TensorFlow GitHub and open an issue. To me the code seems fine (especially, since it trains well in the beginning... One question might be what values for learning rate and decay you are using. I suspect numerical instabilities at some point.
type: QuestionComment
comment on: http://stackoverflow.com/q/52178578
score: 0

http://stackoverflow.com/q/52251023
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/52251043
tagged with: pandas
has answer: http://stackoverflow.com/a/52251106
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91449790
possible better answer: http://stackoverflow.com/a/52251106
tagged with: datetime
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
has title: Creating datetime object in pandas from out of order dates
type: Question
accepted answer: http://stackoverflow.com/a/52251043
has body: I have a dataframe in pandas that looks like this Year Month Month_index Rainfall 1900 Jan 1 4.8 1901 Jan 1 5 . . . 1900 Feb 2 3.2 1901 Feb 2 4.3 . . To use datetime indexing I need to rearrange it to look like - Year Month Month_index Rainfall 1900 Jan 1 4.8 1900 Feb 2 3.2 . . 1901 Jan 1 5 1901 Feb 2 4.3 . . Of course there are the full 12 months I'm just showing a little bit for brevity. I'm reasonably new to python so I don't know if there is a command that will do this. Thank you in advance! edit: Here is the code I'm using to get thus far - import csv #import pyexcel-io as pi import numpy as np import pandas as pd import dateutil #Read data from csv file into dataframe df =pd.read_csv('/Users/Gingeraffe/Documents/University/3rd_year/Bureau_Research/Notebooks/Data/rainfall_SW_WA.csv') months = df.columns[1:] #Melt is putting months down a column and the data down another column. Problem is ' jan jan jan... feb feb feb..' etc. instead of 'jan feb mar.. etc' df = pd.melt(df, id_vars='Year', value_vars=months, var_name='Month') df.insert(2,'Month_index',0) M = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'June':6, 'July':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12} df.Month_index = df.Month.map(M)

http://stackoverflow.com/comment/94915331
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52189736
has text: Quoting PEP8: "Also, beware of writing `if x` when you really mean `if x is not None` -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!"
type: AnswerComment

http://stackoverflow.com/comment/91476479
comment on: http://stackoverflow.com/a/52263246
type: AnswerComment
score: 0
has text: Tried that but now "name 'Results' is not defined"
type: Comment

http://stackoverflow.com/q/52240887
has comment: http://stackoverflow.com/comment/91431148
type: AnsweredQuestion
has body: There are many posts on this topic but unfortunately the solution provided (using loc) is not working for me. In my dataset, I have feature 'GarageYrBlt' which is the year in which the garage was built; and another feature 'YearBuilt' which is the year in which the house was built. The GarageYrBlt has some null values. since GarageYrBlt and YearBuilt are strongly correlated, I am trying to replace the null values of GarageYrBlt by corresponding values of YearBuilt. df.GarageYrBlt[df.GarageYrBlt.isnull()] = df.YearBuilt[df.GarageYrBlt.isnull()] This gave the warning "A value is trying to be set on a copy of a slice from a DataFrame" So I tried the .loc method as shown below, but no change. I still get the same error. Any suggestions? df.loc[:,"GarageYrBlt"][df.GarageYrBlt.isnull()] = df.loc[:,"YearBuilt"][df.GarageYrBlt.isnull()].copy()
tagged with: dataframe
tagged with: slice
has answer: http://stackoverflow.com/a/52241470
type: Question
has comment: http://stackoverflow.com/comment/91430451
accepted answer: http://stackoverflow.com/a/52241470
answer count: 1
score: 0
tagged with: pandas
has title: copy of a slice from a DataFrame warning, loc method not working
tagged with: isnull
tagged with: python

http://stackoverflow.com/comment/91218297
comment on: http://stackoverflow.com/q/52133976
type: Comment
has text: By the way, logic of your tutorial function is wrong, pressing anything but 'y', including 'n' will start the loop over.
score: 0
type: QuestionComment

http://stackoverflow.com/q/52249107
tagged with: discord.py
has answer: http://stackoverflow.com/a/52249187
has body: I have looked before deciding to make this post. I have tried some codes from answers, but they have not worked for me. Note that I am new with coding in general; I started using Python for about a week now. I managed to code my Discord bot to generate random images from one command, however I don't think I made it correctly. The images are sent at random, but their links show in the bot's messages. Here is the code I have for it: client = Bot(command_prefix=BOT_PREFIX) @client.event async def on_message(message): if message.content.upper().startswith("?DOG"): jessie1 = "https://cdn.discordapp.com/attachments/432563417887277060/484484259386621993/22B25E7A-3157-4C23-B889-47ECFE8A15A9.jpg" snowy = "https://cdn.discordapp.com/attachments/487045791697862666/487390822485065749/824B6151-E818-49A4-A564-C2C752ED6384.jpg" await client.send_message(message.channel, random.choice([snowy, jessie1])) I am using two images as examples for now as there are a lot more that I do not want to include all at once. I am able to generate these two images at random by using one command, but I don't know how to code so that their links won't appear in the bot's message as it sends the images. I want to know if there is a way to do so without making a huge change to the code that I have at this moment. However, if there is an efficient/correct way of doing it, I will gladly take your advice for better experience. If all goes well, I would also like to add a message for the bot to say when it sends those images. I do have an idea on how to do so, but I need to solve my first issue first xD
has answer: http://stackoverflow.com/a/52249404
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/91446757
has comment: http://stackoverflow.com/comment/91447801
has title: how to code my bot to generate random images from one command
has answer: http://stackoverflow.com/a/55248679
has comment: http://stackoverflow.com/comment/91446890
has comment: http://stackoverflow.com/comment/91447383
accepted answer: http://stackoverflow.com/a/52249404
tagged with: python
has comment: http://stackoverflow.com/comment/91447212
type: AnsweredQuestion
type: Question
possible better answer: http://stackoverflow.com/a/52249187

http://stackoverflow.com/comment/91404285
type: AnswerComment
has text: "however numbers always refer to a new object" - not true. It is unspecified whether evaluating a numeric literal will produce a new object. In the standard implementation of Python, it happens to be the case that every evaluation of a `10` literal will produce the same int object.
type: Comment
comment on: http://stackoverflow.com/a/52227422
score: 1

wagtail
tag name: wagtail
tags question: http://stackoverflow.com/q/52214109
tags question: http://stackoverflow.com/q/52248562
tags question: http://stackoverflow.com/q/52240962
type: Tag

http://stackoverflow.com/a/52194330
has comment: http://stackoverflow.com/comment/91338483
score: 0
has body: The list addition operator is defined only on two lists, not on a list and an integer. Python was trying to do a list.__add__ on prime_factors and i, which includes iterating through the elements of i. That's where you got the error. The correct command would be prime_factors.append(i) With that change, your program correctly prints only the lowest prime factor. You also need to move your initializations and checks to the proper places: set prime_factors to the empty list only at the start of your program. set counter back to 0 for each suspected prime factor. check the value of counter only after you've looked at all smaller numbers.
type: Answer
answers question: http://stackoverflow.com/q/52194302

http://stackoverflow.com/comment/91315649
has text: Could you provide some example data, and some code attempt? It will be quite helpful to understand the question
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52176612
score: 1

oauth-2.0
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/52264145
type: Tag
tags question: http://stackoverflow.com/q/52113589

http://stackoverflow.com/comment/92734045
has text: I've made an issue on GitHub: https://github.com/keras-team/keras/issues/11438
type: Comment
comment on: http://stackoverflow.com/q/52267297
score: 0
type: QuestionComment